Activity › Forums › Salesforce® Discussions › How can we add a field in object using Salesforce trigger?
Tagged: Data Type, Field Data Types, Fields in Salesforce, Salesforce Objects, Salesforce Triggers, Standard Objects, Triggers in Salesforce
-
How can we add a field in object using Salesforce trigger?
Posted by madhulika shah on July 4, 2018 at 8:16 AMHow can we add field in object with datatype roll up summary in lookup relationship using trigger?
shariq replied 7 years, 8 months ago 3 Members · 2 Replies -
2 Replies
-
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. - [adinserter block='9']
-
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.