• Ashish Kumar Yadav
  • NEWBIE
  • 60 Points
  • Member since 2019

  • Chatter
    Feed
  • 1
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 22
    Questions
  • 28
    Replies
Hello,

I am facing following issue in Standrd List View.

1. Trying to search a record in asearch view.
2. But it's not working correctly.
3. I didn't get any result after searchig, But records are available in the list view.
4. 1000 Plus records are available in this list view.

Thanks In Advance.

Regards,
Soundar.
Hi Team,

Below apex trigger Getting the error message System.LimitException: Too many SOQL queries: 201.can you please help me to bulkified the code.
trigger InvestigatorObjectTrigger on Investigator__c (before update, after insert, after update, before insert){
    
    List<Messaging.SingleEmailMessage> allMails = new List<Messaging.SingleEmailMessage>();
    EmailTemplate etmpltmgr = [Select id from EmailTemplate where DeveloperName = 'template_for_investigation_mgr_vf' limit 1];
    EmailTemplate etmpltPrimary = [Select id from EmailTemplate where DeveloperName = 'template_for_investigation_unit_vf' limit 1];
    EmailTemplate etmpltAlt = [Select id from EmailTemplate where DeveloperName = 'template_for_investigation_alter_vf' limit 1];
    //List<Contact> lstAccount = [select id,Name from Contact limit 1];
    
    
    //for record attachments. 
    if(Trigger.isUpdate && Trigger.isBefore){
       //Set<String> lstIds = new Set<String>();
        profile sAdmID = [select id from profile  where name ='System Administrator'];
        for(Investigator__c inv : trigger.new){
            
            //Complaint__c cmpl = [select id,Name, Complaint_status__c from Complaint__c where Id =: inv.Complaint__c];
            
            /*if(cmpl.Complaint_status__c == 'Investigator / Reviewer'){
                if(inv.Investigation_Report_Attached__c == true || inv.Additional_Document_Attached__c == true){
                    lstIds.add(inv.Id);
                }
             }
             else{
                 inv.addError('You cannot update the record as case is at another stage.');
             } */
             if(inv.Investigation_Status__c == 'Investigation Closed'){
                
                    if(UserInfo.getProfileId() != sAdmID.Id){
                        inv.Investigator_Name1_c__c = UserInfo.getFirstName()+' '+UserInfo.getLastName();
                        inv.Date_of_review__c = System.Today();
                    } 
             }  
        }
        
         /*
        if(lstIds.size()>0){
            List<Attachment> lstAttchment = [select id,Name,parentId from attachment where ParentId IN : lstIds];
            map<String,Attachment> mapOfAttachment = new map<String,Attachment>();
            
            for(Attachment att : lstAttchment){
            
                mapOfAttachment.put(att.ParentId,att);
            }
            
            for(Investigator__c inv : trigger.new){
            
                if(inv.Investigation_Report_Attached__c == true || inv.Additional_Document_Attached__c == true){
                    if(!mapOfAttachment.containsKey(inv.id)){
                        string Url = System.URL.getSalesforceBaseUrl().toExternalForm();                            
                        String str = '<html><Head><script>window.onload = function (){document.getElementById("errorDiv_ep").style.display = "none";window.open("/apex/AttachmentForAllObject?Id='+inv.Id+'","test","Height=400,width=800,top=200,left=300");}</script></Head><Body></Body></html>';
                        inv.addError('Please Attach File '+str, false);
                    }
                }                     
            }
        } */ 
    }
     
    // The following code is for shooting mails to investigator unit and chain and sharing of records .
    if(Trigger.isInsert){
    boolean myb = false;
        if(!test.isrunningtest()){
            notification_chain_enable_disable__c mc = notification_chain_enable_disable__c.getValues('Investigator Notification Chain');
            myb = mc.Is_Active__c;
        }
        else{
            myb = true;
        }      
          
        if(Trigger.isAfter){
        allMails = new List<Messaging.SingleEmailMessage>();
        List<Investigator__share> lastRecShare = new List<Investigator__share>();        
        String caseownername ='';
        
        for(Investigator__c inv : trigger.new){
            
            if(inv.PCC_Role__c != null){
            
            List<Sub_Directory__c> lstUser = [select id,SF_User__c,SF_User_Email__c,Category__c,SF_User_Name__c from Sub_Directory__c where Master_Directory__c =:inv.PCC_Role__c AND isActive__c = true  ];
            Complaint__c cmpl = [select id,Country__c,name,Contact_Person__c,epersonname__c ,Entry_Person_Email__c,Entry_Person_Phone__c,Company_Name__c,Contact_Email__c,Complaint_Type__c,Complaint_Date__c,Other_Comments__c from Complaint__c where id =: inv.Complaint__c];
            
            /*for(Sub_Directory__c usr : lstUser){
            
                if(usr.Category__c == 'Primary' || usr.Category__c == 'Alternate'){
                    caseownername = caseownername+', '+usr.SF_User_Name__c;
                }
            }*/
            
            for(Sub_Directory__c usr : lstUser){
                Boolean check = false;                
               // caseownername = caseownername.removestart(', ');
                if(inv.ownerId != usr.SF_User__c){
                    Investigator__share recShare = new Investigator__share();
                    
                    if(usr.Category__c == 'Primary' || usr.Category__c == 'Alternative'){
                        recShare.AccessLevel = 'Edit';
                         caseownername = caseownername+', '+usr.SF_User_Name__c;
                          check = true;
                    } 
                       
                    if(caseownername.contains(usr.SF_User_Name__c) == false){
                         check = true;
                        recShare.AccessLevel = 'Read';
                    }                 
                   
                    if(check){
                        recShare.ParentId = inv.Id;                  
                        recShare.UserOrGroupId = usr.SF_User__c;
                        lastRecShare.add(recShare);
                    }
                }
                
                if(myb){
                    Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
                    string Url = System.URL.getSalesforceBaseUrl().toExternalForm()+'/'+cmpl.Id;
                    msg.settargetObjectId(usr.SF_User__c);
                    msg.setWhatId(cmpl.Id);
                    if(usr.Category__c == 'Primary'){  
                       msg.setTemplateId(etmpltPrimary.Id);
                    }
                    if(usr.Category__c == 'Alternative'){
                        msg.setTemplateId(etmpltAlt.Id);
                    }
                    if(usr.Category__c == 'Manager'){
                       msg.setTemplateId(etmpltmgr.Id);
                    }
                    //msg.setToAddresses(new String[]{usr.SF_User_Email__c });
                    msg.setsaveAsActivity(false);
                    allMails.add(msg); 
                }         
          }              
        } 
        }
        
        if(lastRecShare.size()>0){
            System.debug('lastREcShare====>>>> '+lastRecShare);
            insert lastRecShare;
        }
        if(allMails.size()>0){
           Messaging.sendEmail(allMails);
        }
        }
    }
    
    //For status updation of complaint according to investigator status update.
    if(Trigger.isUpdate && Trigger.isAfter){
        Boolean chkStk = false;
        Boolean chkSales = false;
        Boolean chkNOreviewer = true;
        Boolean lastChk = false;
        List<Stakeholder__c> ReviewerRcds = new List<Stakeholder__c>();
        List<String> RevwCmpledLst = new List<String>();
         
        for(Investigator__c inv : trigger.new){
            
            if(inv.Investigation_Status__c == 'Investigation Closed' && trigger.oldMap.get(inv.Id).Investigation_Status__c != 'Investigation Closed'){
                
               Complaint__c cmpl = [select id,Investigation_Review_completed__c,name,Complaint_status__c,isSales__c,isReviewer__c,isStakeholder__c from Complaint__c where id =:inv.Complaint__c];
               
               if(cmpl.isReviewer__c == true){
                    system.debug('came inside rwchk truee loop');
                    chkNOreviewer = false;
                    //To check for reviewer records if they are present.
                    ReviewerRcds = [select id,name,Review_Completed__c,Complaint_for_Reviewer__c from Stakeholder__c where recordType.DeveloperName='Reviewer' and Complaint_for_Reviewer__c=:inv.Complaint__c ];
                    for(Stakeholder__c st :ReviewerRcds){
                        if(st.Review_Completed__c == true){
                            RevwCmpledLst.add(st.Id);
                        }
                    }
                    
                    if(RevwCmpledLst.size() != ReviewerRcds.size()){
                        cmpl.Complaint_status__c = 'Investigator / Reviewer';
                        update cmpl;
                    }
                    
                    if(RevwCmpledLst.size() == ReviewerRcds.size()){
                        cmpl.Investigation_Review_completed__c = DateTime.Now();
                        if(cmpl.isStakeholder__c == true){
                            chkStk = true;
                            chkSales = false;
                            lastChk = false;
                        }
                    
                    if(chkStk){
                        cmpl.Complaint_status__c = 'Stakeholder';
                        update cmpl;
                    }
                    if(!chkStk){
                        if(cmpl.isSales__c == true){
                            chkSales = true;
                            lastChk = false;
                        }
                        else{
                            lastChk = true;
                        }
                       
                    }
                    if(chkSales){
                        cmpl.Complaint_status__c = 'Sales';
                        update cmpl;
                    }
                    if(lastChk){
                        cmpl.Complaint_status__c = 'Complaint Closed';
                        update cmpl;
                    }
                   } 
                }
                if(chkNOreviewer){
                    cmpl.Investigation_Review_completed__c = DateTime.Now();
                    if(cmpl.isStakeholder__c == true){
                          chkStk = true;
                          chkSales = false;
                          lastChk = false;
                    }
                    if(chkStk){
                        cmpl.Complaint_status__c = 'Stakeholder';
                        update cmpl;
                    }
                    if(!chkStk){
                        if(cmpl.isSales__c == true){
                            chkSales = true;
                            lastChk = false;
                        }
                        else{
                            lastChk = true;
                        }
                    }
                    if(chkSales){
                        cmpl.Complaint_status__c = 'Sales';
                        update cmpl;
                    }
                    if(lastChk){
                        cmpl.Complaint_status__c = 'Complaint Closed';
                        update cmpl;
                    }
                }
            }
            if(inv.Investigation_Status__c == 'Send back to QRC' && trigger.oldMap.get(inv.Id).Investigation_Status__c != 'Send back to QRC'){
                Complaint__c cmp = new Complaint__c();
                cmp.id = inv.Complaint__c;
                cmp.Complaint_status__c = 'Assigned to QRC Postmaster';
                String Comment = '';
                if(inv.Comments__c != null){
                    if(inv.Comments__c.length() > 255){
                        Comment  = inv.Comments__c.substring(0,254);
                    }
                    else{
                        Comment  = inv.Comments__c;
                    }
                    cmp.Iu_send_back2qrc__c = Comment;
                }
                cmp.IU_Send_back_to_QRC_CHECKBOX__c = true;
                update cmp;
            }
            if(inv.Investigation_Status__c == 'Investigation / Review' && trigger.oldMap.get(inv.Id).Investigation_Status__c != 'Investigation / Review'){
                Complaint__c cmp = new Complaint__c();
                cmp.id = inv.Complaint__c;
                cmp.Complaint_status__c = 'Investigator / Reviewer';
                update cmp;
            }
        }    
    }
    
    //// added for batch sharing
    if(Trigger.isUpdate && Trigger.isAfter){
        List<Investigator__share> lastRecShare = new List<Investigator__share>();
        SET<Investigator__share> SetRecShare = new SEt<Investigator__share>();        
        List<Sub_Directory__c> lstUser = new List<Sub_Directory__c>();
        String caseownername ='';
        for(Investigator__c inv : trigger.new){
            
            
                lstUser = [select id,SF_User__c,SF_User_Email__c,Category__c,SF_User_Name__c from Sub_Directory__c where Master_Directory__c =:inv.PCC_Role__c AND isActive__c = true  ];
                for(Sub_Directory__c usr : lstUser){
                    Boolean check = false;                
                    if(inv.ownerId != usr.SF_User__c){
                        Investigator__share  recShare = new Investigator__share();
                        if(usr.Category__c == 'Primary' || usr.Category__c == 'Alternative'){
                            recShare.AccessLevel = 'Edit';
                            caseownername = caseownername+', '+usr.SF_User_Name__c;
                            check = true;
                        } 
                        if(caseownername.contains(usr.SF_User_Name__c) == false){
                            check = true;
                            recShare.AccessLevel = 'Read';
                        }                 
                        if(check){
                            recShare.ParentId = inv.Id;                  
                            recShare.UserOrGroupId = usr.SF_User__c;
                            SetRecShare.add(recShare);
                        }
                    }
                }
        }
        if(SetRecShare.size() > 0){
            lastRecShare.addall(SetRecShare);
            Upsert lastRecShare;
        }
    }    
}

 
Hi Team,
Please help me to write the test class.
public class AssignScheme {
    public Scheme_Assign_Master__c sam{get;set;}
    public List<Scheme_Assign_Master__c> lstAssignIndividual{get;set;}
    public List<Scheme_Assign_Master__c> lstRemoveIndividual{get;set;}
    public List<Scheme_Assign_Master__c> AssignToAll{get;set;}
    public List<Scheme_Assign_Master__c> SchemeList{get;set;}
    public List<Scheme_Assign_Master__c> searchList{get;set;}
    public List<Scheme_Master__c> smdatelist{get;set;}
    public Id samid;
    public Id RecordTypeId;
    public string query;
    public String strQuery;
    public Scheme_Master__c scheme_masterobj{get;set;}
    Public List<Scheme_Assign_Master__c>removeAccountList{get;set;} 
    Public List<Scheme_Master__c> lstSM {get;set;}
    public Integer rowIndex {get;set;}
    public String showdelId {get;set;}
    public String delId {get; set;}
    public List<Scheme_Assign_Master__c> lstsave{get;set;}
    public Account acc{get;set;}
    public String message{get;set;}
    public List<Scheme_Assign_Master__c> schemepgList{get;set;}
    
    public String scheme2{get;set;}
    public integer counter = 0; 
    public integer OffsetSize = 0;
    public integer LimitSize= 5;
    public integer totalRecs = 0;
    public List<Scheme_Assign_Master__c> membs {get;set;}
    public String sapp {get;set;}
    public String soqlQuery;
    
    public AssignScheme()
    {      
        sam=new Scheme_Assign_Master__c();
        acc=new Account();  
        
    }
    
    
    public AssignScheme(ApexPages.StandardController controller)
    { 
        sam=new Scheme_Assign_Master__c();
        this.controller = controller;
        SchemeList=new List<Scheme_Assign_Master__c>();
        
        Account acc=new Account();
        System.debug('@@@@'+controller.getId());
        acc = [ SELECT Id, Name FROM Account WHERE Id =: controller.getId()];
        System.debug('acc'+acc);
        
    }
  
    public void getControllerField(){
        System.debug('------>'+sam.Scheme_Master__c);
        lstSM = [Select Id,Scheme_Applicable_For__c from Scheme_Master__c where id =: sam.Scheme_Master__c];
        if(lstSM.size() > 0){
            System.debug('lstSM------>'+lstSM[0].Scheme_Applicable_For__c);
            sam.Scheme_Applicable_For__c = lstSM[0].Scheme_Applicable_For__c;
        }
        
    }
    
    public PageReference SearchIndividual(){
        
        try{
            if(sam.Scheme_Master__c == NULL){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please select the Scheme from "Scheme Name"'));
            }
            
            else if(sam.Account__c== NULL && sam.Retailer_Account__c== NULL){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please Check Distributor/Retailer Name'));
                return null;
            }
            else
            {
                Set<Id> distid = new Set<Id>();
                distid.add(sam.Retailer_Account__c);
                distid.add(sam.Account__c);
                System.debug('distid@@'+distid);
                System.debug('sam.Scheme_Master__c@@'+sam.Scheme_Master__c);
                
                
                if(sam.Scheme_Applicable_For__c =='Distributor'){
                    searchList=[select Id,Account__c,Retailer_Account__c,Scheme_Applicable_For__c,Retailer_Account__r.Name,Retailer_Account__r.SF_Customer_Code__c,Retailer_Account__r.SAP_Customer_Code__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c AND Account__c in :distid and Account__c != null];
                    System.debug('searchListacc'+searchList);
                }
                
                else if(sam.Scheme_Applicable_For__c =='Retailer'){
                    searchList=[select Id,Account__c,Retailer_Account__c,Scheme_Applicable_For__c,Retailer_Account__r.Name,Retailer_Account__r.SF_Customer_Code__c,Retailer_Account__r.SAP_Customer_Code__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c AND  Retailer_Account__c in :distid and Retailer_Account__c != null];
                    System.debug('searchListacc'+searchList);
                }
                
                else if(sam.Scheme_Applicable_For__c =='Both'){
                    searchList=[select Id,Account__c,Retailer_Account__c,Scheme_Applicable_For__c,Retailer_Account__r.Name,Retailer_Account__r.SF_Customer_Code__c,Retailer_Account__r.SAP_Customer_Code__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c AND Account__c in :distid and Account__c != null];
                    searchList.addAll([select Id,Account__c,Retailer_Account__c,Scheme_Applicable_For__c,Retailer_Account__r.Name,Retailer_Account__r.SF_Customer_Code__c,Retailer_Account__r.SAP_Customer_Code__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c AND  Retailer_Account__c in :distid and Retailer_Account__c != null]);
                }
                
                if(searchList.size() > 0 ){ 
                    System.debug('individual search list@@@'+searchList);
                    System.debug('search list size @@@'+searchList.size());
                 
                }
                else
                {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Distributor/Retailer is not assigned to this Scheme'));
                    
                }
            }
        }catch(Exception e){
            system.debug('Exception'+e.getLineNumber());
            system.debug('Exception'+e.getMessage());
            
        }
        return null;
    }
   
    public PageReference AssignIndividual(){
        try{
            if(sam.Scheme_Master__c == NULL){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please select the Scheme from "Scheme Name"'));
                return null; 
            }
            else if(sam.Account__c== NULL && sam.Retailer_Account__c== NULL){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please Check Distributor/Retailer Name'));
            }
           
           
                System.debug('---> assign individual');
                List<Id> ret_accid=new List<Id>();
                List<Id> dist_accid=new List<Id>();
                if(sam.Retailer_Account__c != null){
                    ret_accid.add(sam.Retailer_Account__c);
                }
                if(sam.Account__c != null){
                    dist_accid.add(sam.Account__c);
                }
                
                List<Scheme_Assign_Master__c> membs = new List<Scheme_Assign_Master__c>();
                if(sam.Scheme_Applicable_For__c =='Distributor'){
                    membs =[SELECT Id,Account__c,Retailer_Account__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c and Account__c in : dist_accid and Account__c != null];
                }
                else if(sam.Scheme_Applicable_For__c =='Retailer'){
                    membs =[SELECT Id,Account__c,Retailer_Account__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c and Retailer_Account__c in : ret_accid and Retailer_Account__c != null];
                }
                else if(sam.Scheme_Applicable_For__c =='Both'){
                    membs =[SELECT Id,Account__c,Retailer_Account__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c and Account__c in : dist_accid and Account__c != null];
                    list<Scheme_Assign_Master__c> membs1 = new list<Scheme_Assign_Master__c>();
                    membs1 =[SELECT Id,Account__c,Retailer_Account__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c and Retailer_Account__c in : ret_accid and Retailer_Account__c != null];
                    if(membs1.size() > 0){
                        membs.addAll(membs1);
                    }
                }
                
                Set<Id> accIds = new Set<Id>();
                for(Scheme_Assign_Master__c obj : membs){
                    if(obj.Retailer_Account__c != null){
                        accIds.add(obj.Retailer_Account__c);
                    }
                    if(obj.Account__c != null){
                        accIds.add(obj.Account__c);
                    }
                }
                
                lstAssignIndividual = new List<Scheme_Assign_Master__c>();
                scheme_masterobj=new Scheme_Master__c();
                
              
                if(sam.Scheme_Master__c != null){
                    if(sam.Retailer_Account__c != null){
                        if(!accIds.contains(sam.Retailer_Account__c)){
                            Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
                            objSAM.Retailer_Account__c = sam.Retailer_Account__c;
                            objSAM.Scheme_Master__c = sam.Scheme_Master__c;
                            lstAssignIndividual.add(objSAM);
                            accIds.add(sam.Retailer_Account__c);
                        }
                        else{
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Scheme master already assigned to this Retailer Account'));
                        }
                    }
                    
                    if(sam.Account__c != null){
                        if(!accIds.contains(sam.Account__c)){
                            Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
                            objSAM.Account__c = sam.Account__c;
                            objSAM.Scheme_Master__c = sam.Scheme_Master__c;
                            lstAssignIndividual.add(objSAM);
                            accIds.add(sam.Account__c);
                        }
                        else{
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Scheme master already assigned to this Distributer Account'));
                        }
                    }
                }
                
                
                if(lstAssignIndividual.size() > 0){
                    insert lstAssignIndividual;
                    
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,' Assign Individual Scheme to Distributor / Retailer Successfully.'));
                    
                    List<User> userList = new List<User>();
                    userList = [SELECT Id,Email,IsActive FROM User WHERE Profile.Name = 'System Administrator' AND IsActive = True ];
                    for(User u : userList){
                        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                        String[] toAddresses = new String[] {u.Email};
                            mail.setToAddresses(toAddresses);
                        mail.setSubject('Scheme Assign to Distributor/Retailer');
                        mail.setPlainTextBody('Scheme Assigned to Distributor/Retailer successfully');
                        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    }
                }
            }
        }
        catch(Exception e){
        }
        return null;
    }

    public PageReference showassigndel(){
        Scheme_Assign_Master__c  showdelacc=[select id from Scheme_Assign_Master__c where id =:showdelId limit 1];
        if(showdelacc !=null){
            try{
                delete showdelacc;
                getAccounts();
            } catch(DmlException e){
                ApexPages.addMessages(e);
            }
        }else{
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Distributor/Retailer is not assigned to this Scheme'));
            
        }
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,' Remove Scheme to Distributor / Retailer Successfully.'));
        
        return null;
    }
 
    public PageReference RemoveIndividual(){
        if(sam.Scheme_Master__c == NULL){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please select the Scheme from "Scheme Name"'));
            return null; 
        }
        else if(sam.Account__c== NULL && sam.Retailer_Account__c== NULL){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please Check Distributor/Retailer Name'));
        }
        
        else{
            Set<Id> accIds = new Set<Id>();
            lstRemoveIndividual = new List<Scheme_Assign_Master__c>();
            if(sam.Account__c != null){
                accIds.add(sam.Account__c);
            }
            if(sam.Retailer_Account__c != null){
                accIds.add(sam.Retailer_Account__c);
            }
            
            lstRemoveIndividual = [select id,Account__c,Retailer_Account__c from Scheme_Assign_Master__c where Scheme_Master__c =:sam.Scheme_Master__c and (Account__c in :accIds OR Retailer_Account__c in:accIds)];
            
            if(lstRemoveIndividual.size() > 0){
                Delete lstRemoveIndividual;
                ApexPages.addmessage(new 

            }
        }
        return null;   
    }
    
    
    public List<Scheme_Assign_Master__c> getAccounts() {  
        if(sam.Scheme_Master__c == NULL){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please select the Scheme from "Scheme Name"'));
            return null; 
        }
        else{
            totalRecs = [select count() from Scheme_Assign_Master__c];
            /*New code end here*/
            scheme2=sam.Scheme_Master__c;
            membs=new list<Scheme_Assign_Master__c>();
            if(sam.Scheme_Applicable_For__c =='Distributor'){
                membs =[SELECT Id,Account__c,Retailer_Account__c,Retailer_Account__r.Name,Retailer_Account__r.SF_Customer_Code__c,Retailer_Account__r.SAP_Customer_Code__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =:scheme2 and Account__c != null limit :LimitSize offset :OffsetSize]; 
                System.debug('membs---->'+membs.size());
            }
            else if(sam.Scheme_Applicable_For__c =='Retailer'){
                membs =[SELECT Id,Account__c,Retailer_Account__c,Retailer_Account__r.Name,Retailer_Account__r.SF_Customer_Code__c,Retailer_Account__r.SAP_Customer_Code__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =:scheme2 and Retailer_Account__c != null limit :LimitSize offset :OffsetSize]; 
                System.debug('membs---->'+membs.size());
            }
            else if(sam.Scheme_Applicable_For__c =='Both'){
                membs =[SELECT Id,Account__c,Retailer_Account__c,Retailer_Account__r.Name,Retailer_Account__r.SF_Customer_Code__c,Retailer_Account__r.SAP_Customer_Code__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =:scheme2 and Account__c != null limit :LimitSize offset :OffsetSize]; 
                list<Scheme_Assign_Master__c> membs1 = new list<Scheme_Assign_Master__c>();
                membs1 =[SELECT Id,Account__c,Retailer_Account__c,Retailer_Account__r.Name,Retailer_Account__r.SF_Customer_Code__c,Retailer_Account__r.SAP_Customer_Code__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =:scheme2 and Retailer_Account__c != null limit :LimitSize offset :OffsetSize]; 
                if(membs1.size() > 0){
                    membs.addAll(membs1);
                }
            }
          
            if(membs.size() > 0){
                for(Scheme_Assign_Master__c sm : membs){
                    System.debug('membs@@@'+sm.Id);
                }
            }
            else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Distributor/Retailer is not assigned to this Scheme'));
            }
        }
        return null;  
    }      
    
    private final ApexPages.StandardController controller; 
}
Hi Team,

Can you please help me to code coverage of below code.

Batch Apex
==========

global class  SchemeSendEmail implements Database.Batchable<sObject>,Database.AllowsCallouts,Database.Stateful
{
    public Id samid;
    public String SchemeApplicablefor;
    public String soqlQuery='';
    public SchemeSendEmail(Id SchemeMasterId,String SchemeApplicablefor){
        samid = SchemeMasterId;
        this.SchemeApplicablefor = SchemeApplicablefor;
        
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        System.debug('------------>'+SchemeApplicablefor);
        System.debug('------------>'+samid);
        
        
        Set<String> Ret_RTNames = new Set<String>();
        Set<String> Dist_RTNames = new Set<String>();
        Set<String> Both_RTNames = new Set<String>();
        
        if(SchemeApplicablefor == 'Distributor'){
            System.debug('inside distributer'+Dist_RTNames);
            Dist_RTNames.add('India SND');
            Dist_RTNames.add('Brand W');
            Dist_RTNames.add('H&H Modern Trade Distributor');
            Dist_RTNames.add('H&H Traditional Trade Distributor');
            System.debug('after added record type distributer'+Dist_RTNames);
        }
        if(SchemeApplicablefor == 'Retailer'){
            Ret_RTNames.add('H&H Modern Trade Retailer');
            Ret_RTNames.add('H&H Traditional Trade Retailer');
            Ret_RTNames.add('India SND Retailer');
            Ret_RTNames.add('Brand W Retailer');
            System.debug('after added record type Retailer'+Ret_RTNames);
        }
        if(SchemeApplicablefor == 'Both'){
            Both_RTNames.add('India SND');
            Both_RTNames.add('Brand W');
            Both_RTNames.add('H&H Modern Trade Distributor');
            Both_RTNames.add('H&H Traditional Trade Distributor');
            Both_RTNames.add('H&H Modern Trade Retailer');
            Both_RTNames.add('H&H Traditional Trade Retailer');
            Both_RTNames.add('India SND Retailer');
            Both_RTNames.add('Brand W Retailer');
            System.debug('after added record type both'+Both_RTNames);
        }
        
        System.debug('RTNames@@'+Both_RTNames);
        if(SchemeApplicablefor == 'Retailer'){
            soqlQuery ='SELECT Id, Name, RecordType.Name FROM Account where Recordtype.Name in : Ret_RTNames';
        }
        
        else if(SchemeApplicablefor == 'Distributor'){
            soqlQuery ='SELECT Id, Name, RecordType.Name FROM Account where Recordtype.Name in : Dist_RTNames';
        }
        
        
        else if(SchemeApplicablefor == 'Both'){
            soqlQuery ='SELECT Id, Name, RecordType.Name FROM Account where Recordtype.Name in : Both_RTNames';
        }
        
        
        if(samid == null){
            soqlQuery = '';
        }
        System.debug('soqlQuery@@@@-------->'+soqlQuery);
        return Database.getQueryLocator(soqlQuery);
    }
    
    global void execute(Database.BatchableContext BC, List<Account> scope){
        System.debug('Scope size ----->'+ scope.size());
        
        Set<id> accIdswithCurrentSM = new Set<id>();
        List<Scheme_Assign_Master__c> AssignToAll = new List<Scheme_Assign_Master__c>();
        
        
        Map<Id,Account> mapAccount = New Map<Id,Account>(scope);
        List<Scheme_Assign_Master__c> SchemeList;
        
        SchemeList=[select Id,Account__c,Retailer_Account__c,Scheme_Master__c from Scheme_Assign_Master__c where Scheme_Master__c =: samid and (Retailer_Account__c in : mapAccount.keySet() OR Account__c in : mapAccount.keySet())];
        System.debug('SchemeList@@'+SchemeList);
       
        for(Scheme_Assign_Master__c samObj :SchemeList){
            if(samObj.Account__c != null){
                accIdswithCurrentSM.add(samObj.Account__c);
            }
            if(samObj.Retailer_Account__c != null){
                accIdswithCurrentSM.add(samObj.Retailer_Account__c);
            }
        }
        System.debug('Scheme Master with id '+samid +' is Already assigned with accounts, count ->'+accIdswithCurrentSM.size());
        for(Account ac : mapAccount.values()){
            if(!accIdswithCurrentSM.contains(ac.Id)){                
               
                //check ac record type for the retailer account and update value in the retailer id accordingly.
               
                if(SchemeApplicablefor == 'Distributor'){
                    Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
                    objSAM.Account__c = ac.Id;
                    objSAM.Scheme_Master__c = samid;
                    AssignToAll.add(objSAM);
                }
                
                else if(SchemeApplicablefor == 'Retailer'){
                    Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
                    objSAM.Retailer_Account__c = ac.Id;
                    objSAM.Scheme_Master__c = samid;
                    AssignToAll.add(objSAM);
                }
                
                else if(SchemeApplicablefor == 'Both'){
                    Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
                    objSAM.Account__c = ac.Id;
                    objSAM.Scheme_Master__c = samid;
                    AssignToAll.add(objSAM);
                    Scheme_Assign_Master__c objSAM1 = new Scheme_Assign_Master__c();
                    objSAM1.Retailer_Account__c = ac.Id;
                    objSAM1.Scheme_Master__c = samid;
                    AssignToAll.add(objSAM1);
                }
            }
        }
        
        /* List<Account> retacc=[SELECT Id, Name, RecordType.Name FROM Account where Customer_RetailerAC__c in : mapAccount.keySet()];
        for(Account ac :retacc ){
        if(!accIdswithCurrentSM.contains(ac.Id)){
        Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
        objSAM.Account__c = ac.Id;
        objSAM.Scheme_Master__c = samid;
        AssignToAll.add(objSAM);
        }
        }
            */
        
        System.debug('Total SAM to be inserted ---->'+AssignToAll.size());
        if(AssignToAll.size() > 0){
            Database.insert(AssignToAll, false);
        }
    }
    
    global void finish(Database.BatchableContext BC)
    {
        AsyncApexJob a = [Select Id, Status,ExtendedStatus,NumberOfErrors, JobItemsProcessed,TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:BC.getJobId()];
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {a.CreatedBy.Email};
            mail.setToAddresses(toAddresses);
        mail.setSubject('Scheme Assign to All Distributor/Retailer' + a.Status);
        mail.setPlainTextBody('Scheme Assign to All Distributor/Retailer successfully :- ' + a.TotalJobItems +   'with '+ a.NumberOfErrors + ' failures.');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); 
    }
}
Requirement:-
1.My Requirement is while insert the record .check if Scheme_Applicable_at_PO_Creation__c  checkbox=true and Active__c=true and startDate and endDate between if any record is not assigned then only insert the record. 
2.second Requirement is while insert the record .check if Scheme_Applicable_at_PO_Creation__c  checkbox=false and Active__c=false and startDate and endDate between if any record is not assigned then only insert the record. 

Note:only two record is insert one is when checkbox is true and second one when checkbox is false.
User-added image
I have created query but not able to write complete logic.

//main logic
List <Scheme_Master__c> allschemeList = [SELECT Id, Name, Start_Date__c, End_Date__c, Scheme_Type__c, Scheme_Applicable_For__c, Active__c,Scheme_Applicable_at_PO_Creation__c FROM Scheme_Master__c where id =: sam.Scheme_Master__c AND Active__c=false AND Scheme_Applicable_at_PO_Creation__c=false AND createdDate >= : startDate AND createdDate <: endDate];

​​​​​​​
    List <Scheme_Master__c> allschemeList = [SELECT Id, Name, Start_Date__c, End_Date__c, Scheme_Type__c, Scheme_Applicable_For__c, Active__c,Scheme_Applicable_at_PO_Creation__c FROM Scheme_Master__c where id =: sam.Scheme_Master__c AND Active__c=true AND Scheme_Applicable_at_PO_Creation__c=true AND createdDate >= : startDate AND createdDate <: endDate];
    
      for (Scheme_Master__c sm : allschemeList) {
            
            //Iterate through each record within the allAccList using traditional for loop
            //This is needed so we can compare accList records to allAccList records
            for (Integer i = 0; i < allschemeList.size(); i++) {
                
                //If both records' name match and their IDs don't match then they are duplicates
                if ((sm.Name == allschemeList[i].Name) && (sm.id != allschemeList[i].id)) {
                
                //Checks the duplicate name checkbox within that record in allAccList    
                
                }
            }
      }


// this is my complete method where i am inserting the record it is working fine need to set above logic.
 public PageReference AssignIndividual(){
        try{
            if(sam.Scheme_Master__c == NULL){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please select the Scheme from "Scheme Name"'));
                return null; 
            }
            else if(sam.Account__c== NULL && sam.Retailer_Account__c== NULL){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please Check Distributor/Retailer Name'));
            }
            else {
                List<Scheme_main_Product_Detail__c> smpdlist = [SELECT Id, Name, Scheme_Master__c, Product__c, Scheme_Slabs_Details__c, Product_SubCategory__c, Product_Category__c, Merchandise_Category__c, article_code__c FROM Scheme_Main_Product_Detail__c where Scheme_Master__c=:sam.Scheme_Master__c];
                System.debug('smpdlist@@@@'+smpdlist);
                dateInfo = new Scheme_Master__c();
                Set<Id> activeSchemeIds = new Set<Id>();
                if(dateInfo.Start_Date__c != null & dateInfo.End_Date__c != null){
                    Date startDate=dateInfo.Start_Date__c;
                    Date endDate=dateInfo.End_Date__c ;
                    List<Scheme_Master__c> smstlist=[SELECT Id, Name, Start_Date__c, End_Date__c, Scheme_Type__c, Scheme_Applicable_For__c, Active__c,Scheme_Applicable_at_PO_Creation__c FROM Scheme_Master__c where id =: sam.Scheme_Master__c AND Active__c=true AND Scheme_Applicable_at_PO_Creation__c=true AND Start_Date__c =:startDate AND End_Date__c=:endDate];
                    System.debug('smstlist@@@@'+smstlist);
                }
                
                
                System.debug('---> assign individual');
                List<Id> ret_accid=new List<Id>();
                List<Id> dist_accid=new List<Id>();
                if(sam.Retailer_Account__c != null){
                    ret_accid.add(sam.Retailer_Account__c);
                }
                if(sam.Account__c != null){
                    dist_accid.add(sam.Account__c);
                }
                
                List<Scheme_Assign_Master__c> membs = new List<Scheme_Assign_Master__c>();
                if(sam.Scheme_Applicable_For__c =='Distributor'){
                    membs =[SELECT Id,Account__c,Retailer_Account__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c and Account__c in : dist_accid and Account__c != null];
                    System.debug('membs---->'+membs.size());
                }
                else if(sam.Scheme_Applicable_For__c =='Retailer'){
                    membs =[SELECT Id,Account__c,Retailer_Account__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c and Retailer_Account__c in : ret_accid and Retailer_Account__c != null];
                    System.debug('membs---->'+membs.size());
                }
                else if(sam.Scheme_Applicable_For__c =='Both'){
                    membs =[SELECT Id,Account__c,Retailer_Account__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c and Account__c in : dist_accid and Account__c != null];
                    list<Scheme_Assign_Master__c> membs1 = new list<Scheme_Assign_Master__c>();
                    membs1 =[SELECT Id,Account__c,Retailer_Account__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c and Retailer_Account__c in : ret_accid and Retailer_Account__c != null];
                    if(membs1.size() > 0){
                        membs.addAll(membs1);
                        System.debug('membs1---->'+membs1.size());
                    }
                    System.debug('membs---->'+membs.size());
                }
                
                Set<Id> accIds = new Set<Id>();
                
                for(Scheme_Assign_Master__c obj : membs){
                    System.debug('-----------SAM ID ->'+obj.Id);
                    if(obj.Retailer_Account__c != null){
                        accIds.add(obj.Retailer_Account__c);
                    }
                    if(obj.Account__c != null){
                        accIds.add(obj.Account__c);
                    }
                }
                
                lstAssignIndividual = new List<Scheme_Assign_Master__c>();
                scheme_masterobj=new Scheme_Master__c();
                
                System.debug('Retailer_Account__c--->'+sam.Retailer_Account__c);
                System.debug('Scheme_Master__c--->'+sam.Scheme_Master__c);
                System.debug('Account__c--->'+sam.Account__c);
                
                if(sam.Scheme_Master__c != null){
                    if(sam.Retailer_Account__c != null){
                        if(!accIds.contains(sam.Retailer_Account__c)){
                            Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
                            objSAM.Retailer_Account__c = sam.Retailer_Account__c;
                            objSAM.Scheme_Master__c = sam.Scheme_Master__c;
                            lstAssignIndividual.add(objSAM);
                            accIds.add(sam.Retailer_Account__c);
                        }
                        else{
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Scheme master already assigned to this Retailer Account'));
                        }
                    }
                    
                    if(sam.Account__c != null){
                        if(!accIds.contains(sam.Account__c)){
                            Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
                            objSAM.Account__c = sam.Account__c;
                            objSAM.Scheme_Master__c = sam.Scheme_Master__c;
                            lstAssignIndividual.add(objSAM);
                            accIds.add(sam.Account__c);
                        }
                        else{
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Scheme master already assigned to this Distributer Account'));
                        }
                    }
                }
                
                
                if(lstAssignIndividual.size() > 0){
                    insert lstAssignIndividual;
                    
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,' Assign Individual Scheme to Distributor / Retailer Successfully.'));
                    
                    List<User> userList = new List<User>();
                    userList = [SELECT Id,Email,IsActive FROM User WHERE Profile.Name = 'System Administrator' AND IsActive = True ];
                    for(User u : userList){
                        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                        String[] toAddresses = new String[] {u.Email};
                            mail.setToAddresses(toAddresses);
                        mail.setSubject('Scheme Assign to Distributor/Retailer');
                        mail.setPlainTextBody('Scheme Assigned to Distributor/Retailer successfully');
                        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    }
                }
            }
        }
        catch(Exception e){
            System.debug('Exception at '+e.getLineNumber() +','+ e.getMessage());
        }
        return null;
    }
    
    
how can we avoid duplicate insert and give the message to user record already exist.find below method.


    public PageReference AssignIndividual(){
        try{
            if(sam.Scheme_Master__c == NULL){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please select the Scheme from "Scheme Name"'));
                return null; 
            }
            else if(sam.Account__c== NULL && sam.Retailer_Account__c== NULL){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please Check Distributor/Retailer Name'));
            }
            else {
              
                System.debug('---> assign individual');
                Map<Id,Account> mapAccount = New Map<Id,Account>([select id, name from account]);
                Set<Id> accIds = new Set<Id>();
                lstAssignIndividual = new List<Scheme_Assign_Master__c>();
                scheme_masterobj=new Scheme_Master__c();
                System.debug('Retailer_Account__c--->'+sam.Retailer_Account__c);
                System.debug('Scheme_Master__c--->'+sam.Scheme_Master__c);
                System.debug('Account__c--->'+sam.Account__c);
                if(sam.Scheme_Master__c != null){
                    if(sam.Retailer_Account__c != null){
                        try{
                            Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
                            objSAM.Retailer_Account__c = sam.Retailer_Account__c;
                            objSAM.Scheme_Master__c = sam.Scheme_Master__c;
                            lstAssignIndividual.add(objSAM);
                            accIds.add(sam.Retailer_Account__c);
                        }catch(Exception e){
                            System.debug('exception'+e.getLineNumber());
                            System.debug('exception message'+e.getMessage());
                        }
                    }
                    if(sam.Account__c != null){
                        Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
                        objSAM.Account__c = sam.Account__c;
                        objSAM.Scheme_Master__c = sam.Scheme_Master__c;
                        lstAssignIndividual.add(objSAM);
                        accIds.add(sam.Account__c);
                    }
                }
                
              
                if(lstAssignIndividual.size() > 0){
                    insert lstAssignIndividual;
                    
                }
               
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,' Assign Individual Scheme to Distributor / Retailer Successfully.'));
                return null; 
            }
        }
        catch(Exception e){
            System.debug('Exception'+e.getLineNumber());
            System.debug('exception'+e.getMessage());
        }
        return null;
    }
    
    
Hello team,

after delete the record table in not refresh please help me regarding this.

below is my vf code
===================

     <div class="slds-col" style="margin-top:10px;">
                    <p style="font-weight:600; padding:10px;">Distributor / Retailer List</p>
                </div>
            </div>
           
            <div style="border:1px solid #ccc; margin-top:0px;" class="slds-scrollable_x"  >
                 <apex:outputPanel id="TablePanel">
                    <table class="slds-table slds-table_cell-buffer slds-table_bordered slds-table_col-bordered slds-table_striped">
                        <thead>
                            <tr class="slds-line-height_reset">
                                <th class="" scope="col">
                                    <div class="slds-truncate" title="">Account Name</div>
                                </th>
                                <th class="" scope="col">
                                    <div class="slds-truncate" title="">SF Customer Code</div>
                                </th>
                                <th class="" scope="col">
                                    <div class="slds-truncate" title="">SAP Customer Code</div>
                                </th>
                                <th class="" scope="col">
                                    <div class="slds-truncate" title="">Action</div>
                                </th>
                                
                            </tr>
                        </thead>
                        <tbody>
                           
                            <apex:repeat value="{!membs}" var="awl" >
                            <tr class="slds-hint-parent">
                                <th scope="row">
                                    <div class="slds-form-element__control">{!awl.Account__r.Name}</div>
                                </th>
                                <td data-label="" class="fromvalue">
                                    <div class="slds-form-element__control">{!awl.Account__r.SF_Customer_Code__c}</div>
                                </td>
                                <td data-label="" class="fromvalue">
                                    <div class="slds-form-element__control">{!awl.Account__r.SAP_Customer_Code__c}</div>
                                </td>
                               
                                <td data-label="">
                                     <apex:commandLink styleClass="slds-button slds-button_destructive"  value="Delete" action="{!showassigndel}" reRender="TablePanel" onclick="if(!confirm('Are you sure?')) return false;"  >
                                       <apex:param name="schemeId" value="{!awl.id}" assignTo="{!showdelId}"/>
                                    </apex:commandLink>
                                </td>
                            </tr>
                            </apex:repeat>
                                
                        </tbody>
                        
                        <tbody>
                            <apex:repeat value="{!searchList }" var="swl" >
                                <tr class="slds-hint-parent">
                                    <th scope="row">
                                        <div class="slds-form-element__control">{!swl.Account__r.Name}</div>
                                    </th>
                                    <td data-label="" class="fromvalue">
                                        <div class="slds-form-element__control">{!swl.Account__r.SF_Customer_Code__c}</div>
                                    </td>
                                    <td data-label="" class="fromvalue">
                                        <div class="slds-form-element__control">{!swl.Account__r.SAP_Customer_Code__c}</div>
                                    </td>
                                    
                                    <td data-label="">
                                        <apex:commandLink styleClass="slds-button slds-button_destructive"  value="Delete" action="{!Remove}" reRender="TablePanel">
                                            <apex:param name="schemeIdParam" value="{!swl.id}" assignTo="{!delId}"/>
                                        </apex:commandLink>
                                        
                                    </td>
                                </tr>
                            </apex:repeat>
                        </tbody>
                    </table>
                </apex:outputPanel>
            </div>
Hello Team ,

I want to check duplicate insert the record.if duplicate value found give the message else insert the record.


find below code
==============



  Set<Id> accIds = new Set<Id>();
            lstAssignIndividual = new List<Scheme_Assign_Master__c>();
            scheme_masterobj=new Scheme_Master__c();
            if(sam.Scheme_Master__c != null){
                if(sam.Retailer_Account__c != null){
                    Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
                    objSAM.Account__c = sam.Retailer_Account__c;
                    objSAM.Scheme_Master__c = sam.Scheme_Master__c;
                    lstAssignIndividual.add(objSAM);
                    accIds.add(sam.Retailer_Account__c);
                    
                }
                if(sam.Account__c != null){
                    Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
                    objSAM.Account__c = sam.Account__c;
                    objSAM.Scheme_Master__c = sam.Scheme_Master__c;
                    lstAssignIndividual.add(objSAM);
                    accIds.add(sam.Account__c);
                }
            }
            
            List<User> userList = new List<User>();
            if(lstAssignIndividual.size() > 0){
                insert lstAssignIndividual;
                userList = [SELECT Id,Email,IsActive FROM User WHERE Profile.Name = 'System Administrator' AND IsActive = True ];
            }
            
          
Hello Team,

I want to delete the row in table.please help me regarding this.
User-added image

// Remove logic not working
// Code For Remove Account using Delete Icon.
    public PageReference Remove(){
     rowIndex = Integer.valueOf(ApexPages.currentPage().getParameters().get('rowIndex'));
        System.debug('rowIndex'+rowIndex);
        membs.remove(rowIndex);
        return null;
    }

//getting the record properly

public List<Scheme_Assign_Master__c> getAccounts() {  
      totalRecs = [select count() from Scheme_Assign_Master__c];
      String scheme2=sam.Scheme_Master__c;
       membs=new list<Scheme_Assign_Master__c>();
       membs =[SELECT Id,Account__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c from Scheme_Assign_Master__c where Scheme_Master__c =:scheme2 limit :LimitSize offset :OffsetSize]; 
        System.debug('Values are ' + membs);  
        return null;  
  
    }      
    ////////////////******   pagination logic *****************///////
    public void FirstPage()
    {
        OffsetSize = 0;
        getAccounts();
        
    }
    public void previous()
    {
        OffsetSize = (OffsetSize-LimitSize);
        getAccounts();
        
    }
    public void next()
    {
        OffsetSize =( OffsetSize + LimitSize);
        getAccounts();
        
    }
    public void LastPage()
    {
        OffsetSize = totalrecs - math.mod(totalRecs,LimitSize);
        System.debug('OffsetSize--'+OffsetSize);
        getAccounts();
        
    }
    public boolean getprev()
    {
        System.debug('prev'+OffsetSize);
        if(OffsetSize == 0){
            return true;
        }
        else {
            return false;
        }
    }
    public boolean getnxt()
    {
        if((OffsetSize + LimitSize) > totalRecs){
            return true;
        }
        else {
            return false;
        }
    }   

   
Hello Team ,

anyone please help me regarding to display the record using pagination.i want to display the record on button click.getting the error-Unknown property 'AssignScheme.membs'.i am calling the method below button.


vf page
=======
 <apex:commandButton styleClass="slds-button slds-button_brand" value="Show Asignment" action="{!getAccount_apex}" onclick="reloadPage()" reRender="outptText">
                                    </apex:commandButton>

 <apex:repeat value="{!membs }" var="awl" >
                            <tr class="slds-hint-parent">
                                <th scope="row">
                                    <div class="slds-form-element__control">{!awl.scheme.Account__r.Name}</div>
                                </th>
                                <td data-label="" class="fromvalue">
                                    <div class="slds-form-element__control">{!awl.scheme.Account__r.SF_Customer_Code__c}</div>
                                </td>
                                <td data-label="" class="fromvalue">
                                    <div class="slds-form-element__control">{!awl.scheme.Account__r.SAP_Customer_Code__c}</div>
                                </td>
                               
                                <td data-label="">
                                    
                                        <apex:commandButton styleClass="slds-button slds-button_destructive"  value="Delete" action="{!Remove}" onclick="reloadPage()" >
                                            </apex:commandButton>
                                    
                                </td>
                            </tr>
                            </apex:repeat>
                                
                        </tbody>
apex code
===========
 public List<Scheme_Assign_Master__c> getAccount_apex() {  
     String scheme2=sam.Scheme_Master__c;
     List<Scheme_Assign_Master__c> membs =Database.Query('SELECT Id,Account__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c from Scheme_Assign_Master__c where Scheme_Master__c =:scheme2 LIMIT :blockSize OFFSET :index'); 
        System.debug('Values are ' + membs);  
        return membs;  
  
    }      
      
    public void beginning() {  
  
        index = 0;  
  
    }  
      
    public void previous() {  
  
        index = index - blockSize;  
  
    }  
      
    public void next() {  
  
        index = index + blockSize;  
  
    }  
  
    public void end() {  
  
        index = totalrecs - math.mod(totalRecs,blockSize);  
  
    }          
      
    public boolean getprev() {  
        if(index == 0)  
            return true;  
        else  
            return false;  
  
    }    
      
    public boolean getnxt() {  
  
        if((index + blockSize) > totalRecs)  
        return true;  
        else  
        return false;  
  
    }      
   
Please help me regarding this on priority basis.


i try below  code as well as but not working

===================
 public void getAccount_apex(){
        try{
            String scheme2=sam.Scheme_Master__c;
            strQuery ='SELECT Id,Account__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c from Scheme_Assign_Master__c where Scheme_Master__c =:scheme2'; 
            System.debug('strQuery@@'+strQuery);
            if(totalRecs !=null && totalRecs ==0){
                List<Scheme_Assign_Master__c> schemeTemp;
                schemeTemp = Database.query(strQuery);
                totalRecs = (schemeTemp !=null && schemeTemp.size()>0)?schemeTemp.size():0;
            }
            strQuery += ' ORDER BY Name  ASC, CreatedDate DESC LIMIT :LimitSize OFFSET :OffsetSize';
            schemepgList=Database.query(strQuery);
            System.debug('schemepgList---->'+schemepgList);
             for(Scheme_Assign_Master__c sch:schemepgList){
             Wrapschemelist.add(new wrapscheme(sch));          
           }
        }catch(Exception e){
           System.debug('exception'+e.getMessage());
           System.debug('exception'+e.getLineNumber());
             OffsetSize = 0;
            getprev();
            getnxt();
        }
        
        
    }
    
    
  public class Wrapscheme {    
        public Scheme_Assign_Master__c scheme {get;set;}
        public Wrapscheme(Scheme_Assign_Master__c pr){     
            scheme=pr;
        }
    }    
    
    ////////////////******   pagination logic *****************///////
    public void FirstPage()
    {
        OffsetSize = 0;
        getAccount_apex();
        
    }
    public void previous()
    {
        OffsetSize = (OffsetSize-LimitSize);
        getAccount_apex();
        
    }
    public void next()
    {
        OffsetSize = OffsetSize + LimitSize;
        getAccount_apex();
        
    }
    public void LastPage()
    {
        OffsetSize = totalrecs - math.mod(totalRecs,LimitSize);
        System.debug('OffsetSize--'+OffsetSize);
        getAccount_apex();
        
    }
    public boolean getprev()
    {
        System.debug('prev'+OffsetSize);
        if(OffsetSize == 0){
            return true;
        }
        else {
            return false;
        }
    }
    public boolean getnxt()
    {
        if((OffsetSize + LimitSize) > totalRecs){
            return true;
        }
        else {
            return false;
        }
    }
Hello Team ,

I am facing issue not getting the record type in soqlQuery
User-added image

System.debug('------------>'+SchemeApplicablefor);
        System.debug('------------>'+samid);
        Set<String> RTNames = new Set<String>();
        
        if(SchemeApplicablefor == 'Distributer'){
            RTNames.add('India SND');
            RTNames.add('Brand W');
            RTNames.add('H&H Modern Trade Distributor');
            RTNames.add('H&H Traditional Trade Distributor');
        }
        if(SchemeApplicablefor == 'Retailer'){
            RTNames.add('H&H Modern Trade Retailer');
            RTNames.add('H&H Traditional Trade Retailer');
            RTNames.add('India SND Retailer');
            RTNames.add('Brand W Retailer');
        }
        if(SchemeApplicablefor == 'Both'){
            RTNames.add('India SND');
            RTNames.add('Brand W');
            RTNames.add('H&H Modern Trade Distributor');
            RTNames.add('H&H Traditional Trade Distributor');
            RTNames.add('H&H Modern Trade Retailer');
            RTNames.add('H&H Traditional Trade Retailer');
            RTNames.add('India SND Retailer');
            RTNames.add('Brand W Retailer');
        }
        
        String soqlQuery = 'SELECT Id, Name, RecordType.Name FROM Account where RecordType.Name in:RTNames';
        System.debug('soqlQuery@@'+soqlQuery);

Please help me to solve the issue.
In organaization pick list having two value .this is the record type 

scheme master having lookup field.if iam selecting in organazation india snd record type then only visible the record india snd record type this the requirement.

 <apex:inputField id ="sa"  value="{!sam.Scheme_Master__c}" />this is the lookup field which i am taking the input.

Hi Team,

My requirement is I want to display in account lookup account name with sap customer code but i am facing issue to display sap customer code .can anyone please help me regarding this.

Vf Page
=========

<apex:page controller="OrderAccountLookup" tabStyle="OrderAccountLookup__tab">
    <apex:includeScript value="{!$Resource.Jquery_06_09_17}"/>
    <style>
        .txtfield{width:65px; margin-bottom:5px;}
        
        table.bgmpop{
        border-collapse:collapse;
        border:1px solid #333;
        font-family:calibri; font-size:12px;
        }
        table.bgmpop th {
        border-collapse:collapse;
        background:#6B95A0; color:#fff;
        border-right:1px solid #fff; text-align:center;
        font-family:calibri; font-size:14px;
        padding:3px; border:1px solid #fff;
        }
        table.bgmpop td {
        color:#333; border:1px solid #ccc;
        font-family:calibri; font-size:12px;
        padding:3px; text-align:center;
        }
    </style> 
    
    <script>
  function confirmCancel() {
      var isCancel = confirm("Are you sure you wish to cancel?");
      if (isCancel) return true;
  
     return false;
  }  
    </script>
   
    <apex:form id="frm" >
       
        <apex:pageMessages id="showmsg"></apex:pageMessages>
        <apex:inputHidden value="{!targetField}" id="selectedAccId"/>
        <div style="background-color:#009EDB; border-radius:5px; padding:10px;" align="left">
            <b><apex:outputText value="Please Select Account" style="color:#FFFFFF; font-size:20px; font-family:calibri;"/></b>
        </div>
        
        <div align="left" style="padding:10px 5px 10px 5px; border:1px solid #ccc;">
            <apex:OutputLabel value="Account" style="color:#333;font-size:12px; font-weight:bold; padding-right:15px;" />
            <c:AutoCompleteV2 allowClear="true" importJquery="true" labelField="Name" id="acc" SObject="Account" valueField="Id" targetField="{!targetField}" style="width:200px"/>
        </div>
        
        <apex:repeat value="{!accountList}" var="acc" >
        </apex:repeat>
        
        <apex:commandButton id="con" value="Continue" action="{!Redirect}"  reRender="frm"  styleClass="ButtonStyle"  
                            style=" border:1px solid #cacaca; -webkit-border-radius: 4px; -moz-border-radius: 4px;border-radius: 4px;
                                   font-size:12px;font-family:arial, helvetica, sans-serif; margin-top:2px; padding:6px 8px 6px 8px; 
                                   text-decoration:none; font-weight:bold; color: #333;" />
        
        <apex:commandButton id="cancel" value="Cancel" action="{!Cancel}" styleClass="ButtonStyle" onclick="return confirmCancel()" immediate="true" style=" border:1px solid #cacaca; -webkit-border-radius: 3px; -moz-border-radius: 3px;border-radius: 3px;
                                                                                              font-size:12px;font-family:arial, helvetica, sans-serif; margin-top:2px; padding:6px 8px 6px 8px; 
                                                                                              text-decoration:none; font-weight:bold; color: #333;"   />
        
        <div style="padding:10px 8px 10px 8px;display:none" >
        </div>
        
    </apex:form>
    
</apex:page>


Autocompletev2_con
=================

public class AutoCompleteV2_Con {

    public String labelFieldVar{ get; set; }//for acc
    public String valueFieldVar{ get; set; }
    
    public String labelFieldSap{ get; set; }//for sap customer code
    public String valueFieldSapVar{ get; set; }
    
    public String sObjVal{get;set;}
    public Integer randomJsIden{get;set;}
    public Object cacheField{get;private set;} 
    
    private Object targetFieldVar;
    
    public AutoCompleteV2_Con(){
        randomJsIden = getRandomNumber(1000000);
        sObjVal='Account';
        labelFieldVar='Name';
        valueFieldVar='Id';
        labelFieldSap='SAP Customer Code';
        valueFieldSapVar='SAP_Customer_Code__c';
       // valueFieldOrgVar='';
    }
    
    /*Dummy setter Method*/
    public void setCacheField(Object cacheField){}
    
    public void setTargetFieldVar(Object targetFieldVar){    
        if(targetFieldVar != this.targetFieldVar){
            cacheField = getCacheFieldValue(targetFieldVar);
            this.targetFieldVar = targetFieldVar;
        }
    }
    
    public Object getTargetFieldVar(){
        return targetFieldVar;
    }

    
    /*
    *This method queries data according to the passed parameters
    ***/
    @RemoteAction
    public static List<Map<String,String>> getData(String sObjVal,String labelFieldVar,String labelFieldSap,String valueFieldVar,String valueFieldSapVar ,String whereClauseVar,String param){      
        List<Map<String,String>> responses = new List<Map<String,String>>();
        param = String.escapeSingleQuotes(param);
        for( Sobject sObj : Database.query('SELECT '+getFieldCSV(valueFieldVar,labelFieldVar)+''+getFieldCSV(valueFieldSapVar,labelFieldSap)+' FROM '+sObjVal+' WHERE '+labelFieldVar+''+labelFieldSap+' LIKE \'%'+param+'%\''+(String.isNotBlank(whereClauseVar) ? ' AND '+whereClauseVar : ''))){
            responses.add(new Map<String,String>{
                'id' => String.valueOf(sObj.get(valueFieldVar)),
                'text' => String.valueOf(sObj.get(labelFieldVar.split(',')[0])),
                'valueFieldSapVar' => String.valueOf(sObj.get(valueFieldSapVar)),
                'labelFieldSap' => String.valueOf(sObj.get(labelFieldSap))
            });
        }
        return responses;
    }  
    
    private Object getCacheFieldValue(Object targetFieldVar){
        Object retVal = targetFieldVar;
        if(targetFieldVar!=null){
            for(sObject sObj : Database.query('SELECT '+getFieldCSV(valueFieldVar,labelFieldVar)+''+getFieldCSV(valueFieldSapVar,labelFieldSap)+' FROM '+sObjVal+' WHERE '+valueFieldVar+''+valueFieldSapVar+' =:targetFieldVar')){
                retVal = sObj.get(labelFieldVar);
                break;
            }
        }
        
        return retVal;
    }
    
    /*
    *Random number generator to change the js function name if multiple components us
    ***/
    private Integer getRandomNumber(Integer size){
        Double d = Math.random() * size;
        return d.intValue();
    }

    private static String getFieldCSV(String vfld,String lfld){
        Set<String> fields = new Set<String>{vfld.toLowerCase(),lfld.toLowerCase()};
        return String.join(new List<String>(fields),',');
    }
    
}


Autocompletev2_con.vfp
=========================

<
<apex:component controller="AutoCompleteV2_Con" selfClosing="true">
    <apex:attribute name="SObject" description="SOQL Object to query"
        type="String" assignTo="{!sObjVal}" required="true" />
    <apex:attribute name="labelField"
        description="API Name of Field to display for label" type="String"
        required="true" assignTo="{!labelFieldVar}"/>
    <apex:attribute name="valueField"
        description="API Name of Field to display for value that is passed to the targetField"
        type="String" required="true" assignTo="{!valueFieldVar}"/>
    <apex:attribute name="targetField"
        description="Field of current object that will hold the selection."
        type="Object" assignTo="{!targetFieldVar}"/>
    <apex:attribute name="inputFieldId"
        description="Id of the field where the value will copied[Not generally required, used when you need to copy value to a field using js]"
        type="String" />
     <apex:attribute name="importJquery"
        description="Assign false if you dont want to jquery files"
        type="Boolean" default="true" />
    <apex:attribute name="syncManualEntry"
        description="Allow manual entry of data from autocomplete component."
        type="Boolean" default="true" />
    <apex:attribute name="allowClear" 
        description="Set true to give user a option to clear existing value" type="Boolean" default="true"/>
    <apex:attribute name="whereClause"
        description="Add where clause to the search"
        type="String" />
    <apex:attribute name="onChange"
        description="JS method to be invoked when the value changes"
        type="String" />
        
    <apex:attribute name="Style" description="style for the input component" type="String"/>
    <!--Required js files-->
    <apex:outputPanel rendered="{!importJquery}">
        <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"/>
    </apex:outputPanel>
        <apex:includeScript value="{!URLFOR($Resource.select2, 'select2-3.4.2/select2.js')}"/>
        <apex:stylesheet value="{!URLFOR($Resource.select2, 'select2-3.4.2/select2.css')}"/>
    <script>
        var v2{!randomJsIden};
        var prevVal{!randomJsIden};
        function autocompleteV2{!randomJsIden}(){
          var v2=this;
          jQuery(function($){
              v2.init($)
          });
        }
        
        autocompleteV2{!randomJsIden}.prototype={
          init : function($){
            var $elem = $( ".auto{!randomJsIden}" ).select2({
              minimumInputLength: 1,
              placeholder: "No value selected",
              allowClear : {!allowClear},
              query: function (query) {
                queryData{!randomJsIden}(query);
              },
              createSearchChoice:function(term, data) {
                if({!syncManualEntry} == true){
                  return {id:term, text:term};
                }
              }
            });

            $elem.on("select2-selecting", function(e) {
              $('.hiddenField{!randomJsIden}').val(e.val);
            });

            $elem.on("select2-removed", function(e) {
              $('.hiddenField{!randomJsIden}').val('');
            });

            if({!NOT(ISNULL(onChange))}){
                $elem.on("select2-selecting",{!IF(ISNULL(onChange), 'function(e){}',onChange)});
            }

            if({!cacheField !=''}){
              $elem.select2("data", {id: "{!targetFieldVar}", text: "{!cacheField}"})  
            }  
          },
                    
          triggerSearch :function(val){
            if(prevVal{!randomJsIden} != val){
              $=jQuery;
              prevVal{!randomJsIden} = val;
              var select = $('input.auto{!randomJsIden}');          
              var search = $('.select2-input')
              select.select2('open');
              search.val(val);
              search.trigger("input");
            }
          }
        }

         /*
        *This method queries data according to the passed parameter
        *and populates the combobox accordingly
        ***/    
        function queryData{!randomJsIden}(query){
          Visualforce.remoting.Manager.invokeAction(
            '{!$RemoteAction.AutoCompleteV2_Con.getData}','{!sObjVal}','{!labelFieldSap}','{!labelFieldVar}','{!valueFieldVar}','{!valueFieldSapVar}',"{!whereClause}",query.term,
            function(result, event){
              //if success
              if(event.status){ 
                var data = {results: []}
                data.results = result;                            
                query.callback( data);                           
              }
              else{
                alert('Invalid Field/Object API Name : '+event.message);
              }
            }, 
            {escape: false}
          );
        }         
    </script>
    
    <apex:inputText style="{!Style}" styleClass="auto{!randomJsIden}" value="{!cacheField}" />
 
    <apex:outputPanel id="hiddenPanel">
        <apex:inputText value="{!targetField}" id="hiddenField"
            styleClass="hiddenField{!randomJsIden}" style="display:none"/>
    </apex:outputPanel>
    <script>v2{!randomJsIden} = new autocompleteV2{!randomJsIden}({});</script>
</apex:component>
Hi Team,

Please help me i am facing the issue while redirecting the to another vf page . my requirement is after selecting account lookup click on continue button then redirect the page with account id in another vf page.


VF Page
========

<apex:page controller="OrderAccountLookup" tabStyle="OrderAccountLookup__tab">
    <apex:includeScript value="{!$Resource.Jquery_06_09_17}"/>
    <style>
        .txtfield{width:65px; margin-bottom:5px;}
        
        table.bgmpop{
        border-collapse:collapse;
        border:1px solid #333;
        font-family:calibri; font-size:12px;
        }
        table.bgmpop th {
        border-collapse:collapse;
        background:#6B95A0; color:#fff;
        border-right:1px solid #fff; text-align:center;
        font-family:calibri; font-size:14px;
        padding:3px; border:1px solid #fff;
        }
        table.bgmpop td {
        color:#333; border:1px solid #ccc;
        font-family:calibri; font-size:12px;
        padding:3px; text-align:center;
        }
    </style> 
    <script>
    function setContact(idc,val){
        document.getElementById(idc).value=val.value;
        
    }
    </script>  
    
    
    <apex:form id="frm" >
        <script>
        var accReq = "{!acc.Name}";
        if(accReq != '') {
            window.location="/apex/VisualforceName?id={!acc.Id}";
        }
        </script>
        
        <apex:pageMessages id="showmsg"></apex:pageMessages>
        <apex:inputHidden value="{!targetField}" id="selectedAccId"/>
        <div style="background:#A9B97A; border-radius:5px; padding:10px;" align="left">
            <b><apex:outputText value="Please Select Account" style="color:#fff;font-size:20px; font-family:calibri;"/></b>
        </div>
        
        <div align="left" style="padding:10px 5px 10px 5px; border:1px solid #ccc;">
            <apex:OutputLabel value="Account" style="color:#333;font-size:12px; font-weight:bold; padding-right:15px;" />
            <c:AutoCompleteV2 allowClear="true" importJquery="true" labelField="Name" SObject="Account" valueField="Id" targetField="{!targetField}" style="width:200px"/>
        </div>
        
        <apex:repeat value="{!accountList}" var="acc" >
        </apex:repeat>
        
        <apex:commandButton value="Continue" action="{!ShowContacts}"  reRender="frm"  styleClass="ButtonStyle" 
                            style=" border:1px solid #cacaca; -webkit-border-radius: 4px; -moz-border-radius: 4px;border-radius: 4px;
                                   font-size:12px;font-family:arial, helvetica, sans-serif; margin-top:2px; padding:6px 8px 6px 8px; 
                                   text-decoration:none; font-weight:bold; color: #333;" />
        
        <apex:commandButton value="Cancel" action="{!Cancel}" styleClass="ButtonStyle" style=" border:1px solid #cacaca; -webkit-border-radius: 3px; -moz-border-radius: 3px;border-radius: 3px;
                                                                                              font-size:12px;font-family:arial, helvetica, sans-serif; margin-top:2px; padding:6px 8px 6px 8px; 
                                                                                              text-decoration:none; font-weight:bold; color: #333;"   />
        
        <div style="padding:10px 8px 10px 8px;display:none" >
        </div>
        
    </apex:form>
    
</apex:page>


Apex class
============

public class OrderAccountLookup {
    public Account acc{get;set;}
    public String targetField {get;set;}
    public String busAssoID {get;set;}
    public String retURL {get;set;}
    public String conid {get;set;}
    public String message{get;set;}
    public List<Contact> contactList {get;set;}
    public List<Account> accountList {get;set;}
    public List<SelectOption> options {get;set;}
    public string bl1 {get;set;}
    public boolean contactsection {get;set;}
    public boolean desabl {get;set;}
    public String lkid{get;set;}
    public Account selectedAccount{get;set;}   
    
    public OrderAccountLookup()
    {
        acc=new Account();   
    }
    
    ApexPages.standardController a_sc = null;
    public OrderAccountLookup(ApexPages.standardController sc)
    {
        bl1='display:none';
        desabl = true;
        a_sc = sc;
        busAssoID = ApexPages.currentPage().getParameters().get('id');
        retURL = ApexPages.currentPage().getParameters().get('retURL'); 
        
        if(retURL != null){
            retURL = retURL.substring(1,16);
        }
        targetField = '';
        conid = '';
        message = '';
        contactList = new List<Contact>();
        accountList = new List<Account>();
        options = new List<SelectOption>();
        
        if(busAssoID == null){
            if(lkid!=null){
                
                RecordType recordBA = [select id,Name from RecordType where SobjectType = 'Account'];
                acc.recordTypeID = recordBA.Id;
            }else{
                selectedAccount = [select id,name from account];
                ShowContacts();
                Redirect();
            }
        }
        
        
    }
    public void ShowContacts(){
        message = '';
        List<Account> tempAccList = [select Id,Name,OwnerID,Owner.name from Account where Id =: targetField];        
        if(tempAccList.size() == 0 ){
            bl1='display:none';
            if(targetField==''){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please search and select required account.'));
            }
            else{
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'This account doesnot exist, Please select proper account.'));
            }
            
        }else {
           
            bl1='';
            accountList = [select Id,Name,OwnerID,Owner.name from Account where Id =: targetField];
            contactList = [select Id,Name from Contact where AccountId =: targetField];
            
            if(accountList.isEmpty()){
                desabl = true;
                message='No Account to display';
            }
            
            if(contactList.isEmpty()){
                desabl = true;
                message='No Contacts to display';
            }
            options = new List<SelectOption>();
            for(Contact conObj: contactList){
                options.add(new SelectOption(conObj.Id,''));
                desabl = false;
            }
        }  
    }
    public PageReference Redirect() {
        pagereference ref;
        if(acc.Id!=null){
           ref = new PageReference('/apex/Orders_Custom_Page_HO');
          ref.setRedirect(true);
        }
           return ref;
    }
    public pagereference cancel(){
        pagereference ref;
        if(retURL!=null){
          if(lkid!=null)
           {  
             ref = new pagereference('/'+lkid);             
            }
        }
        return ref; 
    }
    
}

 
Hi Team,

I am facing the issue.while try to give the edit  access to perticular user.my custom object department__c .in sharing setting department object have public read only access and profile level department object have read and edit access .I have created permission set with read and edit access object and field ''status'' and assign this to watson user but while login to perticular user watson I am not able to edit the page .

*I tried to using modify all access but problem is user able to edit all fields. in department object have one field is ''status'' I want to give the edit access that field only.what are possible way please help me with this.


Any help would be appreciated thank you in advance.
please find below code --

global class SendemailMSA30days implements Database.Batchable<sObject>,Database.AllowsCallouts,Database.Stateful
{
    List<Account> acclis;
    public SendemailMSA30days(){
    }    
    global Database.QueryLocator start(Database.BatchableContext BC){
        List<ID> idss=new List<ID>();
        String soqlQuery = ''; 
        date todaydate = system.Today();
        acclis=[SELECT ID,Name,MSA_expiry_Date__c,OwnerId,AccountOwnerName__c,OwnerEmail__c,OwnerManagerEmail__c FROM Account where MSA_expiry_Date__c!=NULL];
        System.debug('acclis=='+acclis.size());
        
         //new Code
        List<AccountTeamMember> ATM = new List<AccountTeamMember>(
        [SELECT UserId FROM AccountTeamMember WHERE AccountId =:accid.Id]);
         
        for(Account accid:acclis){
            Date contEnd = accid.MSA_expiry_Date__c;
            Integer dayDiff = todaydate.daysBetween(contEnd);
            System.debug('dayDiff@@'+dayDiff);
            if(dayDiff == 30){
                Id newId = accid.Id;
                idss.add(newId);
            }
        }
        System.debug('idss====>'+idss.size());
        
        if(idss.size()>0){
            soqlQuery='SELECT id,Name,MSA_expiry_Date__c,OwnerId,AccountOwnerName__c,OwnerEmail__c,OwnerManagerEmail__c FROM Account where Id IN:idss';
        }
        else{
            soqlQuery='SELECT id,Name,MSA_expiry_Date__c,OwnerId,AccountOwnerName__c,OwnerEmail__c,OwnerManagerEmail__c FROM Account LIMIT 0';
        }
        System.debug('soqlQuery-------->'+soqlQuery);
        return Database.getQueryLocator(soqlQuery);
    }
    
        
    global void execute(Database.BatchableContext BC, List<Account> scope){
        System.debug('scope==>'+scope);
        System.debug('scope==>'+scope.size());
        String Shivams=Account__c.getValues('Fetchadminsemail').AdminEmailAddress__c;
        String shalets=Account__c.getValues('Fetchadminsemail').BussinessHeadEmail__c;
        System.debug('Email'+Shivams+'-'+shalets);
        List<Id> userlistid = new List<Id>();
        List<User> uslist=new List<User>();
        String AccownerName;
        List < Messaging.SingleEmailMessage > mailList = new List < Messaging.SingleEmailMessage > (); 
        /* for (Account acc: scope) {
userlistid.add(acc.OwnerId);
}
System.debug('userlistid=='+userlistid);
System.debug('userlistidsize()=='+userlistid.size());*/
        List < String > toAddresses = new List < String > ();
        List < String > CCAddresses = new List < String > ();
        CCAddresses.add(Shivams);
        CCAddresses.add(shalets);
        // uslist=[SELECT Id, Email,Manager.Email FROM User where ID IN:userlistid];
        /* for(User c : [SELECT Id,Name,Email,Manager.Email FROM User where id IN:userlistid]){
AccownerName=c.Name;
toAddresses.add(c.Email);
CCAddresses.add(c.Manager.Email);
System.debug('toAddresses'+toAddresses);
System.debug('CCAddresses-111---'+CCAddresses);
System.debug('CCAddresses--111--'+CCAddresses.size());
}*/
        for(Account a:scope){
            //send single emails to these contacts
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            toAddresses.add(a.OwnerEmail__c);
            CCAddresses.add(a.OwnerManagerEmail__c);
            mail.setToAddresses(toAddresses);
            Date dt = a.MSA_expiry_Date__c;
            String dtStr = dt.format();
            System.debug('dtStr=='+dtStr);
            mail.setCcAddresses(CCAddresses);
            System.debug('toAddresses----'+toAddresses);
            System.debug('CCAddresses----'+CCAddresses);
            System.debug('CCAddresses----'+CCAddresses.size());
            mail.setSubject('Reminder for MSA expirying within 30 days');
            String messageBody  ='Hello '+a.AccountOwnerName__c+ '<br/>'; 
            messageBody +='<br/>';
            messageBody +='Your MSA signed with the company,'+a.Name+',is getting expired 30 days from today on '+dtStr+'. Please get in touch with the relevant stakeholders.<br/>';
            messageBody +='<br/>';
            messageBody +='Thank you,<br/>';
            messageBody +='Salesforce Admin';
            mail.setHtmlBody(messageBody);
            mailList.add(mail);
            toAddresses.clear();
            CCAddresses.clear();
            CCAddresses.add(Shivams);
            CCAddresses.add(shalets);
        }
        System.debug('mailList@@@'+mailList.size());
        Messaging.sendEmail(mailList);
    }
    global void finish(Database.BatchableContext BC)
    {
        
    }
}

 
Here is my Code

Apex Trigger
============
trigger EventUpdate on EventApproval__c (after update,before update) {
    
    List<String> ListAuto=new List<String>();
    //List<Event>lstEvent=new List<Event>();
    map<id,Event> mapevntupdate= new map<id,Event>();
    List<Id> EventToBeUpdatedId = new List<Id>();
    
    System.debug('trigger.new---'+trigger.new);    
    for(EventApproval__c EvAppr:trigger.new){
        ListAuto.add(EvAppr.EventAuto__c);
        EventToBeUpdatedId.add(EvAppr.Id);
    }
    System.debug('ListAuto---'+ListAuto);
    if(trigger.isAfter && Onetimeinsertupdate.EventUpdatetrigger){
        //lstEvent=[Select id,Ownerid,Description,Subject,Tavelled_From__c,Travelled_To__c,Kms_Travelled__c,Public_Transport_Fare__c,EventAuto__c,Reimbursement_Amount__c from Event where (EventAuto__c !=Null and EventAuto__c in :ListAuto) ];
        
            
            mapevntupdate=new map<id,Event>([Select id,Ownerid,Telephone_call_type__c,EventSubject__c,Description,Subject,Tavelled_From__c,
                      Travelled_To__c,Kms_Travelled__c,Public_Transport_Fare__c,
                                             EventAuto__c,Reimbursement_Amount__c,
                                             Sales_Manager_Assistance__c 
                                             from Event 
                                             where (EventAuto__c !=Null and EventAuto__c in :ListAuto) ]);
       
        system.debug('-----------map---'+ mapevntupdate.values());    
        for(EventApproval__c EvAppr:trigger.new){
            for(Event ev: mapevntupdate.values()){
                if(EvAppr.EventAuto__c==ev.EventAuto__c){
                    ev.Tavelled_From__c=EvAppr.Tavelled_From__c;   
                    ev.Travelled_To__c=Evappr.Travelled_To__c;
                    ev.Kms_Travelled__c=EvAppr.Kms_Travelled__c;
                    ev.Public_Transport_Fare__c=EvAppr.Public_Transport_Others_Fare__c;
                    //ev.Reimbursement_Amount__c=Integer.valueof(EvAppr.Reimbursement_Amount__c); 
                    ev.Description=EvAppr.Description__c;   
                    ev.Public_Transport_Mode__c=Evappr.Public_Transport_Mode__c;
                    ev.Conveyance_Mode__c=EvAppr.Conveyance_Mode__c;
                    ev.Status__c=EvAppr.Status1__c;
                    ev.Sales_Manager_Assistance__c=EvAppr.Sales_Manager_Assistance__c;
                    
                    // new code added by Ashish
                    ev.Telephone_call_type__c=EvAppr.Telephone_call_type__c;
                    ev.EventSubject__c=EvAppr.EventSubject__c;
                   // ev.Reason_for_winning__c=EvAppr.Reason_for_winning__c;
                  //  ev.Reason_for_losing__c=EvAppr.Reason_for_losing__c;
                   // ev.Reason_for_dropping__c=EvAppr.Reason_for_dropping__c;
                  //  ev.OtherDetails__c=EvAppr.OtherDetails__c;
                  //  ev.OtherDetails1__c=EvAppr.OtherDetails1__c;
                  //  ev.OtherDetails2__c=EvAppr.OtherDetails2__c;//Code End Here

                }
                
                
            } 
        }     
        
        // Logic for updating the Event Status and Comment 
        
        
        List<ProcessInstance>lstprocess = [Select p.TargetObjectId, p.Status, (Select StepStatus,Comments From Steps where StepStatus!='Started') From ProcessInstance p where TargetObjectId in :trigger.newMap.keyset()];
        if(lstprocess .size()>0){ 
            for(Event ev:mapevntupdate.values()){ 
                for(ProcessInstance step :lstprocess ){
                    for( ProcessInstanceStep st:step.Steps){
                        ev.Comments__c=st.Comments; 
                        
                        system.debug('--------------------Steps Ststus----- '+st.StepStatus);
                        system.debug('##########+comments are----'+st.Comments);
                    }
                    /*if(step.Status!='Started'){
ev.Status__c=step.Status;
}else{
ev.Status__c='Pending';
}*/
                    
                    ev.Approved_Date__c=system.today();
                    system.debug('@@@@@@Approval Status---'+step.Status);
                }
                
            }
            
        }  
        system.debug('&&&&&&&&&&&&&&&&&&'+mapevntupdate.size());
        if(mapevntupdate.size()>0){
            system.debug('&&&&&&&&&&&&&&&&&&');
            Onetimeinsertupdate.eventupdateflag=false;
            Onetimeinsertupdate.EventUpdatetrigger = false;
            //update lstEvent;
            update mapevntupdate.values();
            system.debug('************'+mapevntupdate.size());
            
        }
        
        
        //MyFutureClass.myMethod(EventToBeUpdatedId,ListAuto);
        
        
        Onetimeinsertupdate.EventUpdatetrigger=false;
    }
    if(Trigger.isBefore){
        List<ProcessInstance>lstprocess = [Select p.TargetObjectId, p.Status, (Select StepStatus, Comments From 
                                                                               
                                                                               Steps where StepStatus!='Started') From ProcessInstance p where TargetObjectId in :trigger.newMap.keyset()];
        if(lstprocess .size()>0){ 
            for(EventApproval__c Ev:trigger.new){ 
                for(ProcessInstance step :lstprocess ){
                    for( ProcessInstanceStep st:step.Steps){
                        ev.Comments__c=st.Comments; 
                        
                        system.debug('--------------------Steps Ststus----- '+st.StepStatus);
                        system.debug('##########+comments are----'+st.Comments);
                    }
                    
                    /* if(step.Status!='Started'){
ev.Status1__c=step.Status;
}else{
ev.Status1__c='Pending';
}*/
                    //ev.Status1__c=step.Status;
                    // ev.Approved_Date__c=system.today();
                    system.debug('@@@@@@Approval Status---'+step.Status);
                }
                
                
            }
        }
        
    }
       
}


Test Class 27 percent code coverage 
============================
@isTest
public class TestEventUpdateTest {
public static testMethod void testcontroller(){
test.startTest();
    
Account acc=new Account();
acc.Name='test Account';
Opportunity opp = new Opportunity();
opp.Accountid = acc.id;
opp.StageName = '00-Pending';
opp.CloseDate = system.today();
opp.name = 'Test Opportunity';
opp.Hardware__c=true;
opp.No_Of_Units_Of_Hardware__c=5;
opp.INR_Hardware_Contract_Value_In_Lacs__c=5;
opp.Product_Type__c='Hardware';
insert opp;
update opp;
    
Event objevent=new Event(WhatID = opp.id,Subject='visit');
objevent.DurationInMinutes = 1;
objevent.Subject='Test subject';
objevent.StartDateTime=System.today()-1;
objevent.Tavelled_From__c='kanpur';
objevent.Travelled_To__c='delhi';
objevent.Kms_Travelled__c=10;
objevent.Status__c='New';
objevent.Public_Transport_Fare__c=100;
insert objEvent;
objevent.Tavelled_From__c='lucknow';   
objevent.Travelled_To__c='mumbai';
objevent.Kms_Travelled__c=14;
objevent.Public_Transport_Fare__c=200; 
update objevent;
    
map<id,EventApproval__c> mapevntappupdate= new map<id,EventApproval__c>();
EventApproval__c objevent1=new EventApproval__c(); 
objevent1.Tavelled_From__c='kanpur';
objevent1.Travelled_To__c='delhi';
objevent1.Kms_Travelled__c=10;
objevent1.Kms_Travelled__c=10;
objevent1.Conveyance_Mode__c='test';
objevent1.Telephone_call_type__c='Service call';
objevent1.Reason_for_winning__c='Product quality';
objevent1.Reason_for_dropping__c='Insufficient budget';
objevent1.Reason_for_losing__c='Mapping';
objevent1.OtherDetails__c='Test';
objevent1.OtherDetails1__c='Test1';
objevent1.OtherDetails2__c='Test2';
insert objevent1;
    
objevent1.Tavelled_From__c='lucknow';   
objevent1.Travelled_To__c='mumbai';
objevent1.Kms_Travelled__c=14;
objevent1.Public_Transport_Mode__c='test';
objevent1.Conveyance_Mode__c='test';
objevent1.Sales_Manager_Assistance__c='test';
objevent1.Telephone_call_type__c='Service call';
objevent1.Reason_for_winning__c='Product quality';
objevent1.Reason_for_dropping__c='Insufficient budget';
objevent1.Reason_for_losing__c='Mapping';
objevent1.OtherDetails__c='Test';
objevent1.OtherDetails1__c='Test1';
objevent1.OtherDetails2__c='Test2';
update objevent1;


/*opp.StageName='Prospect';
update opp;
opp.StageName='Proposal in Play';
update opp;
opp.StageName='Demo';
update opp;
opp.StageName='Negotiation';
update opp;
opp.StageName='Closed Won';
update opp;*/
List<Opportunity> oppmapid = [SELECT Id, Name, StageName FROM Opportunity];
system.debug('oppmapID@@@@@@@@@@@@@@@@@@@'+oppmapid);
test.stopTest();
}
}
Hello team,

after delete the record table in not refresh please help me regarding this.

below is my vf code
===================

     <div class="slds-col" style="margin-top:10px;">
                    <p style="font-weight:600; padding:10px;">Distributor / Retailer List</p>
                </div>
            </div>
           
            <div style="border:1px solid #ccc; margin-top:0px;" class="slds-scrollable_x"  >
                 <apex:outputPanel id="TablePanel">
                    <table class="slds-table slds-table_cell-buffer slds-table_bordered slds-table_col-bordered slds-table_striped">
                        <thead>
                            <tr class="slds-line-height_reset">
                                <th class="" scope="col">
                                    <div class="slds-truncate" title="">Account Name</div>
                                </th>
                                <th class="" scope="col">
                                    <div class="slds-truncate" title="">SF Customer Code</div>
                                </th>
                                <th class="" scope="col">
                                    <div class="slds-truncate" title="">SAP Customer Code</div>
                                </th>
                                <th class="" scope="col">
                                    <div class="slds-truncate" title="">Action</div>
                                </th>
                                
                            </tr>
                        </thead>
                        <tbody>
                           
                            <apex:repeat value="{!membs}" var="awl" >
                            <tr class="slds-hint-parent">
                                <th scope="row">
                                    <div class="slds-form-element__control">{!awl.Account__r.Name}</div>
                                </th>
                                <td data-label="" class="fromvalue">
                                    <div class="slds-form-element__control">{!awl.Account__r.SF_Customer_Code__c}</div>
                                </td>
                                <td data-label="" class="fromvalue">
                                    <div class="slds-form-element__control">{!awl.Account__r.SAP_Customer_Code__c}</div>
                                </td>
                               
                                <td data-label="">
                                     <apex:commandLink styleClass="slds-button slds-button_destructive"  value="Delete" action="{!showassigndel}" reRender="TablePanel" onclick="if(!confirm('Are you sure?')) return false;"  >
                                       <apex:param name="schemeId" value="{!awl.id}" assignTo="{!showdelId}"/>
                                    </apex:commandLink>
                                </td>
                            </tr>
                            </apex:repeat>
                                
                        </tbody>
                        
                        <tbody>
                            <apex:repeat value="{!searchList }" var="swl" >
                                <tr class="slds-hint-parent">
                                    <th scope="row">
                                        <div class="slds-form-element__control">{!swl.Account__r.Name}</div>
                                    </th>
                                    <td data-label="" class="fromvalue">
                                        <div class="slds-form-element__control">{!swl.Account__r.SF_Customer_Code__c}</div>
                                    </td>
                                    <td data-label="" class="fromvalue">
                                        <div class="slds-form-element__control">{!swl.Account__r.SAP_Customer_Code__c}</div>
                                    </td>
                                    
                                    <td data-label="">
                                        <apex:commandLink styleClass="slds-button slds-button_destructive"  value="Delete" action="{!Remove}" reRender="TablePanel">
                                            <apex:param name="schemeIdParam" value="{!swl.id}" assignTo="{!delId}"/>
                                        </apex:commandLink>
                                        
                                    </td>
                                </tr>
                            </apex:repeat>
                        </tbody>
                    </table>
                </apex:outputPanel>
            </div>
Hi Team,

Below apex trigger Getting the error message System.LimitException: Too many SOQL queries: 201.can you please help me to bulkified the code.
trigger InvestigatorObjectTrigger on Investigator__c (before update, after insert, after update, before insert){
    
    List<Messaging.SingleEmailMessage> allMails = new List<Messaging.SingleEmailMessage>();
    EmailTemplate etmpltmgr = [Select id from EmailTemplate where DeveloperName = 'template_for_investigation_mgr_vf' limit 1];
    EmailTemplate etmpltPrimary = [Select id from EmailTemplate where DeveloperName = 'template_for_investigation_unit_vf' limit 1];
    EmailTemplate etmpltAlt = [Select id from EmailTemplate where DeveloperName = 'template_for_investigation_alter_vf' limit 1];
    //List<Contact> lstAccount = [select id,Name from Contact limit 1];
    
    
    //for record attachments. 
    if(Trigger.isUpdate && Trigger.isBefore){
       //Set<String> lstIds = new Set<String>();
        profile sAdmID = [select id from profile  where name ='System Administrator'];
        for(Investigator__c inv : trigger.new){
            
            //Complaint__c cmpl = [select id,Name, Complaint_status__c from Complaint__c where Id =: inv.Complaint__c];
            
            /*if(cmpl.Complaint_status__c == 'Investigator / Reviewer'){
                if(inv.Investigation_Report_Attached__c == true || inv.Additional_Document_Attached__c == true){
                    lstIds.add(inv.Id);
                }
             }
             else{
                 inv.addError('You cannot update the record as case is at another stage.');
             } */
             if(inv.Investigation_Status__c == 'Investigation Closed'){
                
                    if(UserInfo.getProfileId() != sAdmID.Id){
                        inv.Investigator_Name1_c__c = UserInfo.getFirstName()+' '+UserInfo.getLastName();
                        inv.Date_of_review__c = System.Today();
                    } 
             }  
        }
        
         /*
        if(lstIds.size()>0){
            List<Attachment> lstAttchment = [select id,Name,parentId from attachment where ParentId IN : lstIds];
            map<String,Attachment> mapOfAttachment = new map<String,Attachment>();
            
            for(Attachment att : lstAttchment){
            
                mapOfAttachment.put(att.ParentId,att);
            }
            
            for(Investigator__c inv : trigger.new){
            
                if(inv.Investigation_Report_Attached__c == true || inv.Additional_Document_Attached__c == true){
                    if(!mapOfAttachment.containsKey(inv.id)){
                        string Url = System.URL.getSalesforceBaseUrl().toExternalForm();                            
                        String str = '<html><Head><script>window.onload = function (){document.getElementById("errorDiv_ep").style.display = "none";window.open("/apex/AttachmentForAllObject?Id='+inv.Id+'","test","Height=400,width=800,top=200,left=300");}</script></Head><Body></Body></html>';
                        inv.addError('Please Attach File '+str, false);
                    }
                }                     
            }
        } */ 
    }
     
    // The following code is for shooting mails to investigator unit and chain and sharing of records .
    if(Trigger.isInsert){
    boolean myb = false;
        if(!test.isrunningtest()){
            notification_chain_enable_disable__c mc = notification_chain_enable_disable__c.getValues('Investigator Notification Chain');
            myb = mc.Is_Active__c;
        }
        else{
            myb = true;
        }      
          
        if(Trigger.isAfter){
        allMails = new List<Messaging.SingleEmailMessage>();
        List<Investigator__share> lastRecShare = new List<Investigator__share>();        
        String caseownername ='';
        
        for(Investigator__c inv : trigger.new){
            
            if(inv.PCC_Role__c != null){
            
            List<Sub_Directory__c> lstUser = [select id,SF_User__c,SF_User_Email__c,Category__c,SF_User_Name__c from Sub_Directory__c where Master_Directory__c =:inv.PCC_Role__c AND isActive__c = true  ];
            Complaint__c cmpl = [select id,Country__c,name,Contact_Person__c,epersonname__c ,Entry_Person_Email__c,Entry_Person_Phone__c,Company_Name__c,Contact_Email__c,Complaint_Type__c,Complaint_Date__c,Other_Comments__c from Complaint__c where id =: inv.Complaint__c];
            
            /*for(Sub_Directory__c usr : lstUser){
            
                if(usr.Category__c == 'Primary' || usr.Category__c == 'Alternate'){
                    caseownername = caseownername+', '+usr.SF_User_Name__c;
                }
            }*/
            
            for(Sub_Directory__c usr : lstUser){
                Boolean check = false;                
               // caseownername = caseownername.removestart(', ');
                if(inv.ownerId != usr.SF_User__c){
                    Investigator__share recShare = new Investigator__share();
                    
                    if(usr.Category__c == 'Primary' || usr.Category__c == 'Alternative'){
                        recShare.AccessLevel = 'Edit';
                         caseownername = caseownername+', '+usr.SF_User_Name__c;
                          check = true;
                    } 
                       
                    if(caseownername.contains(usr.SF_User_Name__c) == false){
                         check = true;
                        recShare.AccessLevel = 'Read';
                    }                 
                   
                    if(check){
                        recShare.ParentId = inv.Id;                  
                        recShare.UserOrGroupId = usr.SF_User__c;
                        lastRecShare.add(recShare);
                    }
                }
                
                if(myb){
                    Messaging.SingleEmailMessage msg = new Messaging.SingleEmailMessage();
                    string Url = System.URL.getSalesforceBaseUrl().toExternalForm()+'/'+cmpl.Id;
                    msg.settargetObjectId(usr.SF_User__c);
                    msg.setWhatId(cmpl.Id);
                    if(usr.Category__c == 'Primary'){  
                       msg.setTemplateId(etmpltPrimary.Id);
                    }
                    if(usr.Category__c == 'Alternative'){
                        msg.setTemplateId(etmpltAlt.Id);
                    }
                    if(usr.Category__c == 'Manager'){
                       msg.setTemplateId(etmpltmgr.Id);
                    }
                    //msg.setToAddresses(new String[]{usr.SF_User_Email__c });
                    msg.setsaveAsActivity(false);
                    allMails.add(msg); 
                }         
          }              
        } 
        }
        
        if(lastRecShare.size()>0){
            System.debug('lastREcShare====>>>> '+lastRecShare);
            insert lastRecShare;
        }
        if(allMails.size()>0){
           Messaging.sendEmail(allMails);
        }
        }
    }
    
    //For status updation of complaint according to investigator status update.
    if(Trigger.isUpdate && Trigger.isAfter){
        Boolean chkStk = false;
        Boolean chkSales = false;
        Boolean chkNOreviewer = true;
        Boolean lastChk = false;
        List<Stakeholder__c> ReviewerRcds = new List<Stakeholder__c>();
        List<String> RevwCmpledLst = new List<String>();
         
        for(Investigator__c inv : trigger.new){
            
            if(inv.Investigation_Status__c == 'Investigation Closed' && trigger.oldMap.get(inv.Id).Investigation_Status__c != 'Investigation Closed'){
                
               Complaint__c cmpl = [select id,Investigation_Review_completed__c,name,Complaint_status__c,isSales__c,isReviewer__c,isStakeholder__c from Complaint__c where id =:inv.Complaint__c];
               
               if(cmpl.isReviewer__c == true){
                    system.debug('came inside rwchk truee loop');
                    chkNOreviewer = false;
                    //To check for reviewer records if they are present.
                    ReviewerRcds = [select id,name,Review_Completed__c,Complaint_for_Reviewer__c from Stakeholder__c where recordType.DeveloperName='Reviewer' and Complaint_for_Reviewer__c=:inv.Complaint__c ];
                    for(Stakeholder__c st :ReviewerRcds){
                        if(st.Review_Completed__c == true){
                            RevwCmpledLst.add(st.Id);
                        }
                    }
                    
                    if(RevwCmpledLst.size() != ReviewerRcds.size()){
                        cmpl.Complaint_status__c = 'Investigator / Reviewer';
                        update cmpl;
                    }
                    
                    if(RevwCmpledLst.size() == ReviewerRcds.size()){
                        cmpl.Investigation_Review_completed__c = DateTime.Now();
                        if(cmpl.isStakeholder__c == true){
                            chkStk = true;
                            chkSales = false;
                            lastChk = false;
                        }
                    
                    if(chkStk){
                        cmpl.Complaint_status__c = 'Stakeholder';
                        update cmpl;
                    }
                    if(!chkStk){
                        if(cmpl.isSales__c == true){
                            chkSales = true;
                            lastChk = false;
                        }
                        else{
                            lastChk = true;
                        }
                       
                    }
                    if(chkSales){
                        cmpl.Complaint_status__c = 'Sales';
                        update cmpl;
                    }
                    if(lastChk){
                        cmpl.Complaint_status__c = 'Complaint Closed';
                        update cmpl;
                    }
                   } 
                }
                if(chkNOreviewer){
                    cmpl.Investigation_Review_completed__c = DateTime.Now();
                    if(cmpl.isStakeholder__c == true){
                          chkStk = true;
                          chkSales = false;
                          lastChk = false;
                    }
                    if(chkStk){
                        cmpl.Complaint_status__c = 'Stakeholder';
                        update cmpl;
                    }
                    if(!chkStk){
                        if(cmpl.isSales__c == true){
                            chkSales = true;
                            lastChk = false;
                        }
                        else{
                            lastChk = true;
                        }
                    }
                    if(chkSales){
                        cmpl.Complaint_status__c = 'Sales';
                        update cmpl;
                    }
                    if(lastChk){
                        cmpl.Complaint_status__c = 'Complaint Closed';
                        update cmpl;
                    }
                }
            }
            if(inv.Investigation_Status__c == 'Send back to QRC' && trigger.oldMap.get(inv.Id).Investigation_Status__c != 'Send back to QRC'){
                Complaint__c cmp = new Complaint__c();
                cmp.id = inv.Complaint__c;
                cmp.Complaint_status__c = 'Assigned to QRC Postmaster';
                String Comment = '';
                if(inv.Comments__c != null){
                    if(inv.Comments__c.length() > 255){
                        Comment  = inv.Comments__c.substring(0,254);
                    }
                    else{
                        Comment  = inv.Comments__c;
                    }
                    cmp.Iu_send_back2qrc__c = Comment;
                }
                cmp.IU_Send_back_to_QRC_CHECKBOX__c = true;
                update cmp;
            }
            if(inv.Investigation_Status__c == 'Investigation / Review' && trigger.oldMap.get(inv.Id).Investigation_Status__c != 'Investigation / Review'){
                Complaint__c cmp = new Complaint__c();
                cmp.id = inv.Complaint__c;
                cmp.Complaint_status__c = 'Investigator / Reviewer';
                update cmp;
            }
        }    
    }
    
    //// added for batch sharing
    if(Trigger.isUpdate && Trigger.isAfter){
        List<Investigator__share> lastRecShare = new List<Investigator__share>();
        SET<Investigator__share> SetRecShare = new SEt<Investigator__share>();        
        List<Sub_Directory__c> lstUser = new List<Sub_Directory__c>();
        String caseownername ='';
        for(Investigator__c inv : trigger.new){
            
            
                lstUser = [select id,SF_User__c,SF_User_Email__c,Category__c,SF_User_Name__c from Sub_Directory__c where Master_Directory__c =:inv.PCC_Role__c AND isActive__c = true  ];
                for(Sub_Directory__c usr : lstUser){
                    Boolean check = false;                
                    if(inv.ownerId != usr.SF_User__c){
                        Investigator__share  recShare = new Investigator__share();
                        if(usr.Category__c == 'Primary' || usr.Category__c == 'Alternative'){
                            recShare.AccessLevel = 'Edit';
                            caseownername = caseownername+', '+usr.SF_User_Name__c;
                            check = true;
                        } 
                        if(caseownername.contains(usr.SF_User_Name__c) == false){
                            check = true;
                            recShare.AccessLevel = 'Read';
                        }                 
                        if(check){
                            recShare.ParentId = inv.Id;                  
                            recShare.UserOrGroupId = usr.SF_User__c;
                            SetRecShare.add(recShare);
                        }
                    }
                }
        }
        if(SetRecShare.size() > 0){
            lastRecShare.addall(SetRecShare);
            Upsert lastRecShare;
        }
    }    
}

 
Hi Team,
Please help me to write the test class.
public class AssignScheme {
    public Scheme_Assign_Master__c sam{get;set;}
    public List<Scheme_Assign_Master__c> lstAssignIndividual{get;set;}
    public List<Scheme_Assign_Master__c> lstRemoveIndividual{get;set;}
    public List<Scheme_Assign_Master__c> AssignToAll{get;set;}
    public List<Scheme_Assign_Master__c> SchemeList{get;set;}
    public List<Scheme_Assign_Master__c> searchList{get;set;}
    public List<Scheme_Master__c> smdatelist{get;set;}
    public Id samid;
    public Id RecordTypeId;
    public string query;
    public String strQuery;
    public Scheme_Master__c scheme_masterobj{get;set;}
    Public List<Scheme_Assign_Master__c>removeAccountList{get;set;} 
    Public List<Scheme_Master__c> lstSM {get;set;}
    public Integer rowIndex {get;set;}
    public String showdelId {get;set;}
    public String delId {get; set;}
    public List<Scheme_Assign_Master__c> lstsave{get;set;}
    public Account acc{get;set;}
    public String message{get;set;}
    public List<Scheme_Assign_Master__c> schemepgList{get;set;}
    
    public String scheme2{get;set;}
    public integer counter = 0; 
    public integer OffsetSize = 0;
    public integer LimitSize= 5;
    public integer totalRecs = 0;
    public List<Scheme_Assign_Master__c> membs {get;set;}
    public String sapp {get;set;}
    public String soqlQuery;
    
    public AssignScheme()
    {      
        sam=new Scheme_Assign_Master__c();
        acc=new Account();  
        
    }
    
    
    public AssignScheme(ApexPages.StandardController controller)
    { 
        sam=new Scheme_Assign_Master__c();
        this.controller = controller;
        SchemeList=new List<Scheme_Assign_Master__c>();
        
        Account acc=new Account();
        System.debug('@@@@'+controller.getId());
        acc = [ SELECT Id, Name FROM Account WHERE Id =: controller.getId()];
        System.debug('acc'+acc);
        
    }
  
    public void getControllerField(){
        System.debug('------>'+sam.Scheme_Master__c);
        lstSM = [Select Id,Scheme_Applicable_For__c from Scheme_Master__c where id =: sam.Scheme_Master__c];
        if(lstSM.size() > 0){
            System.debug('lstSM------>'+lstSM[0].Scheme_Applicable_For__c);
            sam.Scheme_Applicable_For__c = lstSM[0].Scheme_Applicable_For__c;
        }
        
    }
    
    public PageReference SearchIndividual(){
        
        try{
            if(sam.Scheme_Master__c == NULL){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please select the Scheme from "Scheme Name"'));
            }
            
            else if(sam.Account__c== NULL && sam.Retailer_Account__c== NULL){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please Check Distributor/Retailer Name'));
                return null;
            }
            else
            {
                Set<Id> distid = new Set<Id>();
                distid.add(sam.Retailer_Account__c);
                distid.add(sam.Account__c);
                System.debug('distid@@'+distid);
                System.debug('sam.Scheme_Master__c@@'+sam.Scheme_Master__c);
                
                
                if(sam.Scheme_Applicable_For__c =='Distributor'){
                    searchList=[select Id,Account__c,Retailer_Account__c,Scheme_Applicable_For__c,Retailer_Account__r.Name,Retailer_Account__r.SF_Customer_Code__c,Retailer_Account__r.SAP_Customer_Code__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c AND Account__c in :distid and Account__c != null];
                    System.debug('searchListacc'+searchList);
                }
                
                else if(sam.Scheme_Applicable_For__c =='Retailer'){
                    searchList=[select Id,Account__c,Retailer_Account__c,Scheme_Applicable_For__c,Retailer_Account__r.Name,Retailer_Account__r.SF_Customer_Code__c,Retailer_Account__r.SAP_Customer_Code__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c AND  Retailer_Account__c in :distid and Retailer_Account__c != null];
                    System.debug('searchListacc'+searchList);
                }
                
                else if(sam.Scheme_Applicable_For__c =='Both'){
                    searchList=[select Id,Account__c,Retailer_Account__c,Scheme_Applicable_For__c,Retailer_Account__r.Name,Retailer_Account__r.SF_Customer_Code__c,Retailer_Account__r.SAP_Customer_Code__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c AND Account__c in :distid and Account__c != null];
                    searchList.addAll([select Id,Account__c,Retailer_Account__c,Scheme_Applicable_For__c,Retailer_Account__r.Name,Retailer_Account__r.SF_Customer_Code__c,Retailer_Account__r.SAP_Customer_Code__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c AND  Retailer_Account__c in :distid and Retailer_Account__c != null]);
                }
                
                if(searchList.size() > 0 ){ 
                    System.debug('individual search list@@@'+searchList);
                    System.debug('search list size @@@'+searchList.size());
                 
                }
                else
                {
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Distributor/Retailer is not assigned to this Scheme'));
                    
                }
            }
        }catch(Exception e){
            system.debug('Exception'+e.getLineNumber());
            system.debug('Exception'+e.getMessage());
            
        }
        return null;
    }
   
    public PageReference AssignIndividual(){
        try{
            if(sam.Scheme_Master__c == NULL){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please select the Scheme from "Scheme Name"'));
                return null; 
            }
            else if(sam.Account__c== NULL && sam.Retailer_Account__c== NULL){
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please Check Distributor/Retailer Name'));
            }
           
           
                System.debug('---> assign individual');
                List<Id> ret_accid=new List<Id>();
                List<Id> dist_accid=new List<Id>();
                if(sam.Retailer_Account__c != null){
                    ret_accid.add(sam.Retailer_Account__c);
                }
                if(sam.Account__c != null){
                    dist_accid.add(sam.Account__c);
                }
                
                List<Scheme_Assign_Master__c> membs = new List<Scheme_Assign_Master__c>();
                if(sam.Scheme_Applicable_For__c =='Distributor'){
                    membs =[SELECT Id,Account__c,Retailer_Account__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c and Account__c in : dist_accid and Account__c != null];
                }
                else if(sam.Scheme_Applicable_For__c =='Retailer'){
                    membs =[SELECT Id,Account__c,Retailer_Account__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c and Retailer_Account__c in : ret_accid and Retailer_Account__c != null];
                }
                else if(sam.Scheme_Applicable_For__c =='Both'){
                    membs =[SELECT Id,Account__c,Retailer_Account__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c and Account__c in : dist_accid and Account__c != null];
                    list<Scheme_Assign_Master__c> membs1 = new list<Scheme_Assign_Master__c>();
                    membs1 =[SELECT Id,Account__c,Retailer_Account__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =: sam.Scheme_Master__c and Retailer_Account__c in : ret_accid and Retailer_Account__c != null];
                    if(membs1.size() > 0){
                        membs.addAll(membs1);
                    }
                }
                
                Set<Id> accIds = new Set<Id>();
                for(Scheme_Assign_Master__c obj : membs){
                    if(obj.Retailer_Account__c != null){
                        accIds.add(obj.Retailer_Account__c);
                    }
                    if(obj.Account__c != null){
                        accIds.add(obj.Account__c);
                    }
                }
                
                lstAssignIndividual = new List<Scheme_Assign_Master__c>();
                scheme_masterobj=new Scheme_Master__c();
                
              
                if(sam.Scheme_Master__c != null){
                    if(sam.Retailer_Account__c != null){
                        if(!accIds.contains(sam.Retailer_Account__c)){
                            Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
                            objSAM.Retailer_Account__c = sam.Retailer_Account__c;
                            objSAM.Scheme_Master__c = sam.Scheme_Master__c;
                            lstAssignIndividual.add(objSAM);
                            accIds.add(sam.Retailer_Account__c);
                        }
                        else{
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Scheme master already assigned to this Retailer Account'));
                        }
                    }
                    
                    if(sam.Account__c != null){
                        if(!accIds.contains(sam.Account__c)){
                            Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
                            objSAM.Account__c = sam.Account__c;
                            objSAM.Scheme_Master__c = sam.Scheme_Master__c;
                            lstAssignIndividual.add(objSAM);
                            accIds.add(sam.Account__c);
                        }
                        else{
                            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,'Scheme master already assigned to this Distributer Account'));
                        }
                    }
                }
                
                
                if(lstAssignIndividual.size() > 0){
                    insert lstAssignIndividual;
                    
                    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,' Assign Individual Scheme to Distributor / Retailer Successfully.'));
                    
                    List<User> userList = new List<User>();
                    userList = [SELECT Id,Email,IsActive FROM User WHERE Profile.Name = 'System Administrator' AND IsActive = True ];
                    for(User u : userList){
                        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                        String[] toAddresses = new String[] {u.Email};
                            mail.setToAddresses(toAddresses);
                        mail.setSubject('Scheme Assign to Distributor/Retailer');
                        mail.setPlainTextBody('Scheme Assigned to Distributor/Retailer successfully');
                        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
                    }
                }
            }
        }
        catch(Exception e){
        }
        return null;
    }

    public PageReference showassigndel(){
        Scheme_Assign_Master__c  showdelacc=[select id from Scheme_Assign_Master__c where id =:showdelId limit 1];
        if(showdelacc !=null){
            try{
                delete showdelacc;
                getAccounts();
            } catch(DmlException e){
                ApexPages.addMessages(e);
            }
        }else{
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Distributor/Retailer is not assigned to this Scheme'));
            
        }
        ApexPages.addmessage(new ApexPages.message(ApexPages.severity.CONFIRM,' Remove Scheme to Distributor / Retailer Successfully.'));
        
        return null;
    }
 
    public PageReference RemoveIndividual(){
        if(sam.Scheme_Master__c == NULL){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please select the Scheme from "Scheme Name"'));
            return null; 
        }
        else if(sam.Account__c== NULL && sam.Retailer_Account__c== NULL){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please Check Distributor/Retailer Name'));
        }
        
        else{
            Set<Id> accIds = new Set<Id>();
            lstRemoveIndividual = new List<Scheme_Assign_Master__c>();
            if(sam.Account__c != null){
                accIds.add(sam.Account__c);
            }
            if(sam.Retailer_Account__c != null){
                accIds.add(sam.Retailer_Account__c);
            }
            
            lstRemoveIndividual = [select id,Account__c,Retailer_Account__c from Scheme_Assign_Master__c where Scheme_Master__c =:sam.Scheme_Master__c and (Account__c in :accIds OR Retailer_Account__c in:accIds)];
            
            if(lstRemoveIndividual.size() > 0){
                Delete lstRemoveIndividual;
                ApexPages.addmessage(new 

            }
        }
        return null;   
    }
    
    
    public List<Scheme_Assign_Master__c> getAccounts() {  
        if(sam.Scheme_Master__c == NULL){
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Please select the Scheme from "Scheme Name"'));
            return null; 
        }
        else{
            totalRecs = [select count() from Scheme_Assign_Master__c];
            /*New code end here*/
            scheme2=sam.Scheme_Master__c;
            membs=new list<Scheme_Assign_Master__c>();
            if(sam.Scheme_Applicable_For__c =='Distributor'){
                membs =[SELECT Id,Account__c,Retailer_Account__c,Retailer_Account__r.Name,Retailer_Account__r.SF_Customer_Code__c,Retailer_Account__r.SAP_Customer_Code__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =:scheme2 and Account__c != null limit :LimitSize offset :OffsetSize]; 
                System.debug('membs---->'+membs.size());
            }
            else if(sam.Scheme_Applicable_For__c =='Retailer'){
                membs =[SELECT Id,Account__c,Retailer_Account__c,Retailer_Account__r.Name,Retailer_Account__r.SF_Customer_Code__c,Retailer_Account__r.SAP_Customer_Code__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =:scheme2 and Retailer_Account__c != null limit :LimitSize offset :OffsetSize]; 
                System.debug('membs---->'+membs.size());
            }
            else if(sam.Scheme_Applicable_For__c =='Both'){
                membs =[SELECT Id,Account__c,Retailer_Account__c,Retailer_Account__r.Name,Retailer_Account__r.SF_Customer_Code__c,Retailer_Account__r.SAP_Customer_Code__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =:scheme2 and Account__c != null limit :LimitSize offset :OffsetSize]; 
                list<Scheme_Assign_Master__c> membs1 = new list<Scheme_Assign_Master__c>();
                membs1 =[SELECT Id,Account__c,Retailer_Account__c,Retailer_Account__r.Name,Retailer_Account__r.SF_Customer_Code__c,Retailer_Account__r.SAP_Customer_Code__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c,Scheme_Applicable_For__c from Scheme_Assign_Master__c where Scheme_Master__c =:scheme2 and Retailer_Account__c != null limit :LimitSize offset :OffsetSize]; 
                if(membs1.size() > 0){
                    membs.addAll(membs1);
                }
            }
          
            if(membs.size() > 0){
                for(Scheme_Assign_Master__c sm : membs){
                    System.debug('membs@@@'+sm.Id);
                }
            }
            else {
                ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error,'Distributor/Retailer is not assigned to this Scheme'));
            }
        }
        return null;  
    }      
    
    private final ApexPages.StandardController controller; 
}
Hi Team,

Can you please help me to code coverage of below code.

Batch Apex
==========

global class  SchemeSendEmail implements Database.Batchable<sObject>,Database.AllowsCallouts,Database.Stateful
{
    public Id samid;
    public String SchemeApplicablefor;
    public String soqlQuery='';
    public SchemeSendEmail(Id SchemeMasterId,String SchemeApplicablefor){
        samid = SchemeMasterId;
        this.SchemeApplicablefor = SchemeApplicablefor;
        
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        System.debug('------------>'+SchemeApplicablefor);
        System.debug('------------>'+samid);
        
        
        Set<String> Ret_RTNames = new Set<String>();
        Set<String> Dist_RTNames = new Set<String>();
        Set<String> Both_RTNames = new Set<String>();
        
        if(SchemeApplicablefor == 'Distributor'){
            System.debug('inside distributer'+Dist_RTNames);
            Dist_RTNames.add('India SND');
            Dist_RTNames.add('Brand W');
            Dist_RTNames.add('H&H Modern Trade Distributor');
            Dist_RTNames.add('H&H Traditional Trade Distributor');
            System.debug('after added record type distributer'+Dist_RTNames);
        }
        if(SchemeApplicablefor == 'Retailer'){
            Ret_RTNames.add('H&H Modern Trade Retailer');
            Ret_RTNames.add('H&H Traditional Trade Retailer');
            Ret_RTNames.add('India SND Retailer');
            Ret_RTNames.add('Brand W Retailer');
            System.debug('after added record type Retailer'+Ret_RTNames);
        }
        if(SchemeApplicablefor == 'Both'){
            Both_RTNames.add('India SND');
            Both_RTNames.add('Brand W');
            Both_RTNames.add('H&H Modern Trade Distributor');
            Both_RTNames.add('H&H Traditional Trade Distributor');
            Both_RTNames.add('H&H Modern Trade Retailer');
            Both_RTNames.add('H&H Traditional Trade Retailer');
            Both_RTNames.add('India SND Retailer');
            Both_RTNames.add('Brand W Retailer');
            System.debug('after added record type both'+Both_RTNames);
        }
        
        System.debug('RTNames@@'+Both_RTNames);
        if(SchemeApplicablefor == 'Retailer'){
            soqlQuery ='SELECT Id, Name, RecordType.Name FROM Account where Recordtype.Name in : Ret_RTNames';
        }
        
        else if(SchemeApplicablefor == 'Distributor'){
            soqlQuery ='SELECT Id, Name, RecordType.Name FROM Account where Recordtype.Name in : Dist_RTNames';
        }
        
        
        else if(SchemeApplicablefor == 'Both'){
            soqlQuery ='SELECT Id, Name, RecordType.Name FROM Account where Recordtype.Name in : Both_RTNames';
        }
        
        
        if(samid == null){
            soqlQuery = '';
        }
        System.debug('soqlQuery@@@@-------->'+soqlQuery);
        return Database.getQueryLocator(soqlQuery);
    }
    
    global void execute(Database.BatchableContext BC, List<Account> scope){
        System.debug('Scope size ----->'+ scope.size());
        
        Set<id> accIdswithCurrentSM = new Set<id>();
        List<Scheme_Assign_Master__c> AssignToAll = new List<Scheme_Assign_Master__c>();
        
        
        Map<Id,Account> mapAccount = New Map<Id,Account>(scope);
        List<Scheme_Assign_Master__c> SchemeList;
        
        SchemeList=[select Id,Account__c,Retailer_Account__c,Scheme_Master__c from Scheme_Assign_Master__c where Scheme_Master__c =: samid and (Retailer_Account__c in : mapAccount.keySet() OR Account__c in : mapAccount.keySet())];
        System.debug('SchemeList@@'+SchemeList);
       
        for(Scheme_Assign_Master__c samObj :SchemeList){
            if(samObj.Account__c != null){
                accIdswithCurrentSM.add(samObj.Account__c);
            }
            if(samObj.Retailer_Account__c != null){
                accIdswithCurrentSM.add(samObj.Retailer_Account__c);
            }
        }
        System.debug('Scheme Master with id '+samid +' is Already assigned with accounts, count ->'+accIdswithCurrentSM.size());
        for(Account ac : mapAccount.values()){
            if(!accIdswithCurrentSM.contains(ac.Id)){                
               
                //check ac record type for the retailer account and update value in the retailer id accordingly.
               
                if(SchemeApplicablefor == 'Distributor'){
                    Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
                    objSAM.Account__c = ac.Id;
                    objSAM.Scheme_Master__c = samid;
                    AssignToAll.add(objSAM);
                }
                
                else if(SchemeApplicablefor == 'Retailer'){
                    Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
                    objSAM.Retailer_Account__c = ac.Id;
                    objSAM.Scheme_Master__c = samid;
                    AssignToAll.add(objSAM);
                }
                
                else if(SchemeApplicablefor == 'Both'){
                    Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
                    objSAM.Account__c = ac.Id;
                    objSAM.Scheme_Master__c = samid;
                    AssignToAll.add(objSAM);
                    Scheme_Assign_Master__c objSAM1 = new Scheme_Assign_Master__c();
                    objSAM1.Retailer_Account__c = ac.Id;
                    objSAM1.Scheme_Master__c = samid;
                    AssignToAll.add(objSAM1);
                }
            }
        }
        
        /* List<Account> retacc=[SELECT Id, Name, RecordType.Name FROM Account where Customer_RetailerAC__c in : mapAccount.keySet()];
        for(Account ac :retacc ){
        if(!accIdswithCurrentSM.contains(ac.Id)){
        Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
        objSAM.Account__c = ac.Id;
        objSAM.Scheme_Master__c = samid;
        AssignToAll.add(objSAM);
        }
        }
            */
        
        System.debug('Total SAM to be inserted ---->'+AssignToAll.size());
        if(AssignToAll.size() > 0){
            Database.insert(AssignToAll, false);
        }
    }
    
    global void finish(Database.BatchableContext BC)
    {
        AsyncApexJob a = [Select Id, Status,ExtendedStatus,NumberOfErrors, JobItemsProcessed,TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:BC.getJobId()];
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {a.CreatedBy.Email};
            mail.setToAddresses(toAddresses);
        mail.setSubject('Scheme Assign to All Distributor/Retailer' + a.Status);
        mail.setPlainTextBody('Scheme Assign to All Distributor/Retailer successfully :- ' + a.TotalJobItems +   'with '+ a.NumberOfErrors + ' failures.');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); 
    }
}
Good day Developers!  I need your help here.  I am new to Visualforce.
I trying to create an Account summary that looks more professional than the Printable View.  I was able to find out how to add fields, image and also make my page render in PDF.  but were i am struggling is with those two things

- I have fields that I want to show as a table or in colums.
ex:   Broker Name :   Joe Fresh Inc                Broker Code: AP12234
but I can't seem to make it work.

- I am trying to add a Bar Graph with fields included is the account profile.

Any help would be more than appreciated. 
Thank you all in advance
Eric

Hi -
I have a Field Filter Validation on Lookup Field CutonFieldA__c on Account Object . The Account is related to Custon Object B . When I make any updates to my related record (from Custom B) , Some of the fields on Account gets updated .

But suppose I have a value already populated on CutonFieldA__c  field on Account , which is now not satisfying the filter condition . If I try to update my related record (from Custom B) , I am able to Save the record succeffuly , but the values on the Account are not getting updated because of the FIELD_FILTER_VALIDATION_EXCEPTION Error .

This way user is not getting to know that the changes didn't flow to Parent recod . 
Can you please suggest me on this?

Regards,
SN SF

  • April 01, 2021
  • Like
  • 0
What is the best way to prevent duplicate records from being created in an object in Salesforce
<button class="btn-view-all" onclick="openall()">View All   </button>

JS function
function openannouncement(){
            var urlString=window.location.href;
            var baseURL = urlString.substring(0, urlString.indexOf("/_ui"));
            var siteBaseURL = baseURL + '/s';
            var redirectUrl = siteBaseURL + '/viewall'
            window.open(redirectUrl,"_self");
         }

after clickig on view all button
browser URL is changing as expected but page is not redirecting 

The following works in desktop, but not mobile:

System.debug(ApexPages.currentPage().getHeaders().get('referer'));

'referer' is not available on when using a mobile device...

I know I'm on a mobile device if the following is true:

Boolean isMobile = UserInfo.getUiTheme() == 'Theme4t';

How do I get the URL parameters in my Apex Class when the VF Page loads in Community Page... ?

Thank you!

  • March 27, 2021
  • Like
  • 0
Hello team,

after delete the record table in not refresh please help me regarding this.

below is my vf code
===================

     <div class="slds-col" style="margin-top:10px;">
                    <p style="font-weight:600; padding:10px;">Distributor / Retailer List</p>
                </div>
            </div>
           
            <div style="border:1px solid #ccc; margin-top:0px;" class="slds-scrollable_x"  >
                 <apex:outputPanel id="TablePanel">
                    <table class="slds-table slds-table_cell-buffer slds-table_bordered slds-table_col-bordered slds-table_striped">
                        <thead>
                            <tr class="slds-line-height_reset">
                                <th class="" scope="col">
                                    <div class="slds-truncate" title="">Account Name</div>
                                </th>
                                <th class="" scope="col">
                                    <div class="slds-truncate" title="">SF Customer Code</div>
                                </th>
                                <th class="" scope="col">
                                    <div class="slds-truncate" title="">SAP Customer Code</div>
                                </th>
                                <th class="" scope="col">
                                    <div class="slds-truncate" title="">Action</div>
                                </th>
                                
                            </tr>
                        </thead>
                        <tbody>
                           
                            <apex:repeat value="{!membs}" var="awl" >
                            <tr class="slds-hint-parent">
                                <th scope="row">
                                    <div class="slds-form-element__control">{!awl.Account__r.Name}</div>
                                </th>
                                <td data-label="" class="fromvalue">
                                    <div class="slds-form-element__control">{!awl.Account__r.SF_Customer_Code__c}</div>
                                </td>
                                <td data-label="" class="fromvalue">
                                    <div class="slds-form-element__control">{!awl.Account__r.SAP_Customer_Code__c}</div>
                                </td>
                               
                                <td data-label="">
                                     <apex:commandLink styleClass="slds-button slds-button_destructive"  value="Delete" action="{!showassigndel}" reRender="TablePanel" onclick="if(!confirm('Are you sure?')) return false;"  >
                                       <apex:param name="schemeId" value="{!awl.id}" assignTo="{!showdelId}"/>
                                    </apex:commandLink>
                                </td>
                            </tr>
                            </apex:repeat>
                                
                        </tbody>
                        
                        <tbody>
                            <apex:repeat value="{!searchList }" var="swl" >
                                <tr class="slds-hint-parent">
                                    <th scope="row">
                                        <div class="slds-form-element__control">{!swl.Account__r.Name}</div>
                                    </th>
                                    <td data-label="" class="fromvalue">
                                        <div class="slds-form-element__control">{!swl.Account__r.SF_Customer_Code__c}</div>
                                    </td>
                                    <td data-label="" class="fromvalue">
                                        <div class="slds-form-element__control">{!swl.Account__r.SAP_Customer_Code__c}</div>
                                    </td>
                                    
                                    <td data-label="">
                                        <apex:commandLink styleClass="slds-button slds-button_destructive"  value="Delete" action="{!Remove}" reRender="TablePanel">
                                            <apex:param name="schemeIdParam" value="{!swl.id}" assignTo="{!delId}"/>
                                        </apex:commandLink>
                                        
                                    </td>
                                </tr>
                            </apex:repeat>
                        </tbody>
                    </table>
                </apex:outputPanel>
            </div>
Hi - can someone suggest how to create new section using LWC under details secion ?
public with sharing class AccountinfoCtrl{
    @AuraEnabled
    public static List<Account> getAccounts() {
        List <Account> accList = [SELECT id,Name, AccountNumber,Phone,Fax, Industry From Account LIMIT 2];
        return accList;
    }
}
I would like to create lwc wherein I want to make some non- required fields as required whenever user does not enter a value. May be display with message or flag a lable.
Hello Team,

I want to delete the row in table.please help me regarding this.
User-added image

// Remove logic not working
// Code For Remove Account using Delete Icon.
    public PageReference Remove(){
     rowIndex = Integer.valueOf(ApexPages.currentPage().getParameters().get('rowIndex'));
        System.debug('rowIndex'+rowIndex);
        membs.remove(rowIndex);
        return null;
    }

//getting the record properly

public List<Scheme_Assign_Master__c> getAccounts() {  
      totalRecs = [select count() from Scheme_Assign_Master__c];
      String scheme2=sam.Scheme_Master__c;
       membs=new list<Scheme_Assign_Master__c>();
       membs =[SELECT Id,Account__c,Account__r.Name,Account__r.SF_Customer_Code__c,Account__r.SAP_Customer_Code__c, Scheme_Master__c from Scheme_Assign_Master__c where Scheme_Master__c =:scheme2 limit :LimitSize offset :OffsetSize]; 
        System.debug('Values are ' + membs);  
        return null;  
  
    }      
    ////////////////******   pagination logic *****************///////
    public void FirstPage()
    {
        OffsetSize = 0;
        getAccounts();
        
    }
    public void previous()
    {
        OffsetSize = (OffsetSize-LimitSize);
        getAccounts();
        
    }
    public void next()
    {
        OffsetSize =( OffsetSize + LimitSize);
        getAccounts();
        
    }
    public void LastPage()
    {
        OffsetSize = totalrecs - math.mod(totalRecs,LimitSize);
        System.debug('OffsetSize--'+OffsetSize);
        getAccounts();
        
    }
    public boolean getprev()
    {
        System.debug('prev'+OffsetSize);
        if(OffsetSize == 0){
            return true;
        }
        else {
            return false;
        }
    }
    public boolean getnxt()
    {
        if((OffsetSize + LimitSize) > totalRecs){
            return true;
        }
        else {
            return false;
        }
    }