You need to sign in to do that
Don't have an account?
Rohit Kumawat
trigger to delete related contact according to account field value changed
Hi All,
I want to create contacts as per field value no of location in account and also if i update the no of location field value .. if new value is more than previous then it create new contacts as per difference between new and old value of account feld.
and if the new value is less than old value then it delete the related contact based on difference between new and old value.
You need to write the Trigger on Contact, because if a new Contact is created or deleted, the change in count must be reflected in the Parent Account.
You can try this,
trigger CountContactOnAccount on Contact (after INSERT, after UPDATE, after DELETE ) {
Set <Id> accountIds = new Set <Id>();
List <Account> lstAccountsToUpdate = new List <Account>();
if(Trigger.isInsert){
for(Contact con:trigger.new){
accountIds.add(con.accountID);
}
}
if(Trigger.isUpdate|| Trigger.isDelete){
for(Contact con:trigger.old){
accountIds.add(con.accountID);
}
}
for(Account acc:[SELECT Id,Name,Count_Contact__c,(Select Id from Contacts) from Account where Id IN: accountIds]){
Account accObj = new Account ();
accObj.Id = acc.Id;
accObj.Count_Contact__c = acc.Contacts.size();
lstAccountsToUpdate.add(accObj);
}
UPDATE lstAccountsToUpdate;
Maybe you need to make some minor changes based on your requirement.
Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.
Thanks.
I think you have not understood my requirment. Your trigger is to count no of contacts associated with account. But my scenerio is:
example : when i create account and i enter the value in custom field no of location = 3 then it will create three contacts as well
but when i update the value from 3 to 5 it will create two more contacts
and if i update the value from 5 to 2 it will delete three contacts
Hi Rohit,
Please Find The Solution of your questions trigger to delete related contact according to account field value changed.
If It will help you then Please Mark it Best Answer so that other people would take reference from it.
Thanks