You need to sign in to do that
Don't have an account?

Trigger to prevent insert of child record based on field on parent.
Trying to create a trigger to prevent new child records being inserted if the field Event Status on it's parent is one of three values. Starting with just one of the values to keep it simple. Here's what I have so far.
trigger CSProductBeforeSave on CS_Product__c (before insert) { for (CS_Product__c q: trigger.new) IF(q.Customer_Support__c.Event_Status__c == 'Open Complaint') { q.addError('Cannot add records to PECs with Open Complaints status'); } }
![]() | Error: Compile Error: Invalid foreign key relationship: CS_Product__c.Customer_Support__c at line 6 column 12 |
CS_Product__c is a child to Customer_Support__c.
Any guidance would be appreciated!.
Rick
Use q.Customer_Support__r.Event_Status__c instead of q.Customer_Support__c.Event_Status__c
OK, using __r and the correct field name :-( allowed me to save the trigger. But the code does not prevent the insert of a new child record. The updated codes is below, what am I missing? I should note that the parent field Event Status is a pickilist, do I need to convert to text or....
can you please change the same to after insert and check again?
i guess that should solve the issue.
Still not preventing a new record. Could it have anything to do with the Event_Status__c field being a picklist?
Can you put a debug statement and let me know the output.
When I add the system debug line I'm not able to save the trigger. I get an error : Compilation Error: Variable does not exist:q.Customer_Support_ID__r.Event_Status__c at line 6 column 12. Did I miss something?
Sorry i missed brackets after the for loop.
Hi RDM1961,
I saw your requirement and it does not need a trigger as it can be achived using a simple Validation Rule. Write the following Validation Rule on the CS_Product__c object:
AND(ISNEW(), TEXT(Customer_Support__r.Event_Status__c) = "Open Complaint")
The Validation Rule when run only when you are trying to create a new CS_Product__c record.
As far as your trigger not working is concerned, the reason lies in the fact that in a Trigger you cannot reference a Parent Objects field values without querying it. You will see that the value printed out in the Debug statement will be null
Hope this fixes your issue.