+ Start a Discussion
divya1234divya1234 

Apex trigger on Custom Object to auto populate lookup field of account and custom object

I'm new to developing in general and I am trying to create a trigger that updates the custom lookup field Test1__c and account__c on the custom object test2  object. I have a created a custom object called test2  o  which has a related one-to-one relationship with the Account and test 1. I'm getting an error when attempting to save the Opportunity record, although it mentions the correct reference below but doesnt populate the field. My code is pasted below the error message."Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger Populatetest2caused an unexpected exception, contact your administrator: Populatetest2 : data changed by trigger for field Repcode: data value too large: (value has been hidden)"
 
trigger PopulateTest2 on Test1(before insert,before update) {
    set<ID> setofTest2 = new set<id>();
    set<ID> setofContactUser     = new set<id>();
    for (Test1 CA : trigger.new){
        if(CA.Test2_Name__c != null){
            setofTest2.add(CA.Test2_Name__c);}
        if(CA.ContactUser__c!=null){
            setofContactUser.add(CA.ContactUser__c); }   }       
        List<Test2__c> Test2List  = [Select ContactUser__c from Test2__c where id in: setofTest2];
        List<Account>  AccList = [Select Name from Account where id in: setofContactUser];    
     for(Integer i = 0; i < Trigger.new.size(); i++){
        if (Trigger.new[i].Test2__c != null) {
           Trigger.new[i].Test2__c = Test2List[i].ID;            
        }
        if (Trigger.new[i].ContactUser__c != null) {
           Trigger.new[i].ContactUser__c  = AccList[i].ID;            
        }
    }
    }


 
Leon ThanikalLeon Thanikal
Hi Divya,

If you could supply the ERD and the fields in the object I can try to help you.
These two pieces of information would really be helpful in trying to understand what you are trying to accomplish.
Thanks!
divya1234divya1234
Hi thansks for the rpely.
i have trying to create a batch job to create a  case ..on case object i have two lookup field one is (ookup to account) account__c and other is ContactUser__c (custom object) i am trying to write a trigger to auto popluate these two field values via trigger.
Leon ThanikalLeon Thanikal
Okay. But with what value are trying to autopopulate those fields with?
Also on what object should the trigger be running on?
divya1234divya1234
i am trying to auto poplate the value of lookup field (which is created on custom objects) on case object .trigger is running on custom object