• Renuka Sharma
  • NEWBIE
  • 20 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 1
    Likes Given
  • 10
    Questions
  • 16
    Replies
Hello

I am new to the apex development, can anyone please help in writing test classes for the below trigger, i have no idea how to write a test classes for Triggers and Apex classes
 
trigger UserTrigger on User (after update) {
    
    Map<String,Id> newManagerQuotaMap = new Map<String,Id>();
    Map<String,Id> oldManagerQuotaMap = new Map<String,Id>();    
    Map<String,Quota__c> newReporteeQuotaMap = new Map<String,Quota__c>();
    Map<Id,Id> managerReporteemap = new Map<Id,Id>();
    Map<Id,Id> oldManagerReporteemap = new Map<Id,Id>();
    List<Quota__c> newMapQuota = new List<Quota__c>();
	List<Quota__c> oldMapQuota = new List<Quota__c>();
    
    for(User u : Trigger.new){
        if(u.managerid != Trigger.oldMap.get(u.Id).ManagerId){
            if(u.managerid != NULL)
                managerReporteemap.put(u.Id,u.managerId);
            
             if(Trigger.oldMap.get(u.Id).ManagerId != NULL)
              	oldManagerReporteemap.put(u.Id,Trigger.oldMap.get(u.Id).ManagerId);
        }
    }
    
    if(NULL != managerReporteemap && managerReporteemap.size() > 0 ){
        for(Quota__c qcm: [SELECT Id,Quater__c,Quater_Year__c, Assigned_To__c ,Manager_Quota__c FROM Quota__c WHERE Assigned_To__c IN : managerReporteemap.values()]){
            newManagerQuotaMap.put(qcm.Assigned_To__c + qcm.Quater__c + qcm.Quater_Year__c,qcm.Id);
        }
        
        for(Quota__c qcr : [SELECT Id,Quater__c,Quater_Year__c, Assigned_To__c ,Assigned_To__r.ManagerId, Manager_Quota__c FROM Quota__c WHERE Assigned_To__c IN : managerReporteemap.keyset()]){
            newReporteeQuotaMap.put(qcr.Assigned_To__r.ManagerId+ qcr.Quater__c + qcr.Quater_Year__c,qcr);
        }
        
        List<Quota__c> quotasOfReporteeupdate = new List<Quota__c>();
        if(newReporteeQuotaMap != NULL && newReporteeQuotaMap.size() > 0 ){
            for(String key : newReporteeQuotaMap.keySet()){
                if(newManagerQuotaMap.containsKey(key)){
                    newReporteeQuotaMap.get(key).Manager_Quota__c = newManagerQuotaMap.get(key);
                    
                }else{
                    newReporteeQuotaMap.get(key).Manager_Quota__c = NULL;
                }
                quotasOfReporteeupdate.add(newReporteeQuotaMap.get(key));
            }      
            if(NULL != quotasOfReporteeupdate && quotasOfReporteeupdate.size() > 0)
            	update quotasOfReporteeupdate;            
        }
                
        for (aggregateResult result: [Select Manager_Quota__c, Sum(Inside_Sales_Roll_Up__c) 
                                      FROM Quota__c WHERE 
                                      Manager_Quota__c IN: newManagerQuotaMap.values() 
                                      GROUP BY Manager_Quota__c]) {
                                              
			newMapQuota.add(new Quota__c(Id=(Id)result.get('Manager_Quota__c'),Actual_Amount__c =(Decimal)result.get('expr0')));         
        }
        
        	
        if(NULL != newMapQuota && newMapQuota.size() > 0){
        update newMapQuota;
    }
    
    	}
    
    if(NULL != oldManagerReporteemap && oldManagerReporteemap.size() > 0){
        for(Quota__c qcm: [SELECT Id,Quater__c,Quater_Year__c, Assigned_To__c ,Manager_Quota__c FROM Quota__c WHERE Assigned_To__c IN : oldManagerReporteemap.values()]){
            oldManagerQuotaMap.put(qcm.Assigned_To__c + qcm.Quater__c + qcm.Quater_Year__c,qcm.Id);
        }
        system.debug('oldManagerQuotaMap::' + oldManagerQuotaMap);
        if(NULL != oldManagerQuotaMap && oldManagerQuotaMap.size() > 0){
            futureHandler.updaterecs(oldManagerQuotaMap);
        }
     
    }      
    }



 
Hi Folks

i am working on  the test class for Emailalertbatclass, but i am not able to cover the excute method, it is only showing 27%, could anyone please help in the covering 100%

Emailalertbatchclass
 
global class Emailalertbatchclass implements Database.Batchable<sObject>, Schedulable, Database.Stateful {
    
    //Variable Section
    global FINAL String strQuery;
    global FINAL String leadid;
    global List<String> errorMessages = new List<String>();
    
    global Emailalertbatchclass() { 
        this.strQuery = getBatchQuery();
    }
    
    //Returns the Query String to Batch constructor to fetch right records.
    private String getBatchQuery() {
        String strQuery = 'SELECT Id,Name,Status,Email,owner.email,owner.name,ownerid,No_Enquiry_Email_Sent__c,Manager_Email__c,recordtype.name FROM Lead where No_Enquiry_Email_Sent__c=false AND recordtype.name=\'Lead Registration\' AND Lead_Intent_Type__c=\'High Intent Lead\' AND Status=\'Enquiry\' And ((DaysSinceLastActivityDone__c>=0) OR (DayssinceEnquirystage__c >= 0))';
        return strQuery;
    }
    
    //Batch Start method
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(strQuery);
    }
    
    //Batch Execute method calls findCostForWoD method
    global void execute(Database.BatchableContext BC, List<sObject> scopeList) {
        System.debug(LoggingLevel.INFO, '== scopeList size ==' + scopeList.size());
        
        List<Lead> ld = (List<Lead>) scopeList;
        List<Lead> updatedld = new List<Lead>();
        if(!ld.isEmpty()) { 
            List<Messaging.SingleEmailMessage> mailList = new List<Messaging.SingleEmailMessage>();
            for (Lead prod : ld)
            {               
                // Step 1: Create a new Email
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                System.debug( 'prod.owner.Email ' + prod.owner.Email);
                String[] toAddresses = new String[] {prod.owner.Email};
                    // Step 2: Set list of people who should get the email
                    if(prod.Manager_Email__c!=null && prod.Manager_Email__c==''){
                        toAddresses.add(prod.Manager_Email__c);
                    }
                mail.setToAddresses(toAddresses);
                System.debug( 'toAddresses ' + toAddresses);
                
                // Step 3: Set who the email is sent from
                mail.setReplyTo(prod.owner.Email);
                mail.setSenderDisplayName('No Activity on Leads for 24hrs');
                
                // (Optional) Set list of people who should be CC'ed
                List<String> ccTo = new List<String>();
                mail.setCcAddresses(ccTo);
                
                // Step 4. Set email contents - you can use variables!
                mail.setSubject('No Activity on Lead for 24hrs');
                String body = 'Dear ' + prod.owner.name + ', <br><br>';
                body += 'This is to notify you that there is no activity done on the respective <b> Lead Name: ';
                body +=prod.Name+'</b>  please find the link below..<br><br>';
                body += 'link to file: '+URL.getSalesforceBaseUrl().toExternalForm()+'/'+prod.id+'<br><br><br> Thanks,<br>Moengage Team</body></html>';
                mail.setHtmlBody(body);
                System.debug( 'body ' + body);
                
                // Step 5. Add your email to the master list
                mailList.add(mail);
                prod.No_Enquiry_Email_Sent__c = true;
                updatedld.add(prod);
                System.debug( 'prod ' + prod);
                
            }
            if(!mailList.isEmpty()) {
                try{
                    Messaging.sendEmail(mailList);
                    update updatedld;
                    system.debug('mailList '+mailList);
                }
                catch (Exception ex) {
                    errorMessages.add('Unable to send email to Tech: '+ ex.getStackTraceString());
                }
            }
        }
    }  
    
    //Batch Finish method for after execution of batch work
    global void finish(Database.BatchableContext BC) { 
        
    }
    
    //Method which schedules the ProductDownloadBatch
    global void execute(SchedulableContext sc) {        
        Emailalertbatchclass snInstance = new Emailalertbatchclass();
        ID batchprocessid = Database.executeBatch(snInstance);
    }
}

test Class
 
@isTest
public class EmailalertbatchclassTestclass
{
    static testMethod void testmethod1()
    {
        List<Lead> Leadld = new List<Lead>();
        lead ld = new lead();
        ld.FirstName= 'test';
        ld.LastName='Test2';
        ld.status='Enquiry';
        ld.Company = 'fgfh';
        ld.Email = 'manjunath.s@proseraa.com';
        ld.Manager_Email__c = 'chandra.s@proseraa.com';
        ld.No_Enquiry_Email_Sent__c = true;
        Insert ld;
        Leadld.add(ld); 
        
        Datetime Yesterday = Datetime.now().addDays(-1);
        Test.setCreatedDate(ld.Id, Yesterday);
        
        Test.startTest();
        ld.FirstName = 'test1';
        update ld;
        
        Emailalertbatchclass snInstance = new Emailalertbatchclass();
        ID batchprocessid = Database.executeBatch(snInstance);
        
        Test.stopTest();
    }
    public static testMethod void testschedule() {
        Test.startTest();
        Emailalertbatchclass sh1 = new Emailalertbatchclass();
        String sch = '0 00 01 * * ?'; 
        ID batchprocessid = Database.executeBatch(sh1);
        String jobId = system.schedule('Emailalertbatchclass', sch, sh1);
        System.assert(jobId != null);
        Test.stopTest(); 
    }
}

​​​​​​​
Hello all

i am very new to the apex development, i am written a trigger where it gives extra sharing rule to the user when the CRM user__c field is populated, i have written a test class where it gives 91% coverage, according to the my manager this is not a best pratices because there are not trigger context variables, can anyone please point out what needs to be updated
 
trigger OppShareWithCRMOwner on Opportunity (after insert,after update){
    List<OpportunityShare> csShareList = new List<OpportunityShare>();
    List<OpportunityShare> removeShareList = new List<OpportunityShare>();
    Set<Id> OPPids = new Set<Id>();
    for( Opportunity cs : trigger.new ) {
        if( cs.CRM_User__c != NULL ) {
            // Create a new LeadShare object for each Lead where CRM_User__c field is not NULL.
            OpportunityShare csShare = new OpportunityShare();
            // Give Read write access to that user for this particular Lead record.
            csShare.OpportunityAccessLevel = 'Read';
            // Assign Lead Id of Lead record.
            csShare.OpportunityId = cs.id;
            // Assign user id to grant read write access to this particular Lead record.
            csShare.UserOrGroupId = cs.CRM_User__c;
            csShareList.add( csShare );
        }
        if( cs.CRM_User__c == NULL ) {
            OPPids.add( cs.id);
        }
    }
    
    if(OPPids.size()>0){
        removeShareList = [Select id,OpportunityId,UserOrGroupId from OpportunityShare where OpportunityId=:OPPids AND RowCause = 'Manual'];
        if(removeShareList.size()>0){
            delete removeShareList;
        }
    }
    if( csShareList != null && csShareList.size() != 0 ) {
        try {
            insert csShareList;
            update csShareList;
            
            System.debug('size of my list is: ' +csShareList.size());
 
        }catch( Exception e ) {
            trigger.new[0].CRM_User__c.addError('Error::::::'+e.getMessage());
        }
    }
}

Test class
 
@isTest
private class OppShareWithCRMOwnerTestClass {

    // test that newly inserted records marked as pubic=true have corresponding shares created
    static testMethod void testAddShares() {

    Set<ID> ids = new Set<ID>();
    Account testAcct = new Account (Name = 'My Test Account');
     insert testAcct;
    List<Opportunity> Opps = new List<Opportunity>();
        User u = [Select id,name from user where isactive=true Limit 1];
    for (Integer i=0;i<10;i++)
      Opps.add(new Opportunity(Name='First',AccountId = testAcct.ID,
      StageName = 'Demo',CloseDate = System.today(),LeadSource = 'Customer',Country__c = 'India',CRM_User__c=u.Id));

    insert Opps;

    // get a set of all new created ids
    for (Opportunity c : Opps)
      ids.add(c.id);

    // assert that 50 shares were created
    List<OpportunityShare> shares = [select id from OpportunityShare where 
      OpportunityId IN :ids and RowCause = 'Manual'];
    System.assertEquals(shares.size(),10);

    }

    // insert records and switch them from public = true to public = false
    static testMethod void testUpdateContacts() {

        Set<ID> ids = new Set<ID>();
        
        Account testAcct = new Account (Name = 'My Test Account');
        insert testAcct;
        List<Opportunity> Opps = new List<Opportunity>();
        User u = [Select id,name from user where isactive=true Limit 1];
        
        for (Integer i=0;i<10;i++)
            Opps.add(new Opportunity(Name='First',AccountId = testAcct.ID,
                                     StageName = 'Demo',CloseDate = System.today(),LeadSource = 'Customer',Country__c = 'India',CRM_User__c=u.Id));

    insert Opps;

    for (Opportunity c : Opps)
      ids.add(c.id);

    update Opps;

    // assert that 0 shares exist
    List<OpportunityShare> shares = [select id from OpportunityShare where 
      OpportunityId IN :ids and RowCause = 'Manual'];
    System.assertNotEquals(shares.size(),0);

    for (Opportunity c : Opps)
      c.CRM_User__c=u.Id;

    update Opps;

    // assert that 50 shares were created
    shares = [select id from OpportunityShare where OpportunityId IN :ids and RowCause = 'Manual'];
    System.assertEquals(shares.size(),10);

    for (Opportunity c : Opps)
      c.CRM_User__c=u.Id;

    update Opps;

    // assert that 0 shares exist
    shares = [select id from OpportunityShare where OpportunityId IN :ids and RowCause = 'Manual'];
    System.assertNotEquals(shares.size(),0);

    }
}

 
How do i cover my apex code for 100%
My test class with 50% code coverage

@isTest(SeeAllData=true)
Private class TestProductSearchpopupController {
    static testMethod void method()        {
        Account acc = new Account ();
        acc.Name = 'Test1';
        insert acc;
        
        Opportunities__c opp= new Opportunities__c ();
        opp.Name= 'Testopp1';
        opp.Account_Name__c = acc.id;
        opp.Close_Date__c = date.today();
        opp.Stage__c = 'Prospecting';
        insert opp;
        
        Quotes__c testque = new Quotes__c();
        testque.Name = 'Test PriceBookEntry';
        testque.OpportunityId__c = opp.id;
        testque.AccountId__c = acc.id;
        insert testque;
        
        List <Product2__c> lstproduct = new List<Product2__c>();
        Product2__c testProduct = new Product2__c();
        testProduct.Name='Test product';
        lstproduct.add(testProduct);
        insert lstproduct;
        
        List <PricebookEntry__c> lstpbe = new List<PricebookEntry__c>();
        PricebookEntry__c testpbe = new PricebookEntry__c();
        testpbe.Name='Test PriceBookEntry';
        lstpbe.add(testpbe);
        insert lstpbe;
        
        List <QuoteLineitem__c> lstqli = new List<QuoteLineitem__c>();
        QuoteLineitem__c testqli = new QuoteLineitem__c();
        testqli.QuotesId__c = testque.id;
        testqli.Quantity__c = 12;    
        lstqli.add(testqli);
        
        PageReference pageRef = Page.ProductSearchPopupController;
        pageRef.getparameters().put('recordId',testque.id);
        Test.setCurrentPage(pageRef);
        
        ApexPages.StandardController sc = new ApexPages.StandardController(testque);
        ProductSearchPopupController psp = new ProductSearchPopupController(sc);
        psp.runQuery();
        psp.ProceedWithSelectedToNextPage();
        psp.processSelected();
        psp.GoBack();
        psp.saveproduct();     
    }
}


My class  - my Apex class code where red lines are not getting covered

public class ProductSearchPopupController {
   
    public String query {get; set;}
    public List<PricebookEntry__c> products {get; set;}
    public List<wrapProduct> wrapProductList {get; set;}
    public List<PricebookEntry__c> selectedProduct{get;set;}
    public List<QuoteLineitem__c> quoteLineList{get;set;}
    public List<wrapProduct> selectedWrapperList{get;set;}
    public Boolean normalList{get;set;}
    public Boolean selectedList{get;set;}
    public Boolean block{get;set;}
    public Boolean block1{get;set;}
    public Boolean block2{get;set;}
    public String SalesPrice {get; set;}
    public integer Discount {get; set;}
    public String Quantity {get; set;}
    public String ServiceDate {get; set;}
    Id recordId;
   
   
    public ProductSearchPopupController(ApexPages.StandardController controller){
        recordId = controller.getId();
        system.debug('recordId '+recordId);
        wrapProductList = new List<wrapProduct>();
        selectedWrapperList = new List<wrapProduct>();
        normalList = true;
        selectedList = false;
        block = true;
        block1 = false;
        block2 = false;
    }
    public PageReference runQuery(){
        if(query == null || query == ''){
            system.debug('query '+query);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info,'Please enter the product to be searched'));
            return null;
        }
       
        List<List<PricebookEntry__c>> searchResults=[FIND :query IN ALL FIELDS RETURNING PricebookEntry__c (id, Name, ProductCode__c, Product2Id__r.Product_Description__c,UnitPrice__c, UseStandardPrice__c)];
        system.debug('searchResults '+searchResults.size()+searchResults[0].size()+searchResults.isempty());
       
        if(searchResults[0]!=null){
            for(PricebookEntry__c a: searchResults[0]) {
                // As each Account is processed we create a new wrapAccount object and add it to the wrapAccountList
                wrapProductList.add(new wrapProduct(a));
                block = true;
                block1 = true;
                block2 = false;
            }
        }
        return null;
    }
    public PageReference ProceedWithSelectedToNextPage(){
        selectedWrapperList = new List<wrapProduct>();
        normalList = false;
        selectedList = true;
        for(wrapProduct selectedWrapObj: wrapProductList){
            system.debug('selectedWrapObj.selected  ---------'+selectedWrapObj.selected);
            if(selectedWrapObj.selected == true)
                selectedWrapperList.add(selectedWrapObj);
        }
        system.debug('selectedWrapperList size ---------'+selectedWrapperList.size());
        PageReference pageRef = new PageReference('/apex/AccountOpportunityTwoPage');
        pageRef.setRedirect(false);
        return pageRef;
    }
    public void processSelected() {
        selectedProduct = new List<PricebookEntry__c>();
        for(wrapProduct wrapProductObj : wrapProductList) {
            if(wrapProductObj.selected == true) {
                selectedProduct.add(wrapProductObj.acc);
                block = false;
                block1 = false;
                block2 = true;
               
            }
        }
    }
   
    public void GoBack() {
        block = true;
        block1 = true;
        block2 = false;
    }
   
    public class wrapProduct {
        public PricebookEntry__c acc {get;set;}
        public Boolean selected {get;set;}
        public wrapProduct(PricebookEntry__c p) {
            this.acc = p;
            this.selected = false;
        }
       
    }
    public pagereference saveproduct(){
        List<QuoteLineitem__c> quoteLineList = new  List<QuoteLineitem__c>();
        if(!selectedProduct.isEmpty()){
            for(PricebookEntry__c sp:selectedProduct){
                system.debug('sp '+sp);
                QuoteLineitem__c qli = new QuoteLineitem__c();
                qli.QuotesId__c = recordId;
                qli.ListPrice__c = sp.UnitPrice__c;
                qli.UnitPrice__c = sp.UnitPrice__c;
                qli.Product2Id__c = sp.Product2Id__c;   
                if(Discount!=0 || Discount!=null){
                    qli.Discount__c = Discount;
                }
                quoteLineList.add(qli);
            }
           
            if(quoteLineList.size()>0){
                insert quoteLineList;
                PageReference pageRef = new PageReference('https://proseraa.lightning.force.com/lightning/r/Quotes__c/'+recordId+'/view');
                pageRef.setRedirect(true);
                return pageRef;
            }
        }
        return null;
    }
}
 
how to use best pratice for test classes for below code
 
@isTest
Private class TestProductSearchpopupController {
    @isTest
    static void testMethod1() 
    {   
        Account acc = new Account (name='Pencil');
        insert acc;
        Opportunity opp= new Opportunity ();
        opp.name= 'Testopp1';
        Opp.Accountid= acc.id;
        opp.CloseDate= date.today();
        opp.StageName= 'Qualification';
        insert opp;
        
        List <Quotes__c> lstquote = new List<Quotes__c>();
        
        Quotes__c testque = new Quotes__c();
        testque.Name = 'Test PriceBookEntry';
        testque.OpportunityId__c = opp.id;
        testque.AccountId__c = acc.id;
        lstquote.add(testque);
        
        List <Product2__c> lstproduct = new List<Product2__c>();
        Product2__c testProduct = new Product2__c();
        testProduct.Name='Test product';
        lstproduct.add(testProduct);
        
        List <PricebookEntry__c> lstpbe = new List<PricebookEntry__c>();
        
        PricebookEntry__c testpbe = new PricebookEntry__c();
        testpbe.Name='Test PriceBookEntry';
        lstpbe.add(testpbe);
        
        List <QuoteLineitem__c> lstqli = new List<QuoteLineitem__c>();
        QuoteLineitem__c testqli = new QuoteLineitem__c();
        testqli.QuotesId__c = testque.id;
        
        lstqli.add(testqli);
      

        Test.startTest();
        ApexPages.StandardController sc = new ApexPages.StandardController(lstquote[0]);
        ProductSearchPopupController psp = new ProductSearchPopupController(sc);
        psp.ProceedWithSelectedToNextPage();
        psp.processSelected();
        psp.runQuery();
        psp.saveproduct();
        Test.stopTest();
    }  
}

my class
 
public class ProductSearchPopupController {
   
    public String query {get; set;}
    public List<PricebookEntry__c> products {get; set;}
    public List<wrapProduct> wrapProductList {get; set;}
    public List<PricebookEntry__c> selectedProduct{get;set;}
    public List<QuoteLineitem__c> quoteLineList{get;set;}
    public List<wrapProduct> selectedWrapperList{get;set;}
    public Boolean normalList{get;set;}
    public Boolean selectedList{get;set;}
    public Boolean block{get;set;}
    public Boolean block1{get;set;}
    public Boolean block2{get;set;}
    public String SalesPrice {get; set;}
    public integer Discount {get; set;}
    public String Quantity {get; set;}
    public String ServiceDate {get; set;}
    Id recordId;
    
    public ProductSearchPopupController(ApexPages.StandardController controller){
        recordId = controller.getId();
        system.debug('recordId '+recordId);
        wrapProductList = new List<wrapProduct>();
        selectedWrapperList = new List<wrapProduct>();
        normalList = true;
        selectedList = false;
        block = true;
        block1 = false;
        block2 = false;
    }
    
    public PageReference runQuery(){
        if(query == null || query == ''){
            system.debug('query '+query);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info,'Please enter Product to search for'));
            
            return null;
        }
        system.debug('query '+query);
        List<List<PricebookEntry__c>> searchResults=[FIND :query IN ALL FIELDS RETURNING PricebookEntry__c (id, Name, ProductCode__c, Product2Id__r.Product_Description__c,UnitPrice__c, UseStandardPrice__c)];
        if(searchResults[0]!=null){
            for(PricebookEntry__c a: searchResults[0]) {
                // As each Account is processed we create a new wrapAccount object and add it to the wrapAccountList
                wrapProductList.add(new wrapProduct(a));
                block = true;
                block1 = true;
                block2 = false;
            }
        }
        return null;
    }
    public PageReference ProceedWithSelectedToNextPage(){
        selectedWrapperList = new List<wrapProduct>();
        normalList = false;
        selectedList = true;
        for(wrapProduct selectedWrapObj: wrapProductList){
            system.debug('selectedWrapObj.selected  ---------'+selectedWrapObj.selected);
            if(selectedWrapObj.selected == true)
                selectedWrapperList.add(selectedWrapObj);
        }
        system.debug('selectedWrapperList size ---------'+selectedWrapperList.size());
        PageReference pageRef = new PageReference('/apex/AccountOpportunityTwoPage');
        pageRef.setRedirect(false);
        return pageRef;
    }
    public void processSelected() {
        selectedProduct = new List<PricebookEntry__c>();
        for(wrapProduct wrapProductObj : wrapProductList) {
            if(wrapProductObj.selected == true) {
                selectedProduct.add(wrapProductObj.acc);
                block = false;
                block1 = false;
                block2 = true;
                
            }
        }
    }
    
    public class wrapProduct{
        public PricebookEntry__c acc {get;set;}
        public Boolean selected {get;set;}
        public wrapProduct(PricebookEntry__c p) {
            this.acc = p;
            this.selected = false;
        }
        
    }
    
    public pagereference saveproduct(){ 
        List<QuoteLineitem__c> quoteLineList = new  List<QuoteLineitem__c>();
        if(!selectedProduct.isEmpty()){
            for(PricebookEntry__c sp:selectedProduct){
                system.debug('sp '+sp);
                QuoteLineitem__c qli = new QuoteLineitem__c();
                qli.QuotesId__c = recordId;
                qli.ListPrice__c = sp.UnitPrice__c;
                qli.UnitPrice__c = sp.UnitPrice__c;
                qli.Product2Id__c = sp.Product2Id__c;    
                if(Discount!=0 || Discount!=null){
                    qli.Discount__c = Discount;
                }
                quoteLineList.add(qli);
            }

            if(quoteLineList.size()>0){
                insert quoteLineList;
                PageReference pageRef = new PageReference('https://proseraa.lightning.force.com/lightning/r/Quotes__c/'+recordId+'/view');
                pageRef.setRedirect(true);
                return pageRef;
            }
        }
        return null;
    }
   
}

​​​​​​​
hey Guys

i need a small help regarding a test classes. Basically i am trying to design a test class for account and contact, in my case Account is Renamed as (Courses) and Contact is Renamed as (Students), and i have 2 custom objects Classes(Class__c) and Attendancess (Attendancess__c)

how do i design a test class for below apex class
public class UpdateUsingCheckboxC {
    
    @AuraEnabled
    public static List <Contact> fetchContact(string key) {
        system.debug('classname'+key);
        Class__c cls = [select id,Courses__r.name from Class__c where id=:key];
        string classname = cls.Courses__r.name;
        system.debug('classname'+classname);
        return [SELECT Id, Name,Account.Name,FirstName,LastName,Check_for_Attendance__c,Check_for_Absentee__c FROM Contact where (Check_for_Attendance__c=false AND Check_for_Absentee__c=false) AND Account.Name =:classname];
    }
    
    @AuraEnabled
    public static void updateRecord(List <String> lstRecordId,string key) {
        List<Contact> lstUpdate = new List<Contact>();
        List<Attendancess__c> listAttendnce = new List<Attendancess__c>();
        Class__c cls = [select id,Courses__r.name from Class__c where id=:key];
        if(cls.Id !=null){
            for(Contact con : [SELECT Id,AccountId, Name,Phone,FirstName,LastName,Check_for_Attendance__c,Check_for_Absentee__c  FROM Contact WHERE Id IN : lstRecordId]){
                con.Check_for_Attendance__c = true;
                con.Check_for_Absentee__c = false;
                lstUpdate.add(con);
                
                Attendancess__c attandenc = new Attendancess__c();
                attandenc.Class__c = cls.Id;
                attandenc.Student_Attended__c = true;
                attandenc.Name = con.Name;
                attandenc.Created_Date_Time__c = system.now();
                listAttendnce.add(attandenc);
                system.debug('listAttendnce'+listAttendnce);
            }
            
            if(lstUpdate.size() > 0){
                update lstUpdate;
            }
            if(listAttendnce.size() > 0){
                insert listAttendnce;
            }
        }
    }
    
    @AuraEnabled
    public static void updateSecondRecord(List <String> secondRecordId,string key) {
        system.debug('key1'+key);
        system.debug('secondRecordId '+secondRecordId);
        List<Contact> lstUpdate = new List<Contact>();
        List<Attendancess__c> listAttendnce = new List<Attendancess__c>();
        if(key !=null){
        Class__c cls = [select id,Courses__r.name from Class__c where id=:key];
            for(Contact con : [SELECT Id,AccountId, Name,Phone,FirstName,LastName,Check_for_Attendance__c,Check_for_Absentee__c  FROM Contact WHERE Id IN : secondRecordId]){
                con.Check_for_Absentee__c = true;
                con.Check_for_Attendance__c = false;
                lstUpdate.add(con);
                
                Attendancess__c attandenc = new Attendancess__c();
                attandenc.Class__c = cls.Id;
                attandenc.Student_Attended__c = false;
                attandenc.Name = con.Name;
                attandenc.Created_Date_Time__c = system.now();
                listAttendnce.add(attandenc);
                system.debug('listAttendnce'+listAttendnce);
            }
            
            if(lstUpdate.size() > 0){
                update lstUpdate;
            }
            if(listAttendnce.size() > 0){
                insert listAttendnce;
            }
        }
    }
    
}

 
Hello all

i am trying to design a lightning component where i need 2 seperate checkbox column, how do i do that

i tried to hardcode from online, but still its not functioning properly
 
<aura:component controller="UpdateUsingCheckboxC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <aura:attribute name="ContactList" type="List" />
    
    <aura:handler name="init" value="{!this}" action="{!c.loadContacts}"/>
    <aura:handler event="force:refreshView" action="{!c.loadContacts}" />
    
    <div class="slds-grid slds-grid--align-end"> 
        <button class="slds-button slds-button--brand" onclick="{!c.updateFields}">Update Attendance</button>
    </div>
    
    <table class="slds-table slds-table--bordered slds-table--cell-buffer">
        <thead>
            <tr class="slds-text-title--caps">
                <th></th>
                <th></th>
                <th>
                    <span class="slds-truncate">Attendee</span>      
                </th>
                <th style="width:3.25rem;" class="slds-text-align--right">
                    <div class="slds-form-element">
                        <div class="slds-form-element__control">
                            <label class="slds-checkbox">
                                <!--header checkbox for select all-->
                                <ui:inputCheckbox aura:id="box3" change="{!c.selectAll}"/>
                                <span >Attended</span>
                                <span class="slds-form-element__label text"></span>
                            </label>
                        </div>
                    </div>
                </th>
                <th style="width:3.25rem;" class="slds-text-align--right">
                    <div class="slds-form-element">
                        <div class="slds-form-element__control">
                            <label class="slds-checkbox">
                                <!--header checkbox for select all-->
                                <ui:inputCheckbox aura:id="box4" change="{!c.selectAll}"/>
                                <span >Absentee</span>
                                <span class="slds-form-element__label text"></span>
                                
                            </label>
                        </div>
                       </div>
                        </th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
            </tr>
        </thead>
        <td>
            
        </td>
        <tbody>
            <aura:iteration items="{!v.ContactList}" var="con">
                <tr>
                    <td></td>
                    <td></td>
                    <td scope="row">
                        <div class="slds-truncate" title="{!con.Name}"><a>{!con.Name}</a></div>
                    </td>
                    <td scope="row" class="slds-text-align--right" style="width:3.25rem;">
                        <div class="slds-form-element">
                            <div class="slds-form-element__control">
                                <label class="slds-checkbox">
                                    <ui:inputCheckbox text="{!con.Id}" aura:id="boxPack" value=""/>
                                    <span class="slds-checkbox--faux"></span>
                                    <span class="slds-form-element__label text"></span>
                                    </label>
                            </div>
                        </div>
                    </td>
                    <td>
                    <div class="slds-checkbox">
                	<input type="checkbox" name="options" id="checkbox-033" tabindex="0" aria-labelledby="check-button-label-033 column-group-header" value="checkbox-033" />
                    <label class="slds-checkbox__label" for="checkbox-033" id="check-button-label-033">
                    <span class="slds-checkbox_faux"></span>
                    <span class="slds-form-element__label slds-assistive-text">Select item 33</span>
                </label>
            </div>
                    </td>
                    <td></td>
                    <td></td>
                </tr>
            </aura:iteration>
        </tbody>
        <tbody>
            <aura:iteration items="{!v.ContactList}" var="con">
                <tr>
                    <td></td>
                    <td></td>
                    <td scope="row">
                        <div class="slds-truncate" title="{!con.Name}"><a>{!con.Name}</a></div>
                    </td>
                        <td scope="row" class="slds-text-align--right" style="width:3.25rem;">
                        <div class="slds-form-element">
                            <div class="slds-form-element__control">
                                <label class="slds-checkbox">
                                    <ui:inputCheckbox text="{!con.Id}" aura:id="boxPack" value=""/>
                                    <span class="slds-checkbox--faux"></span>
                                    <span class="slds-form-element__label text"></span>
                                </label>
                            </div>
                        </div>
                    </td>
                    <td></td>
                    <td></td>
                    <td></td>
                </tr>
            </aura:iteration>
        </tbody>   
    </table>
</aura:component>

User-added image


 
Hello Experts

i am new to the Lightning component, i need small help
i want to add seperate Checkbox list in a component, how do i do this
i have pasted a snaphot to get an idea

Snapshot1
Hello Guys

I need a small Help

I am working on a Education project, I have four custom objects, Student__c, Class__c, course__c,Attandence__c
The first part is working fine,  in a class related list(Snapshot 1)  when I click on Update Attendance, a check box is checked in a student object (Snapshot 2) and it Is checked in child object Attendance object and Related Record Gets created (Snapshot 3)
Now I want to put another button called as Update Absentee, when I click this button, Checkbox should get updated in the Student object named (Check for Absentee) and related record should get created and it should not get updated in attendance custom object,
User-added image

User-added image
User-added image
 
Hello all

In the contact object there is a custom checkbox field called "Course_completed__c" when i check the checkbox field, it should fire an email, i know this can be achived through workflow and process builder, but i want to try in apex so  i have designed a trigger and apex class, but i do get an error

the error i get is - Variable does not exist: checkbox and Method does not exist or incorrect signature: void checkfeesurvey(List<Contact>) from the type emailfeesurvey_handler

Apex class - 

public class emailfeesurvey_handler {
    public static void checkfeesurvey(List<contact> contactlist) {
        try {
            List<String> emailList = new List<String>();
            
            for(contact c : contactList) {
                if(c.Email != null && c.checkbox == 'True') {
                    emailList.add(c.Email);
                    EmailTemplate temp = [SELECT Id FROM EmailTemplate WHERE developername = 'Course_complete_survey' LIMIT 100];
                    system.debug('emailList------' + emailList);
                    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
                    if(emailList.size() > 0) {
                        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                        mail.setToAddresses(emailList);
                        mail.setTemplateId(temp.Id);
                        mail.setTargetObjectId(c.Id);
                        mails.add(mail);
                    }
                    Messaging.sendEmail(mails);
                }
            }
        } catch (Exception ex) {
            system.debug('Exception---ofLine--->' + ex.getLineNumber());
            system.debug('Exception---Message--->' + ex.getMessage());
        }
    }
}


Trigger - 

trigger emailfeesurvey on Contact (before insert, before update) {
    if((trigger.isInsert && trigger.isBefore) || (trigger.isUpdate && trigger.isBefore)) {
        emailfeesurvey_handler.checkfeesurvey(trigger.new);
    }
}


 
Hello

I am new to the apex development, can anyone please help in writing test classes for the below trigger, i have no idea how to write a test classes for Triggers and Apex classes
 
trigger UserTrigger on User (after update) {
    
    Map<String,Id> newManagerQuotaMap = new Map<String,Id>();
    Map<String,Id> oldManagerQuotaMap = new Map<String,Id>();    
    Map<String,Quota__c> newReporteeQuotaMap = new Map<String,Quota__c>();
    Map<Id,Id> managerReporteemap = new Map<Id,Id>();
    Map<Id,Id> oldManagerReporteemap = new Map<Id,Id>();
    List<Quota__c> newMapQuota = new List<Quota__c>();
	List<Quota__c> oldMapQuota = new List<Quota__c>();
    
    for(User u : Trigger.new){
        if(u.managerid != Trigger.oldMap.get(u.Id).ManagerId){
            if(u.managerid != NULL)
                managerReporteemap.put(u.Id,u.managerId);
            
             if(Trigger.oldMap.get(u.Id).ManagerId != NULL)
              	oldManagerReporteemap.put(u.Id,Trigger.oldMap.get(u.Id).ManagerId);
        }
    }
    
    if(NULL != managerReporteemap && managerReporteemap.size() > 0 ){
        for(Quota__c qcm: [SELECT Id,Quater__c,Quater_Year__c, Assigned_To__c ,Manager_Quota__c FROM Quota__c WHERE Assigned_To__c IN : managerReporteemap.values()]){
            newManagerQuotaMap.put(qcm.Assigned_To__c + qcm.Quater__c + qcm.Quater_Year__c,qcm.Id);
        }
        
        for(Quota__c qcr : [SELECT Id,Quater__c,Quater_Year__c, Assigned_To__c ,Assigned_To__r.ManagerId, Manager_Quota__c FROM Quota__c WHERE Assigned_To__c IN : managerReporteemap.keyset()]){
            newReporteeQuotaMap.put(qcr.Assigned_To__r.ManagerId+ qcr.Quater__c + qcr.Quater_Year__c,qcr);
        }
        
        List<Quota__c> quotasOfReporteeupdate = new List<Quota__c>();
        if(newReporteeQuotaMap != NULL && newReporteeQuotaMap.size() > 0 ){
            for(String key : newReporteeQuotaMap.keySet()){
                if(newManagerQuotaMap.containsKey(key)){
                    newReporteeQuotaMap.get(key).Manager_Quota__c = newManagerQuotaMap.get(key);
                    
                }else{
                    newReporteeQuotaMap.get(key).Manager_Quota__c = NULL;
                }
                quotasOfReporteeupdate.add(newReporteeQuotaMap.get(key));
            }      
            if(NULL != quotasOfReporteeupdate && quotasOfReporteeupdate.size() > 0)
            	update quotasOfReporteeupdate;            
        }
                
        for (aggregateResult result: [Select Manager_Quota__c, Sum(Inside_Sales_Roll_Up__c) 
                                      FROM Quota__c WHERE 
                                      Manager_Quota__c IN: newManagerQuotaMap.values() 
                                      GROUP BY Manager_Quota__c]) {
                                              
			newMapQuota.add(new Quota__c(Id=(Id)result.get('Manager_Quota__c'),Actual_Amount__c =(Decimal)result.get('expr0')));         
        }
        
        	
        if(NULL != newMapQuota && newMapQuota.size() > 0){
        update newMapQuota;
    }
    
    	}
    
    if(NULL != oldManagerReporteemap && oldManagerReporteemap.size() > 0){
        for(Quota__c qcm: [SELECT Id,Quater__c,Quater_Year__c, Assigned_To__c ,Manager_Quota__c FROM Quota__c WHERE Assigned_To__c IN : oldManagerReporteemap.values()]){
            oldManagerQuotaMap.put(qcm.Assigned_To__c + qcm.Quater__c + qcm.Quater_Year__c,qcm.Id);
        }
        system.debug('oldManagerQuotaMap::' + oldManagerQuotaMap);
        if(NULL != oldManagerQuotaMap && oldManagerQuotaMap.size() > 0){
            futureHandler.updaterecs(oldManagerQuotaMap);
        }
     
    }      
    }



 
Hi Folks

i am working on  the test class for Emailalertbatclass, but i am not able to cover the excute method, it is only showing 27%, could anyone please help in the covering 100%

Emailalertbatchclass
 
global class Emailalertbatchclass implements Database.Batchable<sObject>, Schedulable, Database.Stateful {
    
    //Variable Section
    global FINAL String strQuery;
    global FINAL String leadid;
    global List<String> errorMessages = new List<String>();
    
    global Emailalertbatchclass() { 
        this.strQuery = getBatchQuery();
    }
    
    //Returns the Query String to Batch constructor to fetch right records.
    private String getBatchQuery() {
        String strQuery = 'SELECT Id,Name,Status,Email,owner.email,owner.name,ownerid,No_Enquiry_Email_Sent__c,Manager_Email__c,recordtype.name FROM Lead where No_Enquiry_Email_Sent__c=false AND recordtype.name=\'Lead Registration\' AND Lead_Intent_Type__c=\'High Intent Lead\' AND Status=\'Enquiry\' And ((DaysSinceLastActivityDone__c>=0) OR (DayssinceEnquirystage__c >= 0))';
        return strQuery;
    }
    
    //Batch Start method
    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(strQuery);
    }
    
    //Batch Execute method calls findCostForWoD method
    global void execute(Database.BatchableContext BC, List<sObject> scopeList) {
        System.debug(LoggingLevel.INFO, '== scopeList size ==' + scopeList.size());
        
        List<Lead> ld = (List<Lead>) scopeList;
        List<Lead> updatedld = new List<Lead>();
        if(!ld.isEmpty()) { 
            List<Messaging.SingleEmailMessage> mailList = new List<Messaging.SingleEmailMessage>();
            for (Lead prod : ld)
            {               
                // Step 1: Create a new Email
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                System.debug( 'prod.owner.Email ' + prod.owner.Email);
                String[] toAddresses = new String[] {prod.owner.Email};
                    // Step 2: Set list of people who should get the email
                    if(prod.Manager_Email__c!=null && prod.Manager_Email__c==''){
                        toAddresses.add(prod.Manager_Email__c);
                    }
                mail.setToAddresses(toAddresses);
                System.debug( 'toAddresses ' + toAddresses);
                
                // Step 3: Set who the email is sent from
                mail.setReplyTo(prod.owner.Email);
                mail.setSenderDisplayName('No Activity on Leads for 24hrs');
                
                // (Optional) Set list of people who should be CC'ed
                List<String> ccTo = new List<String>();
                mail.setCcAddresses(ccTo);
                
                // Step 4. Set email contents - you can use variables!
                mail.setSubject('No Activity on Lead for 24hrs');
                String body = 'Dear ' + prod.owner.name + ', <br><br>';
                body += 'This is to notify you that there is no activity done on the respective <b> Lead Name: ';
                body +=prod.Name+'</b>  please find the link below..<br><br>';
                body += 'link to file: '+URL.getSalesforceBaseUrl().toExternalForm()+'/'+prod.id+'<br><br><br> Thanks,<br>Moengage Team</body></html>';
                mail.setHtmlBody(body);
                System.debug( 'body ' + body);
                
                // Step 5. Add your email to the master list
                mailList.add(mail);
                prod.No_Enquiry_Email_Sent__c = true;
                updatedld.add(prod);
                System.debug( 'prod ' + prod);
                
            }
            if(!mailList.isEmpty()) {
                try{
                    Messaging.sendEmail(mailList);
                    update updatedld;
                    system.debug('mailList '+mailList);
                }
                catch (Exception ex) {
                    errorMessages.add('Unable to send email to Tech: '+ ex.getStackTraceString());
                }
            }
        }
    }  
    
    //Batch Finish method for after execution of batch work
    global void finish(Database.BatchableContext BC) { 
        
    }
    
    //Method which schedules the ProductDownloadBatch
    global void execute(SchedulableContext sc) {        
        Emailalertbatchclass snInstance = new Emailalertbatchclass();
        ID batchprocessid = Database.executeBatch(snInstance);
    }
}

test Class
 
@isTest
public class EmailalertbatchclassTestclass
{
    static testMethod void testmethod1()
    {
        List<Lead> Leadld = new List<Lead>();
        lead ld = new lead();
        ld.FirstName= 'test';
        ld.LastName='Test2';
        ld.status='Enquiry';
        ld.Company = 'fgfh';
        ld.Email = 'manjunath.s@proseraa.com';
        ld.Manager_Email__c = 'chandra.s@proseraa.com';
        ld.No_Enquiry_Email_Sent__c = true;
        Insert ld;
        Leadld.add(ld); 
        
        Datetime Yesterday = Datetime.now().addDays(-1);
        Test.setCreatedDate(ld.Id, Yesterday);
        
        Test.startTest();
        ld.FirstName = 'test1';
        update ld;
        
        Emailalertbatchclass snInstance = new Emailalertbatchclass();
        ID batchprocessid = Database.executeBatch(snInstance);
        
        Test.stopTest();
    }
    public static testMethod void testschedule() {
        Test.startTest();
        Emailalertbatchclass sh1 = new Emailalertbatchclass();
        String sch = '0 00 01 * * ?'; 
        ID batchprocessid = Database.executeBatch(sh1);
        String jobId = system.schedule('Emailalertbatchclass', sch, sh1);
        System.assert(jobId != null);
        Test.stopTest(); 
    }
}

​​​​​​​
how to use best pratice for test classes for below code
 
@isTest
Private class TestProductSearchpopupController {
    @isTest
    static void testMethod1() 
    {   
        Account acc = new Account (name='Pencil');
        insert acc;
        Opportunity opp= new Opportunity ();
        opp.name= 'Testopp1';
        Opp.Accountid= acc.id;
        opp.CloseDate= date.today();
        opp.StageName= 'Qualification';
        insert opp;
        
        List <Quotes__c> lstquote = new List<Quotes__c>();
        
        Quotes__c testque = new Quotes__c();
        testque.Name = 'Test PriceBookEntry';
        testque.OpportunityId__c = opp.id;
        testque.AccountId__c = acc.id;
        lstquote.add(testque);
        
        List <Product2__c> lstproduct = new List<Product2__c>();
        Product2__c testProduct = new Product2__c();
        testProduct.Name='Test product';
        lstproduct.add(testProduct);
        
        List <PricebookEntry__c> lstpbe = new List<PricebookEntry__c>();
        
        PricebookEntry__c testpbe = new PricebookEntry__c();
        testpbe.Name='Test PriceBookEntry';
        lstpbe.add(testpbe);
        
        List <QuoteLineitem__c> lstqli = new List<QuoteLineitem__c>();
        QuoteLineitem__c testqli = new QuoteLineitem__c();
        testqli.QuotesId__c = testque.id;
        
        lstqli.add(testqli);
      

        Test.startTest();
        ApexPages.StandardController sc = new ApexPages.StandardController(lstquote[0]);
        ProductSearchPopupController psp = new ProductSearchPopupController(sc);
        psp.ProceedWithSelectedToNextPage();
        psp.processSelected();
        psp.runQuery();
        psp.saveproduct();
        Test.stopTest();
    }  
}

my class
 
public class ProductSearchPopupController {
   
    public String query {get; set;}
    public List<PricebookEntry__c> products {get; set;}
    public List<wrapProduct> wrapProductList {get; set;}
    public List<PricebookEntry__c> selectedProduct{get;set;}
    public List<QuoteLineitem__c> quoteLineList{get;set;}
    public List<wrapProduct> selectedWrapperList{get;set;}
    public Boolean normalList{get;set;}
    public Boolean selectedList{get;set;}
    public Boolean block{get;set;}
    public Boolean block1{get;set;}
    public Boolean block2{get;set;}
    public String SalesPrice {get; set;}
    public integer Discount {get; set;}
    public String Quantity {get; set;}
    public String ServiceDate {get; set;}
    Id recordId;
    
    public ProductSearchPopupController(ApexPages.StandardController controller){
        recordId = controller.getId();
        system.debug('recordId '+recordId);
        wrapProductList = new List<wrapProduct>();
        selectedWrapperList = new List<wrapProduct>();
        normalList = true;
        selectedList = false;
        block = true;
        block1 = false;
        block2 = false;
    }
    
    public PageReference runQuery(){
        if(query == null || query == ''){
            system.debug('query '+query);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Info,'Please enter Product to search for'));
            
            return null;
        }
        system.debug('query '+query);
        List<List<PricebookEntry__c>> searchResults=[FIND :query IN ALL FIELDS RETURNING PricebookEntry__c (id, Name, ProductCode__c, Product2Id__r.Product_Description__c,UnitPrice__c, UseStandardPrice__c)];
        if(searchResults[0]!=null){
            for(PricebookEntry__c a: searchResults[0]) {
                // As each Account is processed we create a new wrapAccount object and add it to the wrapAccountList
                wrapProductList.add(new wrapProduct(a));
                block = true;
                block1 = true;
                block2 = false;
            }
        }
        return null;
    }
    public PageReference ProceedWithSelectedToNextPage(){
        selectedWrapperList = new List<wrapProduct>();
        normalList = false;
        selectedList = true;
        for(wrapProduct selectedWrapObj: wrapProductList){
            system.debug('selectedWrapObj.selected  ---------'+selectedWrapObj.selected);
            if(selectedWrapObj.selected == true)
                selectedWrapperList.add(selectedWrapObj);
        }
        system.debug('selectedWrapperList size ---------'+selectedWrapperList.size());
        PageReference pageRef = new PageReference('/apex/AccountOpportunityTwoPage');
        pageRef.setRedirect(false);
        return pageRef;
    }
    public void processSelected() {
        selectedProduct = new List<PricebookEntry__c>();
        for(wrapProduct wrapProductObj : wrapProductList) {
            if(wrapProductObj.selected == true) {
                selectedProduct.add(wrapProductObj.acc);
                block = false;
                block1 = false;
                block2 = true;
                
            }
        }
    }
    
    public class wrapProduct{
        public PricebookEntry__c acc {get;set;}
        public Boolean selected {get;set;}
        public wrapProduct(PricebookEntry__c p) {
            this.acc = p;
            this.selected = false;
        }
        
    }
    
    public pagereference saveproduct(){ 
        List<QuoteLineitem__c> quoteLineList = new  List<QuoteLineitem__c>();
        if(!selectedProduct.isEmpty()){
            for(PricebookEntry__c sp:selectedProduct){
                system.debug('sp '+sp);
                QuoteLineitem__c qli = new QuoteLineitem__c();
                qli.QuotesId__c = recordId;
                qli.ListPrice__c = sp.UnitPrice__c;
                qli.UnitPrice__c = sp.UnitPrice__c;
                qli.Product2Id__c = sp.Product2Id__c;    
                if(Discount!=0 || Discount!=null){
                    qli.Discount__c = Discount;
                }
                quoteLineList.add(qli);
            }

            if(quoteLineList.size()>0){
                insert quoteLineList;
                PageReference pageRef = new PageReference('https://proseraa.lightning.force.com/lightning/r/Quotes__c/'+recordId+'/view');
                pageRef.setRedirect(true);
                return pageRef;
            }
        }
        return null;
    }
   
}

​​​​​​​
hey Guys

i need a small help regarding a test classes. Basically i am trying to design a test class for account and contact, in my case Account is Renamed as (Courses) and Contact is Renamed as (Students), and i have 2 custom objects Classes(Class__c) and Attendancess (Attendancess__c)

how do i design a test class for below apex class
public class UpdateUsingCheckboxC {
    
    @AuraEnabled
    public static List <Contact> fetchContact(string key) {
        system.debug('classname'+key);
        Class__c cls = [select id,Courses__r.name from Class__c where id=:key];
        string classname = cls.Courses__r.name;
        system.debug('classname'+classname);
        return [SELECT Id, Name,Account.Name,FirstName,LastName,Check_for_Attendance__c,Check_for_Absentee__c FROM Contact where (Check_for_Attendance__c=false AND Check_for_Absentee__c=false) AND Account.Name =:classname];
    }
    
    @AuraEnabled
    public static void updateRecord(List <String> lstRecordId,string key) {
        List<Contact> lstUpdate = new List<Contact>();
        List<Attendancess__c> listAttendnce = new List<Attendancess__c>();
        Class__c cls = [select id,Courses__r.name from Class__c where id=:key];
        if(cls.Id !=null){
            for(Contact con : [SELECT Id,AccountId, Name,Phone,FirstName,LastName,Check_for_Attendance__c,Check_for_Absentee__c  FROM Contact WHERE Id IN : lstRecordId]){
                con.Check_for_Attendance__c = true;
                con.Check_for_Absentee__c = false;
                lstUpdate.add(con);
                
                Attendancess__c attandenc = new Attendancess__c();
                attandenc.Class__c = cls.Id;
                attandenc.Student_Attended__c = true;
                attandenc.Name = con.Name;
                attandenc.Created_Date_Time__c = system.now();
                listAttendnce.add(attandenc);
                system.debug('listAttendnce'+listAttendnce);
            }
            
            if(lstUpdate.size() > 0){
                update lstUpdate;
            }
            if(listAttendnce.size() > 0){
                insert listAttendnce;
            }
        }
    }
    
    @AuraEnabled
    public static void updateSecondRecord(List <String> secondRecordId,string key) {
        system.debug('key1'+key);
        system.debug('secondRecordId '+secondRecordId);
        List<Contact> lstUpdate = new List<Contact>();
        List<Attendancess__c> listAttendnce = new List<Attendancess__c>();
        if(key !=null){
        Class__c cls = [select id,Courses__r.name from Class__c where id=:key];
            for(Contact con : [SELECT Id,AccountId, Name,Phone,FirstName,LastName,Check_for_Attendance__c,Check_for_Absentee__c  FROM Contact WHERE Id IN : secondRecordId]){
                con.Check_for_Absentee__c = true;
                con.Check_for_Attendance__c = false;
                lstUpdate.add(con);
                
                Attendancess__c attandenc = new Attendancess__c();
                attandenc.Class__c = cls.Id;
                attandenc.Student_Attended__c = false;
                attandenc.Name = con.Name;
                attandenc.Created_Date_Time__c = system.now();
                listAttendnce.add(attandenc);
                system.debug('listAttendnce'+listAttendnce);
            }
            
            if(lstUpdate.size() > 0){
                update lstUpdate;
            }
            if(listAttendnce.size() > 0){
                insert listAttendnce;
            }
        }
    }
    
}

 
Hello Guys

I need a small Help

I am working on a Education project, I have four custom objects, Student__c, Class__c, course__c,Attandence__c
The first part is working fine,  in a class related list(Snapshot 1)  when I click on Update Attendance, a check box is checked in a student object (Snapshot 2) and it Is checked in child object Attendance object and Related Record Gets created (Snapshot 3)
Now I want to put another button called as Update Absentee, when I click this button, Checkbox should get updated in the Student object named (Check for Absentee) and related record should get created and it should not get updated in attendance custom object,
User-added image

User-added image
User-added image
 
Hello all

In the contact object there is a custom checkbox field called "Course_completed__c" when i check the checkbox field, it should fire an email, i know this can be achived through workflow and process builder, but i want to try in apex so  i have designed a trigger and apex class, but i do get an error

the error i get is - Variable does not exist: checkbox and Method does not exist or incorrect signature: void checkfeesurvey(List<Contact>) from the type emailfeesurvey_handler

Apex class - 

public class emailfeesurvey_handler {
    public static void checkfeesurvey(List<contact> contactlist) {
        try {
            List<String> emailList = new List<String>();
            
            for(contact c : contactList) {
                if(c.Email != null && c.checkbox == 'True') {
                    emailList.add(c.Email);
                    EmailTemplate temp = [SELECT Id FROM EmailTemplate WHERE developername = 'Course_complete_survey' LIMIT 100];
                    system.debug('emailList------' + emailList);
                    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
                    if(emailList.size() > 0) {
                        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                        mail.setToAddresses(emailList);
                        mail.setTemplateId(temp.Id);
                        mail.setTargetObjectId(c.Id);
                        mails.add(mail);
                    }
                    Messaging.sendEmail(mails);
                }
            }
        } catch (Exception ex) {
            system.debug('Exception---ofLine--->' + ex.getLineNumber());
            system.debug('Exception---Message--->' + ex.getMessage());
        }
    }
}


Trigger - 

trigger emailfeesurvey on Contact (before insert, before update) {
    if((trigger.isInsert && trigger.isBefore) || (trigger.isUpdate && trigger.isBefore)) {
        emailfeesurvey_handler.checkfeesurvey(trigger.new);
    }
}


 
Hello all

I want to  send an automatic email when lead status is converted to "Qualified" , i tried it in workflow and process, it worked fine, now i want to try it in apex , i have ready made email template named "XXX" which shows as 

Hello {!Lead.LastName} 

Thank you for the registering with us 
Soon we will get back to you 

Team EduProserra

my apex class is

public class emailSending {

    public String Lead { get; set; }
    public string toMail { get; set;}
    public string ccMail { get; set;}
    public string repMail { get; set;}
    
    public void sendMail(){
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        string[] to = new string[] {toMail};
        string[] cc = new string[] {ccMail};
        
        email.setToAddresses(to);
        if(ccMail!=null && ccMail != '')
            email.setCcAddresses(cc);
        if(repmail!=null && repmail!= '')
            email.setInReplyTo(repMail);
        
        email.setSubject('Thank you for the Registration');
        
        email.setHtmlBody('Hello, {!Lead.LastName} <br/><br/>Thank you for Registration. <br/>We will get back to you for more details<br/><br/>Regards<br/> EduPro Team');
        try{
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
        }catch(exception e){
            apexpages.addmessage(new apexpages.message(apexpages.severity.error,e.getMessage()));
        }
        
        toMail = '';
        ccMail = '';
        repMail = '';
    }
}

how do i design a trigger for this??
Lightning component to update contact record with checkbox field=true
Hi all,
I am new to coding.I am stuck here can any one please help me.Your help is appreciated.

My requirement is to display 10 contact records with checkbox beside to it , with update button at last.After clicking on the update button ,selected record should get updated.
Below is my code

***************************APEX CODE***********************************
public class getAllContactRecords 
{
    @AuraEnabled
    public static List<contactListWrapper> getContacts()
    {
        List<contactListWrapper> lstContactWrap=new List<contactListWrapper>();
        for(Contact con:[select id,Name from Contact limit 10])
        {
            lstContactWrap.add(new contactListWrapper(false,con));
        }
        return lstContactWrap;
    }
    
    /* wrapper class */  
    public class contactListWrapper 
    {
        @AuraEnabled public boolean isChecked ;
        @AuraEnabled public  contact objContact ;
        public contactListWrapper(boolean isChecked, contact objContact)
        {
            this.isChecked = isChecked;
            this.objContact = objContact;
        }
    }
    
}

***************************Lightning component***********************************
<aura:component controller="getAllContactRecords" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
   <!-- aura attributes to store data/values --> 
    <aura:attribute name="ContactList" type="Contact[]"/>
    <!-- call doInit method on component load -->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <aura:iteration items="{!v.ContactList}" var="obj">
        
        <tr>
            <td>  <ui:inputCheckbox text="{!obj.objContact.Id}"
                                    value="{!obj.isChecked}"
                                    change="{!c.checkboxSelect}" aura:id="chkBoxId"/>
            </td>
            <td>
                {!obj.objContact.Name} <br/> 
            </td>
        </tr>

    </aura:iteration>
    
    <lightning:button label="Update" onclick="{!c.updateSelectedRecords}"/> 
</aura:component>

***************************Lightning controller***********************************

({
    doInit : function(component, event, helper) 
    {
        var action=component.get("c.getContacts");
        action.setCallback(this, function(data){
            
            component.set("v.ContactList",data.getReturnValue());
            
        });  
        $A.enqueueAction(action);
    },
    
    
    checkboxSelect : function(component, event, helper) 
    {
         alert('test');
        var selectedHeaderCheck = event.getSource().get("v.text");
        var checkVar=component.find("v.chkBoxId");
        alert(selectedHeaderCheck);
     //  $A.enqueueAction(action);
    },
    
    updateSelectedRecords : function(component, event, helper) 
    {
        alert('test 1')
       var check=component.find("v.chkBoxId");
         if (check.get("v.value") == true)
         {
          //         updateId.push(getAllId.get("v.text"));
         }
      // $A.enqueueAction(action); 
    } 
})
<aura:component controller="ListAccounts">
  <aura:attribute name="accounts" type="List" />
  <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <aura:attribute name="accList" type="list"/>
  <!--
    Use a data table from the Lightning Design System:
    https://www.lightningdesignsystem.com/components/data-tables/
  -->
  <table class="slds-table slds-table--bordered slds-table--striped slds-table--cell-buffer slds-table--fixed-layout">
    <thead>
      <tr class="slds-text-heading--label">
                  <th scope="col"><div class="slds-truncate" title="Select">Select</div></th>

        <th scope="col"><div class="slds-truncate" title="ID">ID</div></th>
        <th scope="col"><div class="slds-truncate" title="Name">Name</div></th>
        <th scope="col"><div class="slds-truncate" title="Site">Site</div></th>
       
      </tr>
    </thead>
    <tbody>
      <!-- Use the Apex model and controller to fetch server side data -->
      <aura:iteration items="{!v.accounts}" var="account">
        <tr>
          <th scope="row">
              <ui:inputCheckbox />
            </th>

          <th scope="row"><div class="slds-truncate" title="{!account.Id}">{!account.Id}</div></th>
          <td><div class="slds-truncate" title="{!account.Name}">{!account.Name}</div></td>
          <td><div class="slds-truncate" title="{!account.Site}">{!account.Site}</div></td>
          
          <td>
            
          </td>
        </tr>
      </aura:iteration>
        <ui:button label="Aprove" press="{!c.approve}"/>
    </tbody>
  </table>
</aura:component>



({
  // Fetch the accounts from the Apex controller
  doInit: function(component,event,helper) {
    var action = component.get('c.getAccounts');
    // Set up the callback
    var self = this;
    action.setCallback(this, function(actionResult) {
     component.set('v.accounts', actionResult.getReturnValue());
    });
    $A.enqueueAction(action);
  },
    approve: function(component,event,helper) {
    var a = component.get('c.getApproved');
        console.log('checking the status');
        a.setCallback(this, function(response) {
     component.set('v.accList', response.getReturnValue());
    });
    $A.enqueueAction(a);
    
    },
    
})









public class ListAccounts {
  @AuraEnabled
  public static List<Account> getAccounts() {
    return [SELECT Id, name,site from Account Limit 6];
  }
    @AuraEnabled
    public static  void getApproved(){
        List<Account> accs=[select Id,Name,Site from Account];
        for(Account a:accs){
            a.Site='Approved';
        }
        
        
        
    }
    
}












 
Hi all, I want to preface this by saying I have absolutley zero knowledge of coding and how to write an apex trigger. However, I do know the result i'm trying to achieve so I'm hoping my description will be enough for someone to provide some help.

My situation is the following: I have 2 custom objects Volunteer and Subject. What I want to happen is that when a certain field (Volunteer_Status__c), a picklist value, is updated to the selection "Screening Completed" a new record is created under the Subject object that replicates the information stored under the volunteer record.

If someone could provide some instruction it would be much appreciated!
Hello all

I want to  send an automatic email when lead status is converted to "Qualified" , i tried it in workflow and process, it worked fine, now i want to try it in apex , i have ready made email template named "XXX" which shows as 

Hello {!Lead.LastName} 

Thank you for the registering with us 
Soon we will get back to you 

Team EduProserra

my apex class is

public class emailSending {

    public String Lead { get; set; }
    public string toMail { get; set;}
    public string ccMail { get; set;}
    public string repMail { get; set;}
    
    public void sendMail(){
        Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
        string[] to = new string[] {toMail};
        string[] cc = new string[] {ccMail};
        
        email.setToAddresses(to);
        if(ccMail!=null && ccMail != '')
            email.setCcAddresses(cc);
        if(repmail!=null && repmail!= '')
            email.setInReplyTo(repMail);
        
        email.setSubject('Thank you for the Registration');
        
        email.setHtmlBody('Hello, {!Lead.LastName} <br/><br/>Thank you for Registration. <br/>We will get back to you for more details<br/><br/>Regards<br/> EduPro Team');
        try{
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { email });
        }catch(exception e){
            apexpages.addmessage(new apexpages.message(apexpages.severity.error,e.getMessage()));
        }
        
        toMail = '';
        ccMail = '';
        repMail = '';
    }
}

how do i design a trigger for this??