• Soubhagya Ranjan 2
  • NEWBIE
  • 10 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 23
    Questions
  • 9
    Replies
I want to delete records having status as rejected through batch class . 

please check the below code and let me know the correct code 

global class batchdeleteloan implements Database.batchable<sobject>{
global final String Query;
global batchdeleteloan (String q)
{
Query=q;
}
global Database.QueryLocator start(Database.BatchableContext BC)
{
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC,List<SObject> scope)
{
List <List<Laon_Application__c> > loanList = new list<List<Laon_Application__c> >();
for(List<Laon_Application__c> l : scope)
{
List<Laon_Application__c> la = (List<Laon_Application__c>)l;
If(l.Status__c = 'Rejected'){
LoanList.add(la);
}
}
Delete LoanList;
}

global void finish(Database.BatchableContext BC){

}
}
Hi ,

my requirement is to merge account records with same name . after merge i will store the deleted record value in another object  . the deleted record which will store in new object will have the id of the master record of account to which it is merged . 
Hi 

I am having 2 custom objects as student and studentcopy .

how to move records of student into student copy through batch apex . 

please provide me the code .

Thanks
Hi I want to insert account record from custom object Object1 . If record already present in account then object1 status field will be YES and if new record then insert the record into account and status of object1 will be NO . How to write batch class for this ?
 
Hi All ,
 I have folowing requirement .

i need to update account name through batch apex . if there is no error then update the name . and if there is some error then update the Status__c field as NO and send email to user with attached CSV file with the list of errors .

below is the code where i am able to send the eroor as csv file but not able to upadte the status field 


global class batchAccount2 implements Database.Batchable<sobject>, Database.stateful {
  global Map<Id, String> errorMap {get; set;}
    global Map<Id, SObject> IdToSObjectMap {get; set;}
 
    global batchAccount2 (){
        errorMap = new Map<Id, String>();
        IdToSObjectMap = new Map<Id, SObject>();
    }
    global Database.QueryLocator start(Database.BatchableContext bc){
      
        String query = 'SELECT Id, Name FROM Account';
        return Database.getQueryLocator(query);
    }
      
    global void execute(Database.BatchableContext bc, List<account> scope) {
      List<Account> accountList = new List<Account>();
        for(Account a : scope) {
            a.Name = a.Name + 'Updated';
            accountList.add(a);
        }
        if(accountList.size() > 0) {
            List<Database.SaveResult> dsrs = Database.Update(accountList, false);
            Integer index = 0;
            for(Database.SaveResult dsr : dsrs){
                if(dsr.isSuccess()){
                    
                }
                else{
                String errMsg = dsr.getErrors()[0].getMessage();
                    errorMap.put(accountList[index].Id, errMsg);
                    IdToSObjectMap.put(accountList[index].Id, accountList[index]);
                }
                index++;
            }
        }
    } 
      
    global void finish(Database.BatchableContext BC) { 
       //Send an email to the User after your batch completes 
       if(!errorMap.isEmpty()){
            AsyncApexJob a = [SELECT id, ApexClassId,
                       JobItemsProcessed, TotalJobItems,
                       NumberOfErrors, CreatedBy.Email
                       FROM AsyncApexJob
                       WHERE id = :BC.getJobId()];
            String body = 'Your batch job '
             + 'BatchApexAccountUpdate '
             + 'has finished. \n' 
             + 'There were '
             + errorMap.size()
             + ' errors. Please find the error list attached to the Case.';
 
            // Creating the CSV file
            String finalstr = 'Id, Name, Error \n';
            String subject = 'Account - Apex Batch Error List';
            String attName = 'Account Errors.csv';
            for(Id id  : errorMap.keySet()){
                string err = errorMap.get(id);
                Account acct = (Account) IdToSObjectMap.get(id);
                string recordString = '"'+id+'","'+acct.Name+'","'+err+'"\n';
                finalstr = finalstr +recordString;
            } 
 
            // Define the email
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 
 
            // Create the email attachment    
            Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
            efa.setFileName(attName);
            efa.setBody(Blob.valueOf(finalstr));
 
            // Sets the paramaters of the email
            email.setSubject( subject );
            email.setToAddresses( new String[] {a.CreatedBy.Email} );
            email.setPlainTextBody( body );
            email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
 
            // Sends the email
            Messaging.SendEmailResult [] r = 
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});   
            }
    } 
}
I hav a batch apex in account object . it will update account records . but when one single record failed to update then batch apex failed . please help me on this .. below is my code


