+ Start a Discussion
smitha george 5smitha george 5 

Trigger to update account field

Assumptions: 
1). Account object has a custom string field named acFieldOne
2). Contact object has a custom string field named coFieldOne
 
How to write a trigger, such that any time a Contact is created, the  coFieldOne field on the Contact, is stamped with the value in the acFieldOne field on the Account ?
Thanks in Advance.
Best Answer chosen by smitha george 5
Ankit SehgalAnkit Sehgal
trigger copyField on Contact(after insert)
{
    Id accId = [SELECT Id,AccountId FROM Contact WHERE Id IN: Trigger.new].AccountId;
    Account acc=[SElECT acFieldOne__c FROM Account WHERE Id =: accId];
    String value=acc.acFieldOne__c;
    Contact con = [Select Id,coFieldOne__c FROM Contact WHERE Id IN: Trigger.new];
    con.coFieldOne__c=value;
    update con;
}

All Answers

Prateek Singh SengarPrateek Singh Sengar
Hi Smitha, 
I believe you can do this with workflows with field update as well. Any particular reason you want to go with Triggers?

Please see below a sample where contact address is updated from account address.

https://success.salesforce.com/answers?id=90630000000i03JAAQ

Hope this helps
 
Ankit SehgalAnkit Sehgal
trigger copyField on Contact(after insert)
{
    Id accId = [SELECT Id,AccountId FROM Contact WHERE Id IN: Trigger.new].AccountId;
    Account acc=[SElECT acFieldOne__c FROM Account WHERE Id =: accId];
    String value=acc.acFieldOne__c;
    Contact con = [Select Id,coFieldOne__c FROM Contact WHERE Id IN: Trigger.new];
    con.coFieldOne__c=value;
    update con;
}
This was selected as the best answer
beginnervbeginnerv
How to bulkify the above trigger logic?