I want to update address from parent object when new child record is created by trigger because any time i can change the child record but by default it should have address from its parent object.
3 Answers
Then create your trigger upon insert only on the child record. Get the parent record id and address via SOQL . Run over the parent & Child records loop. Check if parent id is same in the child records and the update the address of the child record. Keep in mind not to do DML operation inside your FOR loop.
Sample Trigger Code
Trigger ChildUpdate on Childobject__c(Before Insert)
{
Set<Id> ParentIds = New Set<Id>();
For(Childobject__c C : Trigger.New)
{
ParentIds.Add(C.ParentId__c);
}
List<ParentObjectName__c> ParentList = [Select Id,Address__c from ParentObjectName__c where id =: ParentIds];
For(Childobject__c CO : Trigger.New)
{
For(ParentObjectName__c PA : ParentList)
{
IF(CO.ParentId__c == PA.ID)
{
IF(PA.Address__c != NULL)
{
C.ChildAddressField__c = PA.Address__c ;
}
}
}
}
}
-
I have added the sample trigger code. Replace them with your object names and field names. But would suggest you to try creating the trigger first by yourself so that you will come to know more about it.– RuchiMay 26, 2016 at 10:18
Instead of a trigger, this can be achieved by using a workflow rule and a field update action.
(Assuming Parent: Account & Child: Contact)
Steps to follow:
- Create a workflow rule on Contact having criteria "AccountId" (lookup to account) not equal to null.
- Once created, create field update action (Under Workflow Actions) for updating MailingCity field.
- In the field update action, under Specify New Field Value, click on formula editor and insert field "Account.BillingCity".
- Repeat step 3 for rest of the address fields.
Hope this helps.
Best Regards!
-
Thanks for reply but i need to do this by trigger so what would be the process because any time i can change the address of child object manually. May 26, 2016 at 9:59
-
Workflow rules get fired every time an insert or update operation is performed. Although if you want to achieve it by trigger, I'll post another answer mentioning the steps to follow. Regards! May 26, 2016 at 10:00
Yet another way to achieve this is using trigger. A before insert
trigger will be fired which will perform the following operations:
- Fetch parent record ids from
Lookup_To_Parent__c
field intrigger.new
records and put them in aset<id>
. - Fetch the address information from related parent records and put them in a
map<Id, Parent_Object__c>
. - Iterate over
trigger.new
again and populate address fields from related parent by accessing the parent record usingget(anyKey);
method of map class.
Voila! The address fields are populated now.
Hope this helps.
Best Regards!