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

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

can you help me on how or where could I possibly invoke that when a profile is Sales it will not display the field Lead Source, while if the Profile is Manager it display the field Lead Source without affecting the order of the field.. 
public  class OpportunityCustomCloningController {

    public Id oppId {get; set;}
    public Id recordTypeId {get; set;}
    public Opportunity opp {get;set;}
    public String cloneOption {get;set;}
    public String pageLayoutFields {get; set;}
    public List<String> addFields {get; set;}
    public List<LayoutComponent__c> sectionComponent {get;set;}
    public Map<Id, List<LayoutComponent__c>> fieldComponent {get; set;}
    
    public string OPPORTUNITY_STRING = 'Opportunity';
    public string MAINTENANCE_PRODUCT_STRING = 'mpo';
    public string WITH_PRODUCT_STRING = 'wip';
    public string WITHOUT_PRODUCT_STRING = 'wop';
    public string CLONE_OPTION_STRING = 'clo';
    public string ID_STRING = 'id';
    
    public static Boolean isCloned = false;
    
    private transient Map<String,Schema.DescribeFieldResult> fieldDescribe;
    private Integer dependentCount = 0;
    
    public ApexPages.StandardController controller {get; set;}

    public OpportunityCustomCloningController(ApexPages.StandardController controller){
        this.controller = controller;
        
        if(!Test.isRunningTest() && addFields != null) {
            controller.addFields(addFields);
        }
        
        oppId = controller.getId();
        opp = (Opportunity) controller.getRecord();
        recordTypeId = opp.RecordTypeID;
        
        cloneOption = apexpages.currentpage().getparameters().get(CLONE_OPTION_STRING);
        
        getMetadata();
        
        //getPageLayout();
        
        
        
    }
    
    private void getMetadata(){
        Map<String,Schema.SObjectField> fieldMap = Schema.sObjectType.Opportunity.fields.getMap();
        fieldDescribe = new Map<String,Schema.DescribeFieldResult>();
        
        for(String fieldName : fieldMap.keyset()){
            fieldDescribe.put(fieldName.toLowerCase(),fieldMap.get(fieldName).getDescribe());
        }
    }

    public PageReference customClone() {
       
        //String urlRecordType = pageRecordType();
        String urlRecordType = 'OpportunityCustomCloneEdit';
        PageReference editCloneOpportunityPage = new PageReference('/apex/'+urlRecordType);
        editCloneOpportunityPage.getParameters().put(ID_STRING , opp.Id);
        editCloneOpportunityPage.getParameters().put(CLONE_OPTION_STRING , cloneOption); 
        editCloneOpportunityPage.setRedirect(true);
        
        
        return editCloneOpportunityPage; 
    }
    
    public Map<String, SObjectField> getObjectFields(String objectName) {
        SObjectType objToken = Schema.getGlobalDescribe().get(objectName); 
        DescribeSObjectResult objDef = objToken.getDescribe();
        Map<String, SObjectField> fields = objDef.fields.getMap();
        
        return fields;
    }
    
