• Sony PSP
  • NEWBIE
  • 30 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 14
    Questions
  • 13
    Replies
Hi,

is there a way to optimized this code? I am having problem with bulk upload and these needs to be optimized, can you instruct me on what should be the proper way?
 
public static void populateLastestEnrollment(List<Case> pCase){
        Id EnrollmentRecordType = Schema.Sobjecttype.Case.getRecordTypeInfosByName().get('Enrollment').getRecordTypeId();
        Id DiscontinuedmentRecordType = Schema.Sobjecttype.Case.getRecordTypeInfosByName().get('Unenroll From GPS').getRecordTypeId();
        Id AdultPatient = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Adult Patient').getRecordTypeId();
        Id MinorPatient = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Minor Patient').getRecordTypeId();
        Id RECORDTYPEID_RELATIONSHIP_INDIVIDUAL = Schema.SObjectType.Relationship__c.getRecordTypeInfosByName().get('Individual Relationship').getRecordTypeId();
        
        List<Account> updatedAccountList = new List<Account>();
        Set<Id> caseAccountId = new Set<Id>();
        
        //Get the parent Account of the case
        for(Case cs : pCase){
            caseAccountId.add(cs.AccountId);
        }
        
        List<Account> caseAccountList = [SELECT Id, Latest_Enrollment_Unenrollment_Case__c, Consent_Provided__c,Consent_Version__c, Consent_Provided_Date__c, 
                                         Enrollment_Status_Text__c, Enrollment_Form_Received_Date__c, RecordTypeId, X18th_Birthdate__c, PersonMobilePhone, PersonHomePhone,
                                         (SELECT Id, GPS_Enrollment_Status_Detail__c, Date_Consent_Provided__c, GPS_Enrollment_Status__c, Enrollment_Type__c,
                                          Enrollment_Form_Received_Date__c, Consent_Version__c, CaseNumber, Consent_Provided__c, Consent_Provided_By__c,
                                          CreatedDate, Status, RecordTypeId, Case_Sub_Status__c FROM Cases ORDER BY CreatedDate ASC) 
                                         FROM Account WHERE Id IN: caseAccountId];
        
        //loop through all child records
        for(Account a : caseAccountList){
            //Checks if case object has records
            if(a.Cases.size() > 0){
                // find out which one is the most recent relevant case for a given patient account
                for(Case c : a.Cases){
                    if(c.CreatedDate >= mostRecentCase.CreatedDate || mostRecentCase.Id == null){
                        if(c.RecordTypeId == EnrollmentRecordType || 
                           (c.RecordTypeId == DiscontinuedmentRecordType
                            && c.Status == 'Closed'
                            && c.Case_Sub_Status__c == 'Completed')){
                                mostRecentCase = c;
                            }                     
                    }
                }
            }
            
            // If there is no relevant case available, then make the auto populated fields null:
            if(mostRecentCase.Id == null){
                a.Latest_Enrollment_Unenrollment_Case__c = null;
                a.Consent_Provided_Date__c = null;
                a.Consent_Expiration_Date__c = null;
                a.Consent_Provided__c = null;
                a.Consent_Version__c = null;
                a.Enrollment_Form_Received_Date__c = null;
                a.Enrollment_Status_Text__c = 'Never Enrolled';
            } else if(mostRecentCase.RecordTypeId == EnrollmentRecordType &&
                      (mostRecentCase.Enrollment_Type__c != 'New Consent' || mostRecentCase.Date_Consent_Provided__c != null)){
                a.Consent_Provided__c = mostRecentCase.Consent_Provided__c;
                a.Consent_Provided_Date__c = mostRecentCase.Date_Consent_Provided__c;
                a.Consent_Version__c = mostRecentCase.Consent_Version__c;
                if (a.Consent_Provided__c == null){
                    a.Consent_Expiration_Date__c = null;
                } else if (a.Consent_Provided__c == 'Verbal Consent') {
                    a.Consent_Expiration_Date__c = a.Consent_Provided_Date__c.addDays(30);
                } else if (a.Consent_Provided__c == 'Written Consent') {
                    if (a.X18th_Birthdate__c.addDays(30) < a.Consent_Provided_Date__c.addYears(10) && a.X18th_Birthdate__c > mostRecentCase.Date_Consent_Provided__c){ // Sheri updated add days
                        a.Consent_Expiration_Date__c = a.X18th_Birthdate__c.addDays(30); 
                    } else {
                        a.Consent_Expiration_Date__c = a.Consent_Provided_Date__c.addYears(10);
                    }
                }
                a.Consent_Expiration_Workflow_Reset__c = false;
                a.Enrollment_Status_Text__c = mostRecentCase.GPS_Enrollment_Status__c;
                a.Enrollment_Form_Received_Date__c = mostRecentCase.Enrollment_Form_Received_Date__c;       
                a.Latest_Enrollment_Unenrollment_Case__c = mostRecentCase.Id;
            } else if(mostRecentCase.RecordTypeId == DiscontinuedmentRecordType){
                a.Consent_Provided__c = null;
                a.Consent_Provided_Date__c = null;
                a.Consent_Expiration_Date__c = null;
                a.Consent_Version__c = null;
                a.Enrollment_Status_Text__c = mostRecentCase.GPS_Enrollment_Status__c;
                a.Latest_Enrollment_Unenrollment_Case__c = mostRecentCase.Id;
            }
            //Make sure that only 1 record will update the Parent
            updatedAccountList.add(a);
        }

        //update Account
        if(updatedAccountList.size() > 0){
                update updatedAccountList;
        }

    }

 
Hi guys,

hope you can help me.

I have this two fields under Project__C namely as Primary_Solution_Series__cand Secondary_Solution_Series__c and another field wherein results/sum are being put namely as Allocated_OEM_Project_Forecast__c.

the scenario is I have a product forecast under agreement which is under project meaning the product forecast is the grand child of project.

under the productforecast there are fields namely Quantity and Product(Primary and Secondary Series)

example is below

User-added image 

what i want is that if S332U if chosen as Primary_Solution_Series__c  it will auto recalculate having the sum 13000 in the  Allocated_OEM_Project_Forecast__c under the Project__c and if Primary_Solution_Series__c is has chosen S3320 it will recalculate having the sum 8500.

another what is the sum of the Allocated_OEM_Project_Forecast__c will also be written on Agreement__c under the field OPA_Lifetime_Product_Forecast__c. wherein the Agreement__c is the child or Project__c

I already have the delete/add function my problem is that when Primary_Solution_Series__c  and Secondary_Solution_Series__c  has changed it doesn't recalculate.
Set<ID> poemId = new Set<ID>();
        Set<ID> poemssId = new Set<ID>();
        Set<ID> pmmfId = new Set<ID>();
        List<Apttus__APTS_Agreement__c> AgreementToUpdate = new List<Apttus__APTS_Agreement__c>();
        List<Project__c> PaneltoUpdate = new List<Project__c>();
        Double pfSum = 0;
        
        for(Project__c pfc: newProject){
            poemId.add(pfc.id);
            poemssId.add(pfc.Primary_Solution_Series__c);
            pmmfId.add(pfc.Secondary_Solution_Series__c);}
        
        for(Apttus__APTS_Agreement__c agr : [select id FROM Apttus__APTS_Agreement__c where  Panel__c =: poemId]){
            poemId.add(agr.id);
        
        for(APTS_Product_Forecast__c pf : [SELECT APTS_Quantity__c , APTS_Price_Agreement__c, Panel__c FROM APTS_Product_Forecast__c WHERE (product_is_primary__c = TRUE OR product_is_secondary__c = TRUE ) AND APTS_Price_Agreement__c != NULL AND  APTS_Price_Agreement__c =: poemId]){
                                                  
            pfSum +=pf.APTS_Quantity__c;
        
        
        for(Project__c prj: [Select Id, Primary_Solution_Series__c, Secondary_Solution_Series__c from Project__c where Id =: poemId]){
            if(prj.Primary_Solution_Series__c != oldMap.get(prj.id).Primary_Solution_Series__c || prj.Secondary_Solution_Series__c != oldMap.get(prj.id).Secondary_Solution_Series__c)
                prj.Allocated_OEM_Project_Forecast__c = pfSum;
            PaneltoUpdate.add(prj);
        }
        
        for(Apttus__APTS_Agreement__c agmt: [Select Id from Apttus__APTS_Agreement__c where ID =: poemId]){
            agmt.OPA_Lifetime_Product_Forecast__c = pfSum;
            AgreementToUpdate.add(agmt);}
    }
Hi Guys,

Can you help me with this, I am just new with salesforce

I need to update the Project Object where the field is OEM_Project_Forecast__c, the Agreement__c is the child of the Project, and the Child of Agreement are list of Product_Forecast__cwherein I need to get the sum of all the product forecast and put it on the Project under the OEM_Project_Forecast__c the sum of product forecast.

thank you
public with sharing class AgreementTriggerHandler{
    
    public static void onAfterInsert(List<Agreement__c> agrList) {
        isUpdateSynapticsPanel(agrList);
    }
    
    public static void onAfterUpdate(List< Agreement__c> agrList) {
        isUpdateSynapticsPanel(agrList);
    }
    
    
    public static void isUpdateSynapticsPanel (List< Agreement__c> agrList){
        Set<Id> agrIdSet = new Set<Id>();
        List<Project__c> PaneltoUpdate = new List<Project__c>();
        Double pfSum = 0;

        for(Agreement__c pfs : agrList){
         // if(pfs.Panel__c != null)
         System.debug('PFA value = ' + pfs);
            agrIdSet.add(pfs.Panel__c);
        }
        
        //System.debug('agrIdSet value = ' + agrIdSet);

       for(Agreement__c  pf: [SELECT Lifetime_Product_Forecast__c, Panel__c  FROM Agreement__c WHERE Panel__c =: agrIdSet]){
            System.debug('pf value = ' + pf);
            pfSum += pf.Lifetime_Product_Forecast__c;
          
        }
  
         
        for(Project__c prj: [Select Id from Project__c where Id =: agrIdSet]){
             System.debug('projsum value = ' + prj);
            prj. OEM_Project_Forecast__c = pfSum;
            System.debug('SUM value = ' + pfSum);
            
            PaneltoUpdate.add(prj);
        }
        
         if(!PaneltoUpdate.isEmpty()){
            update PaneltoUpdate;
        }
    }
}

 
Hi Guys,

Can you please help me with my test class I'm only achieving 39% as of now, please do comment on some line I am just new with test classes.
 
//Test CLASS
public class ProductImportController{


    public Blob csvFileBody { get; set; }
    public String csvFileName { get; set; }
    
    public Boolean showResults { get; set; }
    public Boolean showImport { get; set; }
    public Boolean isUploading { get; set; }
    
    public List<Product2> prdctList { get; set; }
    public List<PricebookEntry> pbeListStandard  { get; set; }
    public List<PricebookEntry> pbeListCustom { get; set; }
    
    public ProductImportController(){
        //Show/hide sections
        showResults = false;
        showImport = true;
        isUploading = false;
    }
    
    public void upload(){
    
        if(isUploading){ return; }
        isUploading = true;
    
        //Show/hide sections
        showResults = true;
        showImport = false;
    
        try{
            parseCsvInsertProductsPricebooks();
        }catch(Exception e){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, e.getMessage() ));
            
            //Show/hide sections
            showResults = false;
            showImport = true;
            isUploading = false;
            
            if(Test.isRunningTest()){
                throw e;
            }else{
                return;
            }
        }
        
        //Finished
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO, 'Product import completed.'));
        isUploading = false;
    }
    
    public void parseCsvInsertProductsPricebooks(){
        
        if(csvFileBody == null){
            throw new ProductImportException('No CSV found.');
        }
        
        //Convert from blob to string
        String csvString = csvFileBody.toString();
        csvFileBody = null;
        csvFileName = null;
        
        if(String.isBlank(csvString)){
            throw new ProductImportException('Empty CSV found.');
        }
        
        //Parse CSV into separate fields
        List<List<String>> allFields = parseCSV(csvString);
        
        if(allFields == null || allFields.isEmpty()){
            throw new ProductImportException('Empty CSV found.');
        }
                
        //Use first line as header
        List<String> headerFields = allFields.remove(0);
        List<HeaderWrapper> headerList = parseHeaders(headerFields);
        List<LineWrapper> lineList = new List<LineWrapper>();
        
        //Parse remaining lines
        if(allFields == null || allFields.isEmpty()){
            throw new ProductImportException('No rows found.');
        }else{
            for(List<String> line : allFields){
                lineList.add(new LineWrapper(line,headerList));
            }
        }
        
        //Get all products
        prdctList = new List<Product2>();
        for(LineWrapper line : lineList){
            prdctList.add(line.prdct);
        }
        
        //Insert products
        try{
            insert prdctList;
            System.debug(prdctList);
        }catch(Exception e){
            throw new ProductImportException('Could not insert products. ' + e.getMessage() ,e);
        } 
        
        
        //Insert standard pricebook entries
        pbeListStandard = new List<PricebookEntry>();
        for(LineWrapper line : lineList){
            List<PricebookEntry> l = line.getStandard();
            if(l != null){
                pbeListStandard.addAll(l);
            }
        }
        try{
            if(!pbeListStandard.isEmpty()){
                System.debug('* ** *** inserting standard pbe '  + pbeListStandard);
                insert pbeListStandard;
                System.debug(pbeListStandard);
            }
        }catch(Exception e){
            throw new ProductImportException('Could not insert pricebook entries. ' + e.getMessage() ,e);
        }
        
        //Insert custom pricebook entries
        pbeListCustom = new List<PricebookEntry>();
        for(LineWrapper line : lineList){
            List<PricebookEntry> l = line.getCustom();
            if(l != null && !l.isEmpty()){
                pbeListCustom.addAll(l);
            }
        }
        try{
            if(!pbeListCustom.isEmpty()){
                System.debug('* ** *** inserting custom pbe ' + pbeListCustom);
                insert pbeListCustom;
                System.debug(pbeListCustom);
            }
        }catch(Exception e){
            throw new ProductImportException('Could not insert pricebook entries. ' + e.getMessage(),e);
        }
    }
    
    public static List<HeaderWrapper> parseHeaders(List<String> headerFields){
    
        //List of headers
        List<HeaderWrapper> headerList = new List<HeaderWrapper>();
        
        //Mapping setting
        Map<String,ProductImportMapping__mdt> pim = new Map<String,ProductImportMapping__mdt>();
        for(ProductImportMapping__mdt p : [SELECT MasterLabel, Field__c, isProductField__c, Pricebook__c, Isocode__c FROM ProductImportMapping__mdt]){
            pim.put(p.MasterLabel,p);
        }
        
        //Field types
        Map<String, Schema.SObjectField> fieldMap  = Schema.SObjectType.Product2.fields.getMap();

        //Pricebooks
        Map<Id,Pricebook2> pbMap = new Map<Id,Pricebook2>([SELECT Id FROM Pricebook2 WHERE IsStandard = false]);
        
        Id pbStandard;
        if(Test.isRunningTest()){
            pbStandard = Test.getStandardPricebookId();
        }else{
            List<Pricebook2> pbStandardList = [SELECT Id FROM Pricebook2 WHERE IsStandard = true];
            if(pbStandardList == null || pbStandardList.isEmpty()){
                throw new ProductImportException('Could not find standard pricebook.');
            }else{
                pbStandard = pbStandardList.get(0).Id;
            }
        }
        
        //Map header
        for(String field : headerFields){
            
            //Get custom setting
            ProductImportMapping__mdt setting = pim.get(field);
            HeaderWrapper header;
            
            if(setting != null){
                if(setting.isProductField__c){
                
                    //check that field is valid and creatable
                    if(fieldMap.containsKey(setting.Field__c.toLowerCase()) && fieldMap.get(setting.Field__c.toLowerCase()).getDescribe().isCreateable()){                                        
                        
                        //create header wrapper
                        header = new HeaderWrapper();
                        header.name = field;
                        header.field = setting.Field__c;
                        header.isProductField = true;
                        header.isSkip = false;
                        header.type = String.valueOf(fieldMap.get(setting.Field__c.toLowerCase()).getDescribe().getType());
                        
                    }else{
                    
                        //skip header wrapper if no field
                        header = new HeaderWrapper();
                        header.isSkip = true;
                        
                    }
                    
                }else{
                
                    //check that pricebook is valid                    
                    Id pbId;
                    try{
                        pbId = Id.valueOf(setting.Pricebook__c);
                    }catch(Exception e){
                        throw new ProductImportException('Could not convert pricebook Id.', e);
                    }
                    if(!pbMap.containsKey(pbId)){
                        throw new ProductImportException('Id is not a custom pricebook Id');
                    }
                    
        
                    //create header wrapper
                    header = new HeaderWrapper();
                    header.name = field;
                    header.isProductField = false;
                    header.pricebook = setting.Pricebook__c;
                    header.standard = pbStandard;
                    header.isocode = setting.Isocode__c;
                    header.isSkip = false;
                    
                }
            }else{
                //skip header wrapper
                header = new HeaderWrapper();
                header.isSkip = true;
            }
        
            //add to list
            headerList.add(header);

        }//end-for
        
        return headerList;
        
    }//end parseHeaders
    
    //Parse CSV into separate fields
    public static List<List<String>> parseCSV(String contents) {
        List<List<String>> allFields = new List<List<String>>();
    
        contents = contents.replaceAll(',"""',',"DBLQT').replaceall('""",','DBLQT",');
        contents = contents.replaceAll('""','DBLQT');
        List<String> lines = new List<String>();
        try {
            lines = contents.split('\n');
        } catch (Exception e) {
            throw new ProductImportException('Could not split CSV.', e);
        }
        
        Integer num = 0;
        for(String line : lines) {
            // check for blank CSV lines (only commas)
            if (line.replaceAll(',','').trim().length() == 0) break;
            
            
            line = line.replaceAll('\r','').trim();
            
            List<String> fields = line.split(',');  
            List<String> cleanFields = new List<String>();
            String compositeField;
            Boolean makeCompositeField = false;
            for(String field : fields) {
                if (field.startsWith('"') && field.endsWith('"')) {
                    cleanFields.add(field.replaceAll('DBLQT','"'));
                } else if (field.startsWith('"')) {
                    makeCompositeField = true;
                    compositeField = field;
                } else if (field.endsWith('"')) {
                    compositeField += ',' + field;
                    cleanFields.add(compositeField.replaceAll('DBLQT','"'));
                    makeCompositeField = false;
                } else if (makeCompositeField) {
                    compositeField +=  ',' + field;
                } else {
                    cleanFields.add(field.replaceAll('DBLQT','"'));
                }
            }
            
            allFields.add(cleanFields);
        }
        
        return allFields;       
    }//end parseCSV
    
    //wrapper for line
    class LineWrapper{
        Product2 prdct;
        Map<String,PricebookEntry> pbeStandard = new Map<String,PricebookEntry>();
        List<PricebookEntry> pbeCustom = new List<PricebookEntry>();
    
        public LineWrapper(List<String> fields, List<HeaderWrapper> headerList){
            
            System.debug('* ** *** fieldsize: ' + fields.size() + '. headersize: ' + headerList.size());
            
            //Loop through every cell in row
            for(Integer ctr = 0; ctr < fields.size() && ctr < headerList.size(); ctr++){
    
                //Get value of cell and header
                String field = fields.get(ctr);
                HeaderWrapper header = headerList.get(ctr);
                
                System.debug('LineWrapper #' + ctr + ': "' + field + '" ' + header);
                
                if(header == null || header.isSkip){
                    //Do nothing
                    System.debug('* ** *** skip');
                }else if(header.isProductField && field == null){
    
                    //Field name is required
                    throw new ProductImportException('Could not identify field for line: ' + fields);
    
                }else if(header.isProductField && field != null){
    
                    //Create product
                    if(this.prdct == null){
                        this.prdct = new Product2();
                    }
    
                    //Set value of field depending on type
                    try{
                        if(header.type == 'BOOLEAN'){
                            this.prdct.put(header.field,Boolean.valueOf(field));
                        }else if(header.type == 'DATETIME'){
                            this.prdct.put(header.field,DateTime.valueOf(field));
                        }else if(header.type == 'DOUBLE'){
                            this.prdct.put(header.field,Double.valueOf(field));
                        }else if(header.type == 'BOOLEAN'){
                            this.prdct.put(header.field,Boolean.valueOf(field));
                        }else if(header.type == 'REFERENCE'){
                            this.prdct.put(header.field,Id.valueOf(field));
                        }else{
                            this.prdct.put(header.field,field);
                        }
                    }catch(Exception e){
                        throw new ProductImportException('Could not populate field ' + header.field + ' with ' + field);
                    }
    
                }else if(String.isBlank(header.isocode) || header.pricebook == null){
    
                    //Pricebook and isocode mapping required
                    throw new ProductImportException('Could not identify pricebook and currency for line: ' + fields);
    
                }else{
                    Decimal price = Decimal.valueOf(field);
                    
                    //Create custom pricebook entry
                    PricebookEntry pbe = new PricebookEntry(Pricebook2Id = header.pricebook, UnitPrice = price, IsActive = true,CurrencyIsoCode=header.isocode);
                    
                    
                    //Create standard pricebook entry
                    if(!pbeStandard.containsKey(header.isocode)){
                        pbeStandard.put(header.isocode,new PricebookEntry(Pricebook2Id = header.standard, UnitPrice = price, IsActive = true,CurrencyIsoCode=header.isocode));
                        
                        //Set custom to use standard
                        pbe.UseStandardPrice = true;
                    }
                    
                    //Add custom pricebook entry to list
                    this.pbeCustom.add(pbe);
                
                }//end if-else
    
            }//end for
    
        }//end constructor
        
        public List<PricebookEntry> getStandard(){
            for(PricebookEntry pbe : pbeStandard.values()){
                pbe.Product2Id = prdct.Id;
            }
            return pbeStandard.values();
        }
        
        public List<PricebookEntry> getCustom(){
            for(PricebookEntry pbe : pbeCustom){
                pbe.Product2Id = prdct.Id;
            }
            
            return pbeCustom;
        }
    
    }//end class

    //custom exception
    class ProductImportException extends Exception {}

    //wrapper for header
    class HeaderWrapper{
        String name;
        String field;
        String isocode;
        String type;
        Id pricebook;
        Id standard;
        boolean isProductField;
        boolean isSkip;
    }
    
}
 
