function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sf_123sf_123 

Apex triggere help

Hi , I have just started with salesforce and i wrote a basic trigger for Contacts. I have created a custom field "des" on Contacts and i want it to have a default value from a standard  Account field: Description whenever a new contact is created.

 

The trigger code:

 

 trigger copyvalue on Contact (before insert,before update) {

for(Contact a:Trigger.new)

 { a.Des__c=a.Account.Description; } }

 

 This is not helping and i do not see the account's description value in the contact custom field. Please help!!!! Thanks a lot.

Ispita_NavatarIspita_Navatar

Please try the following:-

 trigger copyvalue on Contact (before insert,before update)

{

for(Contact a:Trigger.new)

 {

Account acc =[Select id, Description from Account where id=: a.Accountid];

a.Des__c=acc.Description;

}

}

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved.

JimRaeJimRae

That is a good suggestion, but is not bulk safe.

If more than 20 contacts were inserted or updated in batch, the Query limit would be exceeded.

A better practice would be to leverage a map to hold the data.

 

 

trigger copyvalue on Contact (before insert,before update){
     Set<ID> AcctIDs = new Set<ID>();
     for(Contact a:Trigger.new){
           AcctIDs.add(a.Accountid);
     }
     Map<ID,Account> AcctMAP = new Map<ID,Account>([Select id, Description from Account where id in :AcctIDs]);
     for(Contact a:Trigger.new){
          a.Des__c=AcctMap.get(a.AccountID).Description; 
     }
}

 

 

ahab1372ahab1372

you can also use a workflow rule with a field update, no need to create a trigger

sf_123sf_123

Thanks guys!!!! The code works......but one small problem though,I want to see the value as default when i open a new contact......Is this possible??