+ Start a Discussion
Deepak ChouhanDeepak Chouhan 

trigger : object1 field value stored into object2

i have create 2 object Test1 and Test2

Test1 fields : Id auto and name
Test2 fields : Id auto, Test1 Id, Test1Name and status Picklist (Yes,No)

- i want to write a triggen on Test1
- when i insert or update value in Test1 same value insert into Test2
- when i update a value in Test1 same value update on Test2.
Frédéric TrébuchetFrédéric Trébuchet
This should helps :
trigger testTrigger on Test1 (after insert, after update) {
	List<Test1> listTest1 = [SELECT Id, Name FROM Test1 WHERE Id IN :Trigger.New];
    List<Test2> listTest2 = new List<Test2>();

    for(Test1 t1 :listTest1) {
        listTest2.add(new Test2(Test1Id=t1.Id, test1Name=t1.Name));
    if (listTest2.size() > 0) {
        insert listTest2;
Maybe you'll have to deal with the fields name depending of yours.

Hope this helps,
Jerome LusinchiJerome Lusinchi
I would do it that way :
Make the Test1Id__c field of Test2 object as external Id

then your trigger :

trigger Test1Trigger on Test1__c (after insert, after update){
      List<Test2__c> test2List = new List<Test2__c>();
      for(Test1__c myTest1 : trigger.new){
           test2List.add(new Test2__c(IdAuto__c = mtTest1.IdAuto__c, Test1Id__c = myTest1.Id, Test1Name__c = myTest1.Name));

     try {
          upsert test2List Test1Id__c;
     catch (DmlException e) {


check this for upsert details
Frédéric TrébuchetFrédéric Trébuchet
Mine should works also if you replace insert by upsert as Jerome suggest (I forgot the update on Test2).