0

Hello I am writing one trigger to update a lookup field. I have one object job applicant where 2 fields job num(text field) & job(look up field). I want the job(if blank) field should be updated with the job num field. I have written 1 trigger but its not working. on record level error is showing.

    trigger JobNumUpdate on Job_Applicant__c (after insert, before update) {
    list<Job_Applicant__c> JAList= new list<Job_Applicant__c>();
   Job_Applicant__c JAp;
    for (Job_Applicant__c jba:Trigger.new)
    {
        JAList.add(jba);
    }
    for(Job_Applicant__c JA:JAList)
    {
        JAp=[select id,Job_Num__c,Job__c    from Job_Applicant__c];
        if(JA.Job_Num__c!=null)
        {
          JAp.Job__c=JA.Job_Num__c;  
        }
        JAList.add(JAp);
    }
      update JAList;


 }
2
  • What is the error that you mentioned. That would be helpful instead of making us guess.
    – Eric
    Mar 10, 2017 at 7:42
  • @Eric on record level i am getting error like "Error: Invalid Data. Review all error messages below to correct your data. Apex trigger JobNumUpdate caused an unexpected exception, contact your administrator: JobNumUpdate: execution of BeforeUpdate caused by: System.QueryException: List has more than 1 row for assignment to SObject: Trigger.JobNumUpdate: line 10, column 1"
    – geek_sfdc
    Mar 10, 2017 at 8:47

1 Answer 1

1

The problem is that you are trying to fill in Job__c field(lookup) with a text. Lookup field must be filled in with an id of another record(reference). Your code will only work if your Job_Num__c field will actually contain an id of a record.


Now let's review your code. This loop:

list<Job_Applicant__c> JAList= new list<Job_Applicant__c>();
for (Job_Applicant__c jba:Trigger.new)
{
    JAList.add(jba);
}

is not needed. You can simplify it by initialising your list directly with Trigger.new:

List<Job_Applicant__c> JAList = Trigger.new;

Then, you have a query in a loop:

JAp=[select id,Job_Num__c,Job__c    from Job_Applicant__c];

first, this will likely hit the governor limits. Second, it will work if, and only if, your Job_Applicant__c object contains exactly 1 record! If it contains none, you will get List has no rows for assignment to SObject error. If you have 2 or more records you will get List has more than 1 row for assignment to SObject error. Third, and last, you already have this record in your Trigger.new, why would you want to query it?

And, as I mentioned previously, this line:

JAp.Job__c=JA.Job_Num__c;  

Will only work(read: not fail) if Job_Num__c is an Id of a record.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .