Activity Forums Salesforce® Discussions How can we add a field in object using Salesforce trigger?

  • shradha jain

    Member
    August 9, 2018 at 11:58 am

    Hello Madhulika,
    You can refer the following example:

    1. Account (Parent Object)
    2. Contact (Child Object).
    3. Contact_Recs__c (Roll up summary field/Custom Field).
    4. accountid (Lookup field).

    Trigger Code:

    trigger CountContactsnew on Contact (after insert, after delete, after undelete) {

    List accIdList = new List();
    if(Trigger.isInsert || Trigger.isUndelete){
    For(Contact con1 : Trigger.new){
    accIdList.add(con1.accountid);
    }
    }
    if(Trigger.isDelete){
    For(Contact con1 : Trigger.old){
    accIdList.add(con1.accountid);
    }
    }
    List accUpdateList = new List();
    For(Account acc : [SELECT Contact_Recs__c,(SELECT id FROM Contacts) FROM Account WHERE id =: accIdList]){
    acc.Contact_Recs__c = acc.Contacts.size();
    accUpdateList.add(acc);
    }
    try{
    update accUpdateList;
    }Catch(Exception e){
    System.debug('Exception :'+e.getMessage());
    }
    }
    Thanks.

  • shariq

    Member
    September 17, 2018 at 11:20 pm

    Hi,

    For creating fields through code you need to use meta data apis and one more thing you can't create roll up field for lookup, it should master detail.

    Hope this helps.

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos