Hi Everyone,
I have a little bit tricky question here, hope someone come up with a solution.
My Salesforce org has a custom object which has a Master-Detail relationship with Account and lookup relationship with Order. Also, Order has a lookup relationship with Account.
I want to populate both the Account and Order field automatically when creating a new record in the custom object while accessing it from the Order related list.
For instance, if I am in one of the Order record and going into the related custom object and try to create new record for the custom object it will populate Order field automatically but I want to populate both Order and Account fields.
Formula field is not an option as it already has Master-Detail relationship.
Is there any other way to do that???
You can try with a trigger like below
trigger PopulateFields on Custom_Object__c (before insert) {
for (Custom_Object__c obj : Trigger.new) {
if (obj.Order__c != null) {
Order order = [SELECT AccountId FROM Order WHERE Id = :obj.Order__c];
obj.AccountId = order.AccountId;
}
}
}
This trigger will fire before a new custom object record is inserted, it will query the Order object to get the AccountId related to the Order record and populate the AccountId field in the Custom_Object__c.