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
IntroAmmyIntroAmmy 

Write trigger on account to create opportunities when account record is created

Need to create opportunity record when x type of account (x is record type) is created and assign contact id of this account to Opportunity account I'd.

can someone help me on that
SwethaSwetha (Salesforce Developers) 
HI,
This below code is a basic outline of the trigger that you need to customize as per your requirement
 
trigger CreateOpportunity on Account (after insert) {
    List<Opportunity> opportunitiesToInsert = new List<Opportunity>();
    
    // Get the record type ID of the desired Account record type
    Id desiredRecordTypeId = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Your Record Type Name').getRecordTypeId();
    
    for (Account acc : Trigger.new) {
        // Check if the Account record type matches the desired record type
        if (acc.RecordTypeId == desiredRecordTypeId) {
            // Create a new Opportunity and assign the Account's Contact ID to the Opportunity's Account ID
            Opportunity opp = new Opportunity();
            opp.Name = 'New Opportunity';
            opp.AccountId = acc.Id;
            opp.ContactId = acc.ContactId;
            // Set other required fields for the Opportunity
            
            opportunitiesToInsert.add(opp);
        }
    }
    
    // Insert the Opportunities
    if (!opportunitiesToInsert.isEmpty()) {
        insert opportunitiesToInsert;
    }
}

This trigger will create an Opportunity whenever an Account with the specified record type is created. It assigns the Account's Contact ID to the Opportunity's Account ID field. You can add additional logic and field mappings as needed.

If this information helps, please mark the answer as best. Thank you
Arun Kumar 1141Arun Kumar 1141

Hi IntroAmmy

Please refer to this code.

trigger CreateOpportunityOnAccountInsert on Account (after insert) {
    List<Opportunity> oppList = new List<Opportunity>();
    for (Account acc : Trigger.new) {
        if (acc.RecordType.Name == 'X_Record_Type_Name') {
            Opportunity opp = new Opportunity();
            opp.Name = 'New Opportunity';
            opp.AccountId = acc.Id; 
            List<OpportunityContactRole> contactRoles = [SELECT ContactId FROM OpportunityContactRole WHERE OpportunityId IN (SELECT Id FROM Opportunity WHERE AccountId = :acc.Id) LIMIT 1];
            if (!contactRoles.isEmpty()) {
                opp.ContactId = contactRoles[0].ContactId; 
            }
            oppList.add(opp);
        }
    }
    insert oppList;
}
 

Please mark this as the best answer, if it helps.

Thanks