    public void getCloneSettings() {
        Map<String, Opportunity_Fields__c> allOpportunityFields = Opportunity_Fields__c.getAll();
        List<Opportunity_Fields__c> opportunityFields = allOpportunityFields.values();
        
        Map<String, SObjectField> fields = getObjectFields(OPPORTUNITY_STRING);
        if(fieldDescribe == null){
            getMetadata();
        }
        for(Opportunity_Fields__c ofs : opportunityFields){
            System.debug('* ** ** ' + ofs.API_Name__c + ' ' + ofs.To_Be_Cloned__c);
            if(ofs.To_Be_Cloned__c == null || !ofs.To_Be_Cloned__c){ 
                //SObjectField f = fields.get(ofs.API_Name__c);
                
                if(fieldDescribe.containsKey(ofs.API_Name__c)){
                DescribeFieldResult fr = fieldDescribe.get(ofs.API_Name__c.toLowerCase());
                //f.getDescribe();
                System.debug('* ** *** fr ' + fr);
                if(fr.isUpdateable() && fr.isAccessible()){
                    opp.put(ofs.API_Name__c, NULL);
                }
                }else{
                    try{
                        opp.put(ofs.API_Name__c, NULL);
                    }catch(Exception e){}
                }
            }
        }
        System.debug('* ** *** opp ' + opp);
    }
    
    
    public PageReference customSaveAndAddProduct(){
        opp.Id = NULL; 
        opp.OwnerId = UserInfo.getUserId();
        
        boolean hasError = false;
        try{
            //checks if the opportunity has already been cloned once during the transaction.
            if(!isCloned) {
                insert opp;
                isCloned = true;
                sendSuccessMessage(opp.Id);
            }
        }catch(Exception e){
            hasError = true;
            isCloned = false;
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL, e.getMessage()));
            sendErrorEmail(e.getMessage());
            
        }
        
        if(hasError){
            return null;
        }else{        
            PageReference opportunityProductSelect = new PageReference('/apex/OpportunityProductSelection');
            opportunityProductSelect.getParameters().put(ID_STRING , opp.Id);
                    
            return opportunityProductSelect;
        }
    }
    
    public PageReference customSave() {
        List<OpportunityLineItem> oppProdList = new List<OpportunityLineItem>();
                
        if(cloneOption == WITH_PRODUCT_STRING || cloneOption == MAINTENANCE_PRODUCT_STRING){
            Map<String, SObjectField> oltFields = getObjectFields('OpportunityLineItem');
            String selectFields = '';
            String dbQuery = '';
            
            for (Schema.SObjectField ft : oltFields.values()){
               Schema.DescribeFieldResult fd = ft.getDescribe();
               if(fd.isCreateable()){
                   if(selectFields == '') {
                       selectFields = fd.getName();
                   } else {
                       selectFields = selectFields + ', ' + fd.getName();
                   }
               }
            }
            
            dbQuery = 'SELECT ' + selectFields + ' FROM OpportunityLineItem WHERE OpportunityId = \'' +opp.Id+ '\' AND Product2.isActive = true';
            
            if(cloneOption == MAINTENANCE_PRODUCT_STRING) { 
                dbQuery = dbquery + ' AND Product2.Family = \'Maintenance\'';
            }
            
            List<OpportunityLineItem> opportunityProducts = Database.query(dbQuery);
            for(OpportunityLineItem op : opportunityProducts){
                oppProdList.add(op.clone(false,true));
            }
        }
        
        opp.Id = NULL;
        opp.OwnerId = UserInfo.getUserId();
        
        boolean hasError = false;
        try{
            //checks if the opportunity has already been cloned once during the transaction.
            if(!isCloned) {
                insert opp;
            }
        }catch(Exception e){
            hasError = true;
            isCloned = false;
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL, e.getMessage()));
            sendErrorEmail(e.getMessage());
        }
        
        if(!hasError && !isCloned){
            if(!oppProdList.isEmpty()){
                for(OpportunityLineItem olt : oppProdList) {
                    olt.OpportunityID = opp.Id;
                    if(olt.UnitPrice != NULL && olt.TotalPrice != NULL) { 
                       olt.UnitPrice = NULL;
                    }
                }
                try{
            
                    insert oppProdList;
                    isCloned = true;
                    sendSuccessMessage(opp.Id);
                }catch(Exception e){
                    hasError = true;
                    isCloned = false;
                    ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL, e.getMessage()));
                    sendErrorEmail(e.getMessage());
                }
            }
        }
        
        if(hasError){
            return null;
        }else{
            return new PageReference('/'+opp.id);
        }
    }
    
    public static Boolean runningInASandbox() {
      return [SELECT Id, IsSandbox FROM Organization LIMIT 1].IsSandbox;
    }
       
    
    public Boolean getShowSaveAndAddProducts(){
        if(cloneOption == WITHOUT_PRODUCT_STRING){
            return true;
        } else return false;
    }
    
    public Boolean getShowSaveButton(){
        if(cloneOption == WITHOUT_PRODUCT_STRING){
            return false;
        } else return true;
    }
    public Component.Apex.PageBlock dynBlock;
    
    public Component.Apex.PageBlock getDynamicBlock(){
        if(dynBlock != null){
            return dynBlock;
        }
        Component.Apex.PageBlock dynBlock = new Component.Apex.PageBlock();
        dynBlock.mode = 'edit';
        dynBlock.id = 'mainBlock';
        dynBlock.title = 'Opportunity Clone';
        
        Component.Apex.PageBlockButtons buttons = new Component.Apex.PageBlockButtons();
        
        if(getShowSaveButton()){ 
            Component.Apex.CommandButton saveButton = new Component.Apex.CommandButton();
            saveButton.value = 'Save';
            saveButton.Id = 'saveButton';
            saveButton.onclick = 'saveButtonBehavior(true);';
            saveButton.oncomplete = 'saveButtonBehavior(false);';
            saveButton.expressions.action = '{!customSave}';
            saveButton.rerender = new Set<String>{'msgs'};
            buttons.childComponents.add(saveButton);
        }
            
        if(getShowSaveAndAddProducts()){
            Component.Apex.CommandButton saveAddButton = new Component.Apex.CommandButton();
            saveAddButton.value = 'Save & Add Product';
            saveAddButton.Id = 'saveAddButton';
            saveAddButton.onclick = 'saveButtonBehavior(true);';
            saveAddButton.oncomplete = 'saveButtonBehavior(false);';
            saveAddButton.expressions.action = '{!customSaveAndAddProduct}';
            saveAddButton.rerender = new Set<String>{'msgs'};
            buttons.childComponents.add(saveAddButton);
        }
        
        Component.Apex.CommandButton cancelButton = new Component.Apex.CommandButton();
        cancelButton.value = 'Cancel';
        cancelButton.Id = 'cancelButton';
        cancelButton.expressions.action = '{!cancel}';
        buttons.childComponents.add(cancelButton);
        buttons.Id = 'pageBlockButtons';
                
        dynBlock.childComponents.add(buttons);
        
        
        List<LayoutComponent__c> layoutComponentList= new List<LayoutComponent__c>();
        sectionComponent = new List<LayoutComponent__c>();
        fieldComponent = new Map<Id, List<LayoutComponent__c>>();
        pageLayoutFields = '';
        List<String> fieldNames = new List<String>();
        Id profileId = UserInfo.getProfileId();
        
        List<LayoutMapping__c > layoutMapList = [SELECT Layout__c FROM LayoutMapping__c 
            WHERE SObjectType__c = :OPPORTUNITY_STRING AND RecordTypeId__c = :recordTypeId 
            AND ProfileId__c = :profileId
            ORDER BY CreatedDate DESC LIMIT 1];
        
        if(layoutMapList.isEmpty()){    
            layoutMapList  = [SELECT Layout__c FROM LayoutMapping__c  
                WHERE SObjectType__c = :OPPORTUNITY_STRING AND IsDefault__c = true
                AND ProfileId__c = :profileId
                ORDER BY CreatedDate DESC LIMIT 1];
            if(layoutMapList.isEmpty()){    
                layoutMapList  = [SELECT Layout__c FROM LayoutMapping__c  
                    WHERE SObjectType__c = :OPPORTUNITY_STRING AND IsDefault__c = true
                    ORDER BY CreatedDate DESC LIMIT 1];
            }
        }
        
        if(!layoutMapList.isEmpty()){
            
            getMetadata();
            
            Component.Apex.PageBlockSection debugSection = new Component.Apex.PageBlockSection(title='Debug');
            for(String fieldName : fieldDescribe.keyset()){
                //debugSection.childComponents.add(new Component.Apex.OutputText(value = '"'+fieldName+'"'));
            }
            //dynBlock.childComponents.add(debugSection);
            
            Id layoutId = layoutMapList.get(0).Layout__c;
            
            List<Id> sectionIds = new List<Id>();
            Map<Id,Component.Apex.PageBlockSection> componentMap = new Map<Id,Component.Apex.PageBlockSection>();
            
            
            for(LayoutComponent__c lc : [
             SELECT   ID, Name, Columns__c, IsRequired__c, IsBlank__c, IsField__c, IsSection__c,
                      Order__c, ParentComponent__c, FieldName__c,SectionName__c 
            FROM LayoutComponent__c 
            WHERE Layout__c = :layoutId AND IsSection__c = true
            ORDER BY Order__c
            ]){
                System.debug('* ** *** component ' + lc);
                if(lc.IsSection__c) {
                    Component.Apex.PageBlockSection sectionComponent = new Component.Apex.PageBlockSection();
                    sectionComponent.title = lc.SectionName__c; // + ' ' + lc.Id + ' ' + lc.Name;                    
                    sectionIds.add(lc.Id);
                    componentMap.put(lc.Id,sectionComponent);
                    
                    System.debug('* ** *** adding section ' + lc.SectionName__c);
                    
                    
                } 
                 
            }//end-for
            
            for(LayoutComponent__c lc : [
             SELECT   ID, Name, Columns__c, IsRequired__c, IsBlank__c, IsField__c, IsSection__c, IsEditable__c,
                      Order__c, ParentComponent__c, FieldName__c,SectionName__c 
            FROM LayoutComponent__c 
            WHERE Layout__c = :layoutId AND (IsField__c = true OR IsBlank__c = true)
            ORDER BY Order__c
            ]){
                
                
                if(lc.IsField__c && !String.isBlank(lc.FieldName__c)  && 
                    fieldDescribe.containsKey(lc.FieldName__c.toLowerCase()) &&
                    componentMap.containsKey(lc.ParentComponent__c) 
                ){
                    boolean isDependent = fieldDescribe.get(lc.FieldName__c.toLowerCase()).isDependentPicklist();
                    if(isDependent){ 
                        dependentCount++;
                    }
                
                //debugSection.childComponents.add(new Component.Apex.OutputText(value = '{!opp.' + lc.FieldName__c + '}'));
                    
                    if(lc.IsEditable__c && (!isDependent || dependentCount <= 10) ){
                        Component.Apex.InputField fieldComponent = new Component.Apex.InputField();
                        if(lc.IsRequired__c) { 
                            fieldComponent = new Component.Apex.InputField(required = true);
                        }
                        fieldComponent.expressions.value = '{!opp.' + lc.FieldName__c + '}';
                        componentMap.get(lc.ParentComponent__c).childComponents.add(fieldComponent);
                    }else{
                        Component.Apex.OutputField fieldComponent = new Component.Apex.OutputField();
                        fieldComponent.expressions.value = '{!opp.' + lc.FieldName__c + '}';
                        componentMap.get(lc.ParentComponent__c).childComponents.add(fieldComponent);
                        
                    }
                    
                    /*Component.Apex.OutputText textComponent = new Component.Apex.OutputText();
                    textComponent.value = lc.Order__c + ': ' + lc.FieldName__c;
                    componentMap.get(lc.ParentComponent__c).childComponents.add(textComponent);*/
                    
                    System.debug('* ** *** adding field ' + lc.FieldName__c);
                    
                    fieldNames.add(lc.FieldName__c);
                }else if(lc.IsBlank__c){
                    Component.Apex.PageBlockSectionItem blankComponent = new Component.Apex.PageBlockSectionItem();
                    componentMap.get(lc.ParentComponent__c).childComponents.add(blankComponent);
                }
                 
            }//end-for
            
            for(Id sectionId : sectionIds){
                dynBlock.childComponents.add(componentMap.get(sectionId));
            }
            
            if(!fieldNames.isEmpty()){
                for(String fieldName : fieldNames){
                    if(pageLayoutFields == '') {
                        pageLayoutFields = fieldName;
                    } else {
                        pageLayoutFields += ', ' + fieldName;
                    }
                }
                
                opp = Database.query('SELECT ' + pageLayoutFields + ' FROM Opportunity WHERE Id = \'' + oppId + '\' LIMIT 1');
                getCloneSettings();
                opp.OwnerId = UserInfo.getUserId();
            }
        }
        return dynBlock;
    }
    

}
Thank you!
 
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);}
    }
