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
Scott0987Scott0987 

Before insert help

I am relatively new to apex.  I have written a couple of apex triggers, but never one that runs before something is inserted.  I am not sure on a couple of things.  here is my code:

    if(trigger.isinsert){
        list<Object1__c> field1List = new list<Object1__c>();
        Object1__c m = new Object1__c();
        for(Object1__c t : trigger.new){
            m.Field1__c = t.Field1__c;
            m.Field1_email__c = t.Field1__c;
            field1List.add(m);
    }    }

 What I am trying to do is copy the data in Field1__c to Field1_email__c.  What I am not sure and maybe I am just complicating it is how to add the change back to the items that triggered the code and make sure that all of the fields are inserted not just the 2 that I am working with.  If I just add "insert field1List;" will it add the data to salesforce and if so will it add the other fields that are initially on the object like field2__c, field3__c and so forth?  

Best Answer chosen by Admin (Salesforce Developers) 
Yoganand GadekarYoganand Gadekar

Try below,  considering ur custom fields are on account:

 

Trigger Copy_Fields on account (before insert){

 

       for(account acc:trigger){

             acc.Field1_email__c = acc.Field1__c;

      }

  

}

 

Put value in Field1 and keep Field1_email empty at the time of insert and click save. After record is saved both the  fields will have same value.

mark this as answer if this works. :-)

All Answers

logontokartiklogontokartik

Since you are trying to copy from one field to another field on same object, all you need is something like below to copy from your field1 to field1_email

 

if(Trigger.isInsert && Trigger.isBefore){
     for(Object1__c t : trigger.new) {
         t.Field1_email__c = t.Field1__c;
     }
}

 

This should take care of copying field1 to field1email and save records. (in before insert / update trigger you dont have you specify explicit DML for the object you have written the trigger on)

 

 

Yoganand GadekarYoganand Gadekar

Try below,  considering ur custom fields are on account:

 

Trigger Copy_Fields on account (before insert){

 

       for(account acc:trigger){

             acc.Field1_email__c = acc.Field1__c;

      }

  

}

 

Put value in Field1 and keep Field1_email empty at the time of insert and click save. After record is saved both the  fields will have same value.

mark this as answer if this works. :-)

This was selected as the best answer