0

I want to update a check box in Opportunity obj.but it is throwing a error that field is read only. Please suggest me how I can update my field. My logic is if account having Lead and lead status not converted then for that same account when I am creating a opportunity at that time my opportunity field get checked as true.Please help me.

trigger CopyleadvaluetoOpp on Opportunity (after insert) {

    Set <String> OppotunityCustId = new Set <String> ();

    for (Opportunity Opp : trigger.New) {
        OppotunityCustId.add(Opp.Customer_Id__c);
    }

    //Map <String, Lead> matchingLeadMap = new Map <String, Lead> ();

    List <Lead> newLead = new List<Lead> ([Select Id,Status,Customer_Code__c From Lead Where Customer_Code__c IN :OppotunityCustId AND Status != 'Converted']);
    /*{
     matchingLeadMap.put(Ld.Status, Ld);
    }*/

    List <Opportunity> opportunityToUpdate = new List <Opportunity> ();

    for (Opportunity Opp : trigger.New) {
        if (newLead.size() > 0) {
            if (newLead != null) {
                // we found a mathing one
                Opp.Lead_Exception__c = true;
            }

            //Opp.adderror('Lead already exists for this account. Please convert lead to create account.');

            // add it to a separate list and update it
            //opportunityToUpdate.add(Opp);
        }
    }
    update OpportunityToUpdate;
}

2 Answers 2

0

Your trigger needs to be before insert instead of after insert. This is needed in order to update records in Trigger.new before the records are saved.

1
  • Thanks for your reply. It is working. Just need one modification If I want to Update a field value from Lead to Opportunity then how will I do it. Please suggest.
    – Supriyo
    Dec 9, 2020 at 12:18
0

In an After trigger you cannot directly update the records in the trigger (as they are locked).

I'd advise changing this to a Before trigger as you will not need a DML statement then to update the checkbox.

If you need to do an After trigger, then create a new Opportunity record variable in the code, assigning it the Id of the Opportunity in the trigger, and do an update on that record.

2
  • Thanks for your reply. It is working. Just need one modification If I want to Update a field value from Lead to Opportunity then how will I do it. Please suggest.
    – Supriyo
    Dec 9, 2020 at 12:19
  • 1
    @Supriyo You can map fields for lead conversion. You shouldn't need code for this.
    – sfdcfox
    Dec 9, 2020 at 13:40

You must log in to answer this question.

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