How to update a field automatically(OPA_Lifetime_Product_Forecast__c) recalculate when a primary is changed. meaning if values from product_is_primary__c  is changed value, it will recalculate the OPA_Lifetime_Product_Forecast__c
public with sharing class AgreementTriggerHandler{
    
    public static void onAfterInsert(List<APAgreement__c> agrList) {
        isUpdatePanel(agrList);
    }
    
    public static void onAfterUpdate(List<APAgreement__c> agrList) {
        isUpdatePanel(agrList);
    }
    
    public static void onAfterDelete(List<AP_Agreement__c> agrList) {
        isUpdatePanel(agrList);
    }

     public static void onBeforeInsert(List<APAgreement__c> agrList) {
        isUpdatePanel(agrList);
    }



    public static void isUpdatePanel (List<AP_Agreement__c> agrList){
        Set<Id> ProjIDs = new Set<Id>();
        List<Project__c> PaneltoUpdate = new List<Project__c>();
        Double pfSum = 0;

         //Get the Project ID
        for(AP_Agreement__c pfs : agrList){
            ProjIDs.add(pfs.Panel__c);
        }
        
        //Checks if there are Projects on the Agreement
        if(!ProjIDs.isEmpty()){
        
            //Loop through Agreement and use the Product Forecast Condition(OPA_Lifetime_Product_Forecast__c) to filter the Primary and Seconadry Series and Panel/Project ID
            for(AP_Agreement__c  pf: [SELECT OPA_Lifetime_Product_Forecast__c, Panel__c  FROM AP_Agreement__c WHERE Panel__c =: ProjIDs]){
                
                //Check if OPA_Lifetime_Product_Forecast__c has a value as MPA records will not have any value here
                if(pf.OPA_Lifetime_Product_Forecast__c!=null){
                pfSum += pf.OPA_Lifetime_Product_Forecast__c;
                }
            }
        
        }


        
         //Update the Project with the summed up quantity from Agreements using the Product Forecast Condtion
        for(Project__c prj: [Select Id from Project__c where Id =: ProjIDs]){
            prj.Allocated_OEM_Project_Forecast__c = pfSum;
            PaneltoUpdate.add(prj);
        }

        //Update the Project
         if(!PaneltoUpdate.isEmpty()){
            update PaneltoUpdate;
        }
    }
}

 
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,

