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
DorababuDorababu 

trigger on account

Hi,

I am new to triggers. I wanted to assign FirstName and LastName to customFields, which I have tried as follows.

PLease improve the code. Any help will be appreciated.

 

trigger copyFirstNameLastName on Account (before insert) {
    for(Account ac:trigger.new){
    List<Account> acc = new List<Account>([Select id,FirstName,LastName from Account Where id IN :Trigger.new]); 
                     
    for(Account a:acc){
    if(acc.IsPersonAccount==true){
        if(!acc.isEmpty()){
        acc.First_Name__pc = acc.FirstName;
        acc.Last_Name__pc = acc.LastName;
        }
        }
    update acc;
    }
    }
    
}

 -- Thanks in Advance --

Best Answer chosen by Admin (Salesforce Developers) 
JohnSchultzJohnSchultz

Because you're doing this as a "before insert" trigger, you don't need to use the update function. You could just do it like this:

trigger copyFirstNameLastName on Account (before insert) {
    for(Account ac:trigger.new){
        if (acc.IsPersonAccount == true) {
            acc.First_Name__c = acc.FirstName;
            acc.Last_Name__c = acc.LastName;
        }
    }    
}

 

All Answers

JohnSchultzJohnSchultz

Because you're doing this as a "before insert" trigger, you don't need to use the update function. You could just do it like this:

trigger copyFirstNameLastName on Account (before insert) {
    for(Account ac:trigger.new){
        if (acc.IsPersonAccount == true) {
            acc.First_Name__c = acc.FirstName;
            acc.Last_Name__c = acc.LastName;
        }
    }    
}

 

This was selected as the best answer
sushant sussushant sus
trigger copyFirstNameLastName on Account (before insert) {
for(Account acc:trigger.new){
if (acc.IsPersonAccount == true) {
acc.First_Name__c = acc.FirstName;
acc.Last_Name__c = acc.LastName;
}
}
}