Activity Forums Salesforce® Discussions How to delete a lookup record in vf page on clicking a custom button in Salesforce?

  • Yogesh

    Member
    December 2, 2019 at 7:01 am

    Hello,

    I have written code for deleting selected contacts.

    Apex Controller:-

    public class WrapperDeleteContactsAccounts
    {
    List<WrapContacts> conListWrap ;
    List<Account> accounts ;
    List<Contact> contacts ;
    List<Contact> delContacts;
    public WrapperDeleteContactsAccounts()
    {
    conListWrap = new List<WrapContacts>();
    accounts = new List<Account>();
    contacts = new List<Contact>();
    delContacts = new List<Contact>();
    }
    public class WrapContacts
    {
    public Contact con {get;set;}
    public Boolean check {get;set;}
    public WrapContacts(Contact c)
    {
    con = c;
    check = false;
    }
    }
    public List<WrapContacts> getContacts()
    {
    contacts = [SELECT Id, LastName, AccountId, Gender__c FROM Contact LIMIT 100];
    for(Contact c : contacts)
    {
    conListWrap.add(new WrapContacts(c));
    }
    return conListWrap;
    }
    public PageReference deleteContacts()
    {
    PageReference PageRefer = new PageReference(‘/apex/WrapperDelPage’);
    PageRefer.setRedirect(true);
    delContacts = new List<Contact>();
    for(WrapContacts c : conListWrap)
    {
    if(c.check == true)
    {
    delContacts.add(c.con);
    }
    }
    try
    {
    delete delContacts;
    }
    catch(Exception e)
    {
    System.debug(‘m=====’+e.getMessage());
    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,e.getMessage()));
    return null;
    }
    return PageRefer;
    }
    }

    Apex Page:-

    <apex:page controller=”WrapperDeleteContactsAccounts” sidebar=”false”>
    <apex:form >
    <apex:pageBlock id=”pb”>
    <apex:pageBlockButtons >
    <apex:commandButton value=”delete selected” action=”{!deleteContacts}” reRender=”pb” />
    </apex:pageBlockButtons>
    <apex:pageMessages />
    <apex:pageBlockTable value=”{!Contacts}” var=”cont” columns=”5″ Id=”pb1″>
    <apex:column headerValue=”select”>
    <apex:inputCheckbox value=”{!cont.check}”/>
    </apex:column>
    <apex:column value=”{!cont.con.LastName}”/>
    <apex:column value=”{!cont.con.Gender__c}”/>
    </apex:pageBlockTable>
    </apex:pageBlock>
    </apex:form>
    </apex:page>

     

    Hope this helps.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos