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
Chidanand Magadum 24Chidanand Magadum 24 

Create New Opportunity

Hai All,

How to create new opportunity Using Apex Code. Any Code help Please.
Waqar Hussain SFWaqar Hussain SF
Opportunity opp = new Opportunity();
opp.CloseDate=date.today().addMonths(2);
opp.Name='test opp';
opp.StageName='IsWon';
insert opp;
Himanshu ParasharHimanshu Parashar
Hi Chidanand,

what the issue you are facing in that.

it is as simple as inserting any other object. first initialize Opportunity object and then call insert method.
 
Opportunity Opp = new Opportunity();
insert Opp;

if you have other fields then you can pass them as well with above call as
 
Opportunity Opp = new Opportunity();
Opp.Accountid= acc.id;
Opp.Closedate= System.today();
//Other fields.
//Other fields
//Other fields.
insert Opp;

Thanks,
Himanshu
Salesforce Certified Developer | Administrator | Service Cloud Consultant

P.S.  If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.
 

 
Chidanand Magadum 24Chidanand Magadum 24
Thanks. But when i try to update the opportunity M getting the following error
System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call: []

This is my Code.
    Opportunity opp = new Opportunity();
    opp.CloseDate=date.today().addMonths(2);
    opp.Name='test opp1';
    opp.StageName='Legal';
    opp.AccountId='001J000001Z9p7o';
    opp.Amount=50000;
    update opp;
Himanshu ParasharHimanshu Parashar
Hi Chidanand,

update last line with
 
upsert opp;

it will work.


Thanks,
Himanshu
Salesforce Certified Developer | Administrator | Service Cloud Consultant

P.S.  If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.
 
Suraj Tripathi 47Suraj Tripathi 47
Hello Chidanand,

"Try this code to create opportunity record using apex code."
public class CreateOpportunity{
    public static void insertOpp()
    {
             Opportunity opp = new Opportunity();
             opp.Name='Opp1';
             opp.StageName='Closed Won';
             opp.CloseDate=Date.today();
             insert opp;  
  }
}

If you find your Solution then Mark this as Best Answer

Thank you!
Regards,
Suraj Tripathi