I have this Trigger wherein it sums up what is in the product forecast and puts it into Project in the field ex. Sum of Product Forecasted, but unfortunately it doesn't appear, my problem is that how can i move from agreement going to project so I can populate the field

    public static void PFSumOEM (List<APTS_Product_Forecast__c> newProductForecast){
        
        Set<ID> pdIds = new Set<ID>();
        List<Project__c> OEMToUpdate = new List<Project__c>();
        Double pfSum;
        
        for(APTS_Product_Forecast__c pf: newProductForecast){
            pdIds.add(pf.APTS_Price_Agreement__c);
        }

         for(APTS_Product_Forecast__c pf : [SELECT APTS_Quantity__c , Panel__c FROM APTS_Product_Forecast__c WHERE isDeleted = false AND panel__c != null AND apts_price_agreement__r.id = null AND product_is_primary__c = TRUE and Panel__c =: pdIds]){
            System.debug('pf value = ' + pf);
            pfSum +=pf.APTS_Quantity__c;
        }
        
        for(Project__c prj: [Select Id from Project__c where ID =: pdIds]){
            prj.Tier1_Project_Forecast__c = pfSum;
            OEMToUpdate.add(prj);
        }
        
        //Update the Project
        if(!OEMToUpdate.isEmpty()){
            update OEMToUpdate;
        }
    }
    
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 i'm new with salesforce, do you have any idea on how can I hide this page table? meaning, onload, no records found, but after clicking the button search, it will display the pagetable result, my problem is it still displays the columns headers onload meaning still without any idea.

