0

Line 4 of this trigger is giving 'Illegal assignment from List to String' error. Can anyone help? thank you.

trigger NewLeadCreateAcct on Lead (after insert) {
    for (Lead newL : Trigger.new){
        Account newAcc = new Account();
        newAcc.name = [select LastName from Lead where id = :newL.id LIMIT 1];
        insert newAcc;
    }
}
1

A query returns a list no matter what, but can be cast to a single sObject when it results in a single record. But you can't reference the field directly, as you're doing. With the query in it, line 4 could be:

newAcc.name = [select LastName from Lead where id = :newL.id LIMIT 1].LastName;

But you don't need to query the Leads, and indeed you definitely shouldn't query inside your loop that's processing the leads in the trigger. Just reference the last name of the Lead specified by your loop variable:

newAcc.name = newL.LastName;

Not related to your specific question, but another important principle, is not to do DML in a loop. Put any created Accounts into a List, and insert them all at the end:

trigger NewLeadCreateAcct on Lead (after insert) {
    List<Account> accs = new List<Account>();
    for (Lead newL : Trigger.new){
        Account newAcc = new Account();
        newAcc.name = newL.LastName;
        accs.add(newAcc);
    }
    insert accs;
}
0

For your line no.4 you can just add newAcc.name = newL.LastName;

There are some best practice while writting trigger. Dml and Soql in for loop is not a best practice. You can learn from this link description here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.