You need to sign in to do that
Don't have an account?
Anoop Kumar 31
Trigger : account has multiple contacts(with custom field age__c), i want to show youngest and oldest contact age in custom account fields youngest__c and oldest__c respectively.
I have tried this :
trigger Surajtrg on Contact (after insert, after update, after delete)
{
set<id> act=new set<id>();
List <Account> lstAccountsToUpdate = new List <Account>();
if(trigger.isInsert ||trigger.isUpdate)
{
for(contact cc:trigger.new)
{
act.add(cc.AccountId);
}
}
if(trigger.isDelete)
{
for(contact cc:trigger.old)
{
act.add(cc.AccountId);
}
}
List<Account> shocksList = [SELECT Id,Youngest__c,(SELECT id,MIN(Age__c) FROM Contact) from Account where Id IN: act];
for(Account acc:shocksList) //(Select Id from Contacts) represents size of Contacts
{
Account accObj = new Account ();
accObj.Id = acc.Id;
accObj.Youngest__c= acc.MIN(Age__c);
lstAccountsToUpdate.add(accObj);
}
Update lstAccountsToUpdate;
}
trigger Surajtrg on Contact (after insert, after update, after delete)
{
set<id> act=new set<id>();
List <Account> lstAccountsToUpdate = new List <Account>();
if(trigger.isInsert ||trigger.isUpdate)
{
for(contact cc:trigger.new)
{
act.add(cc.AccountId);
}
}
if(trigger.isDelete)
{
for(contact cc:trigger.old)
{
act.add(cc.AccountId);
}
}
List<Account> shocksList = [SELECT Id,Youngest__c,(SELECT id,MIN(Age__c) FROM Contact) from Account where Id IN: act];
for(Account acc:shocksList) //(Select Id from Contacts) represents size of Contacts
{
Account accObj = new Account ();
accObj.Id = acc.Id;
accObj.Youngest__c= acc.MIN(Age__c);
lstAccountsToUpdate.add(accObj);
}
Update lstAccountsToUpdate;
}
Try This :
Note: Add undelete also so it will work for undelete records aswell.
trigger Surajtrg on Contact (after insert, after update, after delete , after undelete)
if(trigger.isInsert ||trigger.isUpdate || trigger.isUndelete)
Hope this helps you!
If my answer helps resolve your query, please mark it as the 'Best Answer' & upvote it to benefit others.
Thanks
Varaprasad
@For SFDC Support: varaprasad4sfdc@gmail.com
Blog: http://salesforceprasad.blogspot.com/
Salesforce latest interview questions :
https://www.youtube.com/channel/UCOcam_Hb4KjeBdYJlJWV_ZA?sub_confirmation=1