function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
UserSFDXUserSFDX 

I want Lead Title should be mapped to Opportunity Name on conversion of lead.

I want a trigger to do some dml of Lead Title should be mapped to Opportunity Name on conversion of lead.
Best Answer chosen by UserSFDX
SubratSubrat (Salesforce Developers) 
Hello ,

Can you try with the below trigger and let me know further :
trigger LeadConversionTrigger on Lead (after update) {
    // Check if the lead has been converted
    List<Lead> convertedLeads = new List<Lead>();
    for (Lead lead : Trigger.new) {
        if (lead.IsConverted && !Trigger.oldMap.get(lead.Id).IsConverted) {
            convertedLeads.add(lead);
        }
    }

    if (!convertedLeads.isEmpty()) {
        List<Opportunity> opportunitiesToUpdate = new List<Opportunity>();

        // Retrieve the converted opportunities
        Map<Id, Opportunity> convertedOpportunities = new Map<Id, Opportunity>();
        for (Opportunity opportunity : [SELECT Id, LeadId, Name FROM Opportunity WHERE LeadId IN :convertedLeads]) {
            convertedOpportunities.put(opportunity.LeadId, opportunity);
        }

        // Update the opportunity names based on the lead titles
        for (Lead lead : convertedLeads) {
            Opportunity convertedOpportunity = convertedOpportunities.get(lead.Id);
            if (convertedOpportunity != null && lead.Title != null) {
                convertedOpportunity.Name = lead.Title;
                opportunitiesToUpdate.add(convertedOpportunity);
            }
        }

        // Perform the updates
        if (!opportunitiesToUpdate.isEmpty()) {
            update opportunitiesToUpdate;
        }
    }
}
In this trigger, we first check if the lead has been converted by verifying the IsConverted field. We iterate over the updated leads in the trigger context and identify the leads that have been converted for the first time.

Next, we query for the opportunities associated with the converted leads using the LeadId field. We store the converted opportunities in a map using the lead IDs as the keys.

Then, we iterate over the converted leads and retrieve the corresponding opportunity from the map. If the opportunity exists and the lead has a non-null title, we update the opportunity's name with the lead's title and add it to the opportunitiesToUpdate list.

Finally, if there are opportunities to update, we perform the update using the update DML statement.

If this helps , please mark this as Best Answer.
Thank you.