global class batchAccount2 implements Database.Batchable<sobject>, Database.stateful {
  
    global Database.QueryLocator start(Database.BatchableContext bc){
      
        String query = 'SELECT Id, Name FROM Account';
        return Database.getQueryLocator(query);
    }
      
    global void execute(Database.BatchableContext bc, List<account> scope) {
      
        for(Account a : scope) {
            a.Name = a.Name + 'Updated';
        }
        // update scope;
        Database.update(scope, false);
    } 
      
    global void finish(Database.BatchableContext bc) {
       // Get the AsyncApexJob that represents the Batch job using the Id from the BatchableContext
 AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
  TotalJobItems, CreatedBy.Email, ExtendedStatus
  from AsyncApexJob where Id = :BC.getJobId()];
  
 // Email the Batch Job's submitter that the Job is finished.
 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 String[] toAddresses = new String[] {a.CreatedBy.Email};
 mail.setToAddresses(toAddresses);
 mail.setSubject('BatchJob batchAccount2  Status: ' + a.Status);
 mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +
  ' batches with '+ a.NumberOfErrors + ' failures. Please modify the error . ExtendedStatus: ' + a.ExtendedStatus);
   
 Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}
can someone provide me batch apex code for the folowing requirement ?

1 - if account name and billing address are same then it will not insert record and through error . 
2 - if account name and phone are same then it will not insert and through error .


is there any other way how to achieve this . i tried for trigger but number of records are more so it is throwing governemnt limit error .

Thanks,
 
requirement is when we insert record into account object then status field will be success and if it find duplicate then status will be error .
below is my code . it is executong but fields are not updating .

global class insertrecord implements Database.Batchable<sObject>, Database.Stateful {
String Query = 'select name , phone, fax, BillingStreet from Account ';
global Database.QueryLocator start(Database.BatchableContext BC)  {
      return Database.getQueryLocator(query);
      }
global void execute(Database.BatchableContext BC, List<sObject> scope) {
       List<Account > AccList = [Select name,BillingStreet,fax from Account ];
         Set<string> name= new Set<string>();
         Set<string> BillingStreet= new Set<string>();
         Set<string> fax= new Set<string>();
        for(Account Acc : AccList)
         {
           name.add(Acc.name );
           BillingStreet.add(Acc.BillingStreet);
           fax.add(Acc.fax);
         } 
       List<Account > duplicateAccountList = [Select name,BillingStreet from Account where name=:name and BillingStreet=:BillingStreet];
       List<Account > duplicateAccountList1 = [Select name,fax from Account where name=:name and fax=:fax];
       Set<string > duplicateAccountIds = new Set<string >();
       for(Account dup: duplicateAccountList )
       {
         duplicateAccountIds.add(dup.name);
         duplicateAccountIds.add(dup.BillingStreet);  
       }
       for(Account a : duplicateAccountList )
       {
            if(a.name!=null & a.BillingStreet!=null )
            {
               if(duplicateAccountIds.contains(a.name) & duplicateAccountIds.contains(a.BillingStreet))
               {
                 a.status1__c = 'Error';
               }
               else{
               a.status1__c = 'Success';
               }
            }
       }
             for(Account dup: duplicateAccountList1 )
       {
         duplicateAccountIds.add(dup.name);
         duplicateAccountIds.add(dup.fax);  
       }
       for(Account a1 : duplicateAccountList1 )
       {
            if(a1.name!=null & a1.fax!=null )
            {
               if(duplicateAccountIds.contains(a1.name) & duplicateAccountIds.contains(a1.fax))
               {
                 a1.status1__c = 'Duplicate';
               }
            }
       }       
}
global void finish(Database.BatchableContext BC)
    {

    }

}




