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
cyrilvercyrilver 

Batch Apex : create opportunities with product item

Hi,

 

In my Org, Account can have many assets. These assets have a custom field "renewal date".

When the renewal date of an asset of an account expired an opportunity has to be created for the account with the same product

reference.

So I've created a batch apex to do that which is executed each day.

I've managed to create the opportunities but I don't know how to create the link with the good product.

Many Thanks.

Here is my execute method code :

 

 

global void execute(Database.BatchableContext BC, List<sObject> scope){

Date dCloseDate = system.now().date();

   

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

List<Asset> listAssets = new List<Asset>();

List<Opportunity_Asset_Link__c> listOppAssetLinks = new List<Opportunity_Asset_Link__c>();

   

   

for(sObject oObj:scope){

Asset oAsset = (Asset) oObj;

   listAssets.add(oAsset);

   

    Opportunity oOpp = new Opportunity(Name='Test Create Opp', StageName='Prospecting', CloseDate=dCloseDate,

    AccountId=oAsset.AccountId, OwnerId = oAsset.Account.OwnerId);

   

listOpps.add(oOpp);

}

// Insert Opportunity   

if(listOpps.size() > 0){

    list<Database.SaveResult> listSaveResult=database.insert(listOpps,false);

   

    // Check Results

    for (integer i=0;i<listSaveResult.size();i++){

   Database.SaveResult sr=listSaveResult[i];

 

    if(sr.isSuccess()){

// How can I be sure that I'm on the good opportunities and the good asset ???

    Opportunity_Asset_Link__c oOppAssetLink = new Opportunity_Asset_Link__c(Opportunity__c=sr.getId(), Asset__c=listAssets[i].Id);

   

   listOppAssetLinks.add(oOppAssetLink);

   }

   } 

}  

 

// Insert Opportunity Asset Link 

if(listOppAssetLinks.size() > 0){

list<Database.SaveResult> listSaveResult2=database.insert(listOppAssetLinks,false);

}

}

 

Regards,

Cyril