How to Delete Records of an sObject using PageBlockTable in Visualforce page

By | November 1, 2019

Hi, In this scenario we have shown how to delete the records using pageblocktable in visualforce page. Here we used ‘apex:param’ for transmitting individual record ids from vf to apex class…. we used custom controller to perform delete action, and pageBlockTable to display records and command link to delete individual records.

Apex Controller

public with sharing class DeleteRecords{    
    public String sId{get;set;}
    
    List<Student__c> dlt = new List<Student__c>();    
    public List<Student__c> getRecords() {
        dlt =[select id,name,city__c,country__c,phone__c from Student__c];
        return dlt;
    }   
    
    Student__c StuDlt = new Student__c();    
    public PageReference RecDelete() {
        StuDlt=[select Id from Student__c where id =:sId];
        delete StuDlt;
        pagereference ref=new pagereference('/apex/DeleteRecords');
        ref.setredirect(true);
        return ref;
    }
}

Vf Page

<apex:page controller="DeleteRecords" sidebar="false">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockSection >
                <apex:pageBlockTable value="{!records}" var="s">
                    <apex:column headerValue="Action">
                        <apex:commandlink value="Delete" action="{!RecDelete}">
                            <apex:param name="sId" value="{!s.Id}" assignTo="{!sId}"/>
                        </apex:commandlink>
                    </apex:column>
                    <apex:column headerValue="Name">
                        {!s.name}
                    </apex:column>
                    <apex:column headerValue="city">
                        {!s.City__c}
                    </apex:column>
                    <apex:column headerValue="phone">
                        {!s.Phone__c}
                    </apex:column>
                    <apex:column headerValue="country">
                        {!s.Country__c}
                    </apex:column>
                </apex:pageBlockTable>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Output

If we click on delete, the record gets deleted…
Share this...
Share on Facebook
Facebook
Email this to someone
email

Leave a Reply

Your email address will not be published.