//Test CLASS
@isTest
public class ProductImportController_Test {
    private static testMethod void testData()
    {
        
        Product2 prdctlist = new Product2(Name = 'Test Product004', ProductCode = 'Test Product004');
        insert prdctlist;
        
        PricebookEntry pbeListStandard =  new PricebookEntry();
        PricebookEntry pbeListCustom =  new PricebookEntry();

ApexPages.standardController(testProduct);
        ProductImportController scontroller = new ProductImportController();
        

        scontroller.csvFileName = 'Test Product';
        scontroller.csvFileBody = Blob.valueOf('Test AttachmentBody');


        scontroller.upload();
        
    }      
}

 
HI,

I have this class

public class OpportunityContactRoleController {
    
    public Id contRoleId {get; set;}
    public Id oppId;
    public Opportunity oppObj;
    public ApexPages.StandardController controller {get; set;}
    

    public List<OpportunityContactRole> oppContRoles {get; set;}
    
    public OpportunityContactRoleController(ApexPages.StandardController controller){
        this.oppObj = (Opportunity)controller.getRecord();
        oppId = this.oppObj.Id;
        
        oppContRoles = [SELECT Id,OpportunityId, Contact.Name, Contact.Email, Role, Contact.Account.Name, Contact.Phone, IsPrimary
                            FROM OpportunityContactRole WHERE OpportunityId = :((Opportunity)controller.getRecord()).Id];
        
    }
    
    public void deleteOppContRole(){
        if(contRoleId != null){
        OpportunityContactRole ocr = new OpportunityContactRole();
        ocr.Id = contRoleId;
        delete ocr;
        oppContRoles = new List<OpportunityContactRole>();
        
        oppContRoles = [SELECT Id,OpportunityId, Contact.Name, Contact.Email, Role, Contact.Account.Name, Contact.Phone, IsPrimary
                            FROM OpportunityContactRole WHERE OpportunityId = :((Opportunity)controller.getRecord()).Id];
        }
        
    }
    
   public pageReference primaryContact() {
     
       PageReference pageRef = Page.OpportunityPrimaryContact;
       pageRef.getParameters().put('Id', oppId);
       pageRef.setRedirect(true);
       
       return pageRef;
   }
    
}



Test Class :


@isTest
public class OpportunityContactRoleController_Test {
    
    private static testMethod void testData(){
        
 
        Account testAccount = new Account(Name = 'Test Account', Country__c = 'Denmark');
        insert testAccount;
        
     
        Contact testContact = new Contact(LastName = 'Test LastName', FirstName = 'Test LastName');
        insert testContact;
        

        Opportunity testOpportunity = new Opportunity(AccountId = testAccount.Id, Name = 'Test Opportunity', Country__c = 'Denmark', 
                                                      
                                                      CurrencyIsoCode = 'USD', StageName = 'Loan Current', CloseDate = date.today(), Days_In_Term__c = 2 );
        insert testOpportunity;
        

        OpportunityContactRoleController controller = new OpportunityContactRoleController(new ApexPages.StandardController(testOpportunity));
  
        controller.primaryContact();

        OpportunityContactRole ocr = new OpportunityContactRole(OpportunityId = testOpportunity.Id, ContactId = testContact.Id );
        insert ocr;
        
       
        controller.contRoleId = ocr.Id;
        controller.deleteOppContRole();
        
}
}



when I run the test class it fails and returns like this.


Class.OpportunityContactRoleController.deleteOppContRole: line 30, column 1
Class.OpportunityContactRoleController_Test.testData: line 33, column 1

System.NullPointerException: Attempt to de-reference a null object


Any Idea which returns a Null?

Apologies Still a newbiew in this
Hi Guys,

good day!

Just a newbie in here, can you assist me with below Apex Class I already made a Test Class and my Problem in the Test Class is the part of method  deleteOppContRole() wherein it doesn't covered any help please ?

public class OpportunityContactRoleController {
    
    public Id contRoleId {get; set;}
    public Id oppId;
    public Opportunity oppObj;
    public ApexPages.StandardController controller {get; set;}
    

    public List<OpportunityContactRole> oppContRoles {get; set;}
    
    public OpportunityContactRoleController(ApexPages.StandardController controller){
        this.oppObj = (Opportunity)controller.getRecord();
        oppId = this.oppObj.Id;
        
        oppContRoles = [SELECT Id,OpportunityId, Contact.Name, Contact.Email, Role, Contact.Account.Name, Contact.Phone, IsPrimary
                            FROM OpportunityContactRole WHERE OpportunityId = :((Opportunity)controller.getRecord()).Id];
        
    }
    
    public void deleteOppContRole(){
        if(contRoleId != null){
        OpportunityContactRole ocr = new OpportunityContactRole();
        ocr.Id = contRoleId;
        delete ocr;
        oppContRoles = new List<OpportunityContactRole>();
        
        oppContRoles = [SELECT Id,OpportunityId, Contact.Name, Contact.Email, Role, Contact.Account.Name, Contact.Phone, IsPrimary
                            FROM OpportunityContactRole WHERE OpportunityId = :((Opportunity)controller.getRecord()).Id];
        }
        
    }
    
   public pageReference primaryContact() {
     
       PageReference pageRef = Page.OpportunityPrimaryContact;
       pageRef.getParameters().put('Id', oppId);
       pageRef.setRedirect(true);
       
       return pageRef;
   }
    
}



Test Class:

@isTest
public class OpportunityContactRoleController_Test {
    
    private static testMethod void testData(){
        Account testAccount = new Account(Name = 'Test Account', Country__c = 'US');
        insert testAccount;
        
        Contact testContact = new Contact(LastName = 'Test LastName', FirstName = 'Test LastName');
        insert testContact;
        
        Opportunity testOpportunity = new Opportunity(AccountId = testAccount.Id, Name = 'Test Opportunity', Country__c = 'US', 
                                                      CurrencyIsoCode = 'USD', StageName = 'Loan Current', CloseDate = date.today(), Days_In_Term__c = 2 );
        insert testOpportunity;
        
        
        OpportunityContactRoleController controller = new OpportunityContactRoleController(new ApexPages.StandardController(testOpportunity));
        OpportunityContactRole ocr = new OpportunityContactRole();
        
        controller.deleteOppContRole();
 
        controller.primaryContact();
        
        
    }

}
Hi Guys,

good day!

Just a newbie in here, can you assist me with below Apex Class I already made a Test Class and my Problem in the Test Class is the part of method  deleteOppContRole() wherein it doesn't covered any help please ?

public class OpportunityContactRoleController {
    
    public Id contRoleId {get; set;}
    public Id oppId;
    public Opportunity oppObj;
    public ApexPages.StandardController controller {get; set;}
    

    public List<OpportunityContactRole> oppContRoles {get; set;}
    
    public OpportunityContactRoleController(ApexPages.StandardController controller){
        this.oppObj = (Opportunity)controller.getRecord();
        oppId = this.oppObj.Id;
        
        oppContRoles = [SELECT Id,OpportunityId, Contact.Name, Contact.Email, Role, Contact.Account.Name, Contact.Phone, IsPrimary
                            FROM OpportunityContactRole WHERE OpportunityId = :((Opportunity)controller.getRecord()).Id];
        
    }
    
    public void deleteOppContRole(){
        if(contRoleId != null){
        OpportunityContactRole ocr = new OpportunityContactRole();
        ocr.Id = contRoleId;
        delete ocr;
        oppContRoles = new List<OpportunityContactRole>();
        
        oppContRoles = [SELECT Id,OpportunityId, Contact.Name, Contact.Email, Role, Contact.Account.Name, Contact.Phone, IsPrimary
                            FROM OpportunityContactRole WHERE OpportunityId = :((Opportunity)controller.getRecord()).Id];
        }
        
    }
    
   public pageReference primaryContact() {
     
       PageReference pageRef = Page.OpportunityPrimaryContact;
       pageRef.getParameters().put('Id', oppId);
       pageRef.setRedirect(true);
       
       return pageRef;
   }
    
}
Hi folks

please help me, how to I search on textbox via wild card?

ex. is a textbox and I input *h* it should display all wildcards of h, it is needed to use * in textbox for wildcards since in my method below is already a wildcard string query which should be done on textbox instead.

 if(accname != '')
        {
            String strQuery = 'Select Id, FirstName, LastName, '+
                'Account.Name,Account.ShippingCountry,  '+
                'From Contact where Account.Name like \'%'+accname+'%\'';
            
            lstContact =  Database.query(strQuery);
        }