You need to sign in to do that
Don't have an account?
Florin W
Apex Trigger to prevent child record to be saved
Hello Apex Masters!
I'm new on Apex and I'm trying to create a trigger that prevents Salesforce from saving child records.
Parent record: "Account"
Custom child record: "Budget" --> Fields: "Year"(picklist) and "Amount" (picklist, four values)
Conditions for saving related child records:
- Maximum of 3 "Budget" child records per related account and "Year" (e.g. "2016")
- Sum(Amount) of related "Budget" child records must be <= $500 per year
Can you help me with this?
It seems not to be working with validation rules.
I'm new on Apex and I'm trying to create a trigger that prevents Salesforce from saving child records.
Parent record: "Account"
Custom child record: "Budget" --> Fields: "Year"(picklist) and "Amount" (picklist, four values)
Conditions for saving related child records:
- Maximum of 3 "Budget" child records per related account and "Year" (e.g. "2016")
- Sum(Amount) of related "Budget" child records must be <= $500 per year
Can you help me with this?
It seems not to be working with validation rules.
First Thing - You have to write a trigger on Budget object.
When ever a Budget object record has been created than your trigger will fire and get the value of parent which is of Accont.
Now you have account Id, Find out all the child reocrds of Budget which are belong to this Account, And check the account is having how many budget records and put your condition.
-Thanks
Ashlekh Gera
Hi Florin,
+1 to AKG's suggestions. I would also suggest throwing a nice to read error when the condition is met not to create another budget record so your users stay informed and know why it's preventing them from creating the record.
Information on adding errors can be found here:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_sobject.htm
-derhyk
You can try below code sample. Let me know if it works.