public class OpportunityToAccountBatchClass implements Database.Batchable<sObject> {
//Start Method
public Database.QueryLocator start(Database.BatchableContext BC)
{
return Database.getQueryLocator('select id,AccountId,Name,Type from Opportunity where Status__c != \'Closed\'');
}
//Execute Method
public void execute(Database.BatchableContext BC,List<Opportunity> oppData)
{
Map<Id, List<Opportunity>> mapOppIdToAccOrd = new Map<Id, List<Opportunity>>();
Set<Id> oppId = new Set<Id>();
List<Account> accList = new List<Account>();
List<Order> orderList = new List<Order>();
List<Opportunity> updateAccRefToOpp = new List<Opportunity>();
for(Opportunity opp : oppData)
{
if(String.isNotBlank(opp.AccountId) && opp.Type=='New Customer') {
if(!mapOppIdToAccOrd.containsKey(opp.AccountId)) {
mapOppIdToAccOrd.put(opp.AccountId, new List<Opportunity>());
}
mapOppIdToAccOrd.get(opp.AccountId).add(opp);
oppId.add(opp.AccountId);
}
if(oppId.size()>0)
{
accList.add(New Account(Name=opp.Name+'-'+'Account'));
}
}
if(accList.size()>0)
{
insert accList;
for(Account acc : accList)
{
for(Opportunity op : oppData)
{
if(!mapOppIdToAccOrd.containsKey(op.AccountId) && op.Type=='New Customer')
{
op.AccountId=acc.Id;
updateAccRefToOpp.add(op);
}
}
}
update updateAccRefToOpp;
}
}
//Finish Method
public void finish(Database.BatchableContext BC)
{
}
}Thanks in Advance
Hi Rakesh M 20, Kindly find the solution.
If you find your Solution then mark it as the best answer. Thanks and RegardsSuraj Tripathi.public class BatchOnOpprtunity implements Database.Batchable<sObject>{
public final String Query;
public final String Entity;
public final String Field;
public final String Value;
public Database.QueryLocator start(Database.BatchableContext BC){
String query ='select id,AccountId,Name,Type from Opportunity where Status__c != \'%Closed%\' And Type = \'New Customer\'';
return Database.getQueryLocator(query);
}
public void execute(Database.BatchableContext BC, List<Opportunity> oppList){
Map<Opportunity, Account> accountMap = new Map<Opportunity,Account>();
for(Opportunity opp: oppList){
Account acc = new Account();
acc.Name = opp.Name;
accountMap.put(opp,acc);
}
if(!accountMap.values().isEmpty()){
insert accountMap.values();
}
for(Opportunity opp : oppList){
opp.AccountId = accountMap.get(opp).Id;
}
if(!oppList.isEmpty()){
update oppList;
}
}
public void finish(Database.BatchableContext BC){
}
}