<apex:pageBlock title="Final Records">
    <apex:outputPanel layout="block" styleClass="noRecords" rendered="{!conlist.size == 0}"><i> No Records </i>
                </apex:outputPanel>
                <apex:outputPanel layout="block" styleClass="noRecords" rendered="{!conlist.size == NULL}"><i> No  Record </i>
                </apex:outputPanel>
                <apex:pageblocktable value="{!conlist}" var="con" id="pv">
                    <apex:column headerValue="Account Name>  
                        <apex:outputlink value="https://ap1.salesforce.com/{!conlist.Account.id}">{!conlist.Account.Name}</apex:outputlink>  
                    </apex:column>
                    <apex:column headerValue="Country}" value="{!conlist.Account.BillingCountry}" />
                        <apex:outputlink value="https://ap1.salesforce.com/{!conlist.id}"{!conlist.FirstName}</apex:outputlink>  
                    </apex:column>
                </apex:pageblocktable>
Pagination

hi folks, how to create this pagination?
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);
        }
hope you can help me, how can I display in a table a both the account and contacts fields in VF Page?

Regards

Currently I have this in a method since I call this in button

if(accname !=  ' ')
        {
            string srcqry = 'SELECT Name,BillingCountry,(Select Id, FirstName, LastName From Contacts) FROM Account where name like \'%'+accname+'%\'';
            acc= Database.query(searchquery);
        }
          
how to display the the contacts together with accountname with billingcountry in VF Page without contacts not using repeating instead 1 account = 1contact per display in row, meaninf if there are many contacts in a single account it will display 1 unique account = 1 associated contacts.


Something like this, apologies, still in the stage of learning

AccountName        BillingCountry     ContactName
Unique  1                    US                  John Trevor
Unique  1                    Spain               Paul Blake
Unique  1                   India                  Peter Pan
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);
        }