TRIGGER :

trigger testbatch on Account (before insert) {

Database.executeBatch(new insertrecord());


}
while i am inserting record i am getting these error 

ERROR :
Apex trigger DuplicateCoreCustomer caused an unexpected exception, contact your administrator: DuplicateCoreCustomer: execution of BeforeInsert caused by: System.QueryException: Non-selective query against large object type (more than 200000 rows). Consider an indexed filter or contact salesforce.com about custom indexing. Even if a field is indexed a filter might still not be selective when: 1. The filter value includes null (for instance binding with a list that contains null) 2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times): Trigger.DuplicateCoreCustomer: line 12, column 1


why i am getting theses errors and how to avoid these 
 
we can send email notifying that the batch job has suceesfully completed with these number of errors .

Can we send the failed record in batch apex as excel file to owner of batch job ?

if yes then how to achieve that in fibnish method ?
 
Hi I am having this trigger . when my account name is already present status will updated as Y . and when address is already present then its not updating to Y .. why ?

trigger accountupdatestatus1 on Account (before insert) {
  list<account> acc = new list<account>(); 
  list<account> acc1 = new list<account>();
 for(account a: trigger.new)
 {
acc=[select id,name from account where name=:a.name];
  if(acc.size()>0)
  {
   a.Status__c = 'Y' ;
  }
 }
 for(account a1: trigger.new)
 {
acc1=[select id,name,BillingStreet from account where name=:a1.BillingStreet];
  if(acc1.size()>0)
  {
   a1.Status__c = 'Y' ;
  }
 }
}
Hi I want to prevent duplicate value in account .I have written folowing trigger . but every time i created a new record it is showing error that you can not create duplicate record .

trigger AccountDuplicateTrigger on Account (before insert,before update) {
        for(Account a:Trigger.new)
        {
            List<Account> acc=[select ID,name from account where Name=:a.Name ];
            if(acc.size()>0)
            {
                a.adderror('You cannot create a dulplicate account');
            }
        }
    }
Hi ,

Can we insert account object records to data.com and latter we can serach those account records 
Hi 

I have a requirement . in this i have to insert and update account records . 
If account filed failed to insert then status field value will be IF .
If account field failed to update then status field value will be UF .

After batch apex execute there are records which will be failed to insert and failed to update .
I want to send mail to the owner that these records are failed due to duplicate value .
How to send this mail to owner in the finish method of batch apex .

 
Hi all 

My requirement is to insert records into account object through batch apex . there are some validations in account objects . so some records can not insert in to it . so at the last step of batch apex i want to send email to users of those failed record to modify the record as per requirement . how will i achieve this . can any one provide me the code for this .

Thanks
I want to write a trigger in account object . when a new record is created with same name then it will automatically send mail to account owner that duplicate record is created .
 
I want a trigger in account object when a new record is inserted with same phon enumber then it will automatically mail to account owner that account has been ctreated .

but i am facing issue REQUIRED_FIELD_MISSING, Missing target address (target, to, cc, bcc): 

below is my code 


trigger EmailAfterInserttest on Account(after Insert,after update) {
    Messaging.reserveSingleEmailCapacity(trigger.size);
    List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
    Set<Id> accId = new Set<Id>();
    List<ID>ownerids=new List<ID>();
    List<String> sendTo = new List<String>();
  List<User>users=[select name,id,email from user where id in:ownerids];
  for(User u:users){
      sendTo.add(u.Email);
    }
  
    for(Account a : Trigger.new)
        {
            accId.add(a.Id);
            ownerids.add(a.ownerid) ;
        }
        
        
    for (Account acct : Trigger.new) {
    List<Account> accList = [Select ID, owner.Id,owner.email, Name ,fax, phone From Account Where Id in :accId And phone=:acct.phone];
        if(acclist.size()>0)
        {
         Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(sendTo);
        email.setSubject('Inserted Account Alert');
        email.setPlainTextBody('This message is to alert you that the account named ' + acct.Name + ' has been inserted.');
        emails.add(email);
        Messaging.sendEmail(emails);
        }
    }
   
}
 
i have a trigger which shows error while trying to delete a record . it is working fine but after that the requirement is to send email to owner of that record . it is not working . i am posting my code . please check and provide the solution .

Trigger : 
Trigger ErrorDelete on Course__c(before delete) {
    Messaging.reserveSingleEmailCapacity(trigger.size);
    List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
    for (Course__c c: Trigger.old) {
        c.adderror ('can not delete');
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(new String[] {'ranjan.soubhagya2015@gmail.com'});
        email.setSubject('Deleted Account Alert');
        email.setPlainTextBody('This message is to alert you that the account  has been deleted.');
        emails.add(email);
    Messaging.sendEmail(emails);
        
    }
    
}




whenever i am commenting the adderror line then mail is sending but at a time error showing and email sending not working 
email not sent to user .

Trigger : 

trigger checkDuplicateValue on Account (after insert)
{
    if(Trigger.isAfter)
    {   
        //Get list of Users
        Map<Id,User> userMap = new Map<Id,User>([SELECT Name, Email FROM User]);
        
        //Get all Ids in order to do a query
        //and bulkify the trigger
        Set<Id> accIdSet = new Set<Id>();
        for(Account a : Trigger.new)
        {
            accIdSet.add(a.Id);
        }
        
        List<Account> accList = [Select ID, owner.Id, Name, fax, phone 
                                 From Account 
                                 Where Id in :accIdSet];
        
        if(!accList.isEmpty())
        {
            //Create a map with the Name and the Owner Id
            //With the Owner Id I can look for the User in the first Map
            Map<String, Id> accMap = new Map<String, Id>();
            for(Account acc : accList)
            {
                accMap.put(acc.Name, acc.owner.Id);
            }
            
            for(Account acc : Trigger.new)
            {
                String accName = acc.Name;
                if(accMap.containsKey(accName))
                {
                    //Double check the name for the new account
                    Id userId = accMap.get(accName);
                    acc.adderror('Account already exists in your Organization with name ' + acc.Name);
                    
                    //Retrieve the owner's email
                    String theEmail = userMap.get(userId).Email;
                    EmailHelper.sendEmail(theEmail);
                }
            }
        }
    }
}



Class :

public with sharing class EmailHelper
{
    public static void sendEmail(String theEmail)
    {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {theEmail});
        mail.setSenderDisplayName('My Email');
        mail.setSubject('My email subject');
        mail.setPlainTextBody('Process fails duplicate value');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

 
while inserting account record if account having same account name and same phone number the it will show error . and if account having same account name and differenet phone then it will save .
I want to delete records having status as rejected through batch class . 

please check the below code and let me know the correct code 

global class batchdeleteloan implements Database.batchable<sobject>{
global final String Query;
global batchdeleteloan (String q)
{
Query=q;
}
global Database.QueryLocator start(Database.BatchableContext BC)
{
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC,List<SObject> scope)
{
List <List<Laon_Application__c> > loanList = new list<List<Laon_Application__c> >();
for(List<Laon_Application__c> l : scope)
{
List<Laon_Application__c> la = (List<Laon_Application__c>)l;
If(l.Status__c = 'Rejected'){
LoanList.add(la);
}
}
Delete LoanList;
}

global void finish(Database.BatchableContext BC){

}
}
Hi ,

my requirement is to merge account records with same name . after merge i will store the deleted record value in another object  . the deleted record which will store in new object will have the id of the master record of account to which it is merged . 
I hav a batch apex in account object . it will update account records . but when one single record failed to update then batch apex failed . please help me on this .. below is my code


global class batchAccount2 implements Database.Batchable<sobject>, Database.stateful {
  
    global Database.QueryLocator start(Database.BatchableContext bc){
      
        String query = 'SELECT Id, Name FROM Account';
        return Database.getQueryLocator(query);
    }
      
    global void execute(Database.BatchableContext bc, List<account> scope) {
      
        for(Account a : scope) {
            a.Name = a.Name + 'Updated';
        }
        // update scope;
        Database.update(scope, false);
    } 
      
    global void finish(Database.BatchableContext bc) {
       // Get the AsyncApexJob that represents the Batch job using the Id from the BatchableContext
 AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
  TotalJobItems, CreatedBy.Email, ExtendedStatus
  from AsyncApexJob where Id = :BC.getJobId()];
  
 // Email the Batch Job's submitter that the Job is finished.
 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 String[] toAddresses = new String[] {a.CreatedBy.Email};
 mail.setToAddresses(toAddresses);
 mail.setSubject('BatchJob batchAccount2  Status: ' + a.Status);
 mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +
  ' batches with '+ a.NumberOfErrors + ' failures. Please modify the error . ExtendedStatus: ' + a.ExtendedStatus);
   
 Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}
Hi I am having this trigger . when my account name is already present status will updated as Y . and when address is already present then its not updating to Y .. why ?

trigger accountupdatestatus1 on Account (before insert) {
  list<account> acc = new list<account>(); 
  list<account> acc1 = new list<account>();
 for(account a: trigger.new)
 {
acc=[select id,name from account where name=:a.name];
  if(acc.size()>0)
  {
   a.Status__c = 'Y' ;
  }
 }
 for(account a1: trigger.new)
 {
acc1=[select id,name,BillingStreet from account where name=:a1.BillingStreet];
  if(acc1.size()>0)
  {
   a1.Status__c = 'Y' ;
  }
 }
}
i have a trigger which shows error while trying to delete a record . it is working fine but after that the requirement is to send email to owner of that record . it is not working . i am posting my code . please check and provide the solution .

Trigger : 
Trigger ErrorDelete on Course__c(before delete) {
    Messaging.reserveSingleEmailCapacity(trigger.size);
    List<Messaging.SingleEmailMessage> emails = new List<Messaging.SingleEmailMessage>();
    for (Course__c c: Trigger.old) {
        c.adderror ('can not delete');
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        email.setToAddresses(new String[] {'ranjan.soubhagya2015@gmail.com'});
        email.setSubject('Deleted Account Alert');
        email.setPlainTextBody('This message is to alert you that the account  has been deleted.');
        emails.add(email);
    Messaging.sendEmail(emails);
        
    }
    
}




whenever i am commenting the adderror line then mail is sending but at a time error showing and email sending not working 
email not sent to user .

Trigger : 

trigger checkDuplicateValue on Account (after insert)
{
    if(Trigger.isAfter)
    {   
        //Get list of Users
        Map<Id,User> userMap = new Map<Id,User>([SELECT Name, Email FROM User]);
        
        //Get all Ids in order to do a query
        //and bulkify the trigger
        Set<Id> accIdSet = new Set<Id>();
        for(Account a : Trigger.new)
        {
            accIdSet.add(a.Id);
        }
        
        List<Account> accList = [Select ID, owner.Id, Name, fax, phone 
                                 From Account 
                                 Where Id in :accIdSet];
        
        if(!accList.isEmpty())
        {
            //Create a map with the Name and the Owner Id
            //With the Owner Id I can look for the User in the first Map
            Map<String, Id> accMap = new Map<String, Id>();
            for(Account acc : accList)
            {
                accMap.put(acc.Name, acc.owner.Id);
            }
            
            for(Account acc : Trigger.new)
            {
                String accName = acc.Name;
                if(accMap.containsKey(accName))
                {
                    //Double check the name for the new account
                    Id userId = accMap.get(accName);
                    acc.adderror('Account already exists in your Organization with name ' + acc.Name);
                    
                    //Retrieve the owner's email
                    String theEmail = userMap.get(userId).Email;
                    EmailHelper.sendEmail(theEmail);
                }
            }
        }
    }
}



Class :

public with sharing class EmailHelper
{
    public static void sendEmail(String theEmail)
    {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        mail.setToAddresses(new String[] {theEmail});
        mail.setSenderDisplayName('My Email');
        mail.setSubject('My email subject');
        mail.setPlainTextBody('Process fails duplicate value');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

 
while inserting records into account if the phone number is duplicate then it will show an error and send email to account owner to modify the filed value .
how to write trigger for this .

Thanks,
Soubhagya