-1

chartHelper run as system but still getting error. I have tried all possible ways but no luck. Can someone please help.

Challenge Not yet complete... here's what's wrong: Ensure that the methods in the chartHelper class run as the system.

ChartHelper.apxc

public class ChartHelper {

    @AuraEnabled// Make sure annotation should be pplied for this method 
    public static List<chartData> GetInventory()
    {

        List<chartData> cht = new List<chartData>();

        for(AggregateResult ar : [SELECT Family family, Sum(Quantity_Remaining__c) total 
                                  FROM Product2
                                  WHERE Quantity_Remaining__c > 0 GROUP BY Family]){
                                      cht.add(new chartData((String)ar.get('family'), Integer.valueOf(ar.get('total'))));
                                  }
        return cht;
    }

    public class ChartData {
        public String name {get;set;}
        public Decimal val {get;set;}

        public ChartData(String name, Decimal val){
            this.name = name;
            this.val = val;
        }
    }

}

Product2Extension​.apxc

public class Product2Extension {

    public List<ProductWrapper> productsToInsert {get;set;}

    public Product2Extension(ApexPages.StandardController controller){
        productsToInsert = new List<ProductWrapper>();
        addRows();
    }

    public List<SelectOption> GetFamilyOptions() {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption(Constants.SELECT_ONE, Constants.SELECT_ONE));
        for(PickListEntry eachPicklistValue : Constants.PRODUCT_FAMILY) {
            options.add(new SelectOption(eachPicklistValue.getValue(), eachPicklistValue.getLabel()));
        }
            return options;
    }

    public void AddRows(){
        for (Integer i=0; i<Constants.DEFAULT_ROWS; i++ ){
            productsToInsert.add(new ProductWrapper());
        }
    }

    public List<ChartHelper.ChartData> GetInventory(){
        return ChartHelper.GetInventory();
    }

    public PageReference Save(){
        SavePoint sp = Database.setSavepoint();
        Integer insertedCount = 0;
        try {
            List<Product2> newProducts = new List<Product2>();
            List<PriceBookEntry> pbeList = new List<PriceBookEntry>();
            List<ProductWrapper> filteredProductWrappers = new List<ProductWrapper>();
            for(ProductWrapper eachPW : productsToInsert) {
                if(!String.isBlank(eachPW.productRecord.Name) && !String.isBlank(eachPW.productRecord.Family) && 
                   eachPW.productRecord.Family!=Constants.SELECT_ONE && eachPW.productRecord.isActive &&
                   eachPW.pricebookEntryRecord.UnitPrice!=null && eachPW.productRecord.Initial_Inventory__c!=null && 
                   eachPW.productRecord.Initial_Inventory__c!=0 && eachPW.pricebookEntryRecord.UnitPrice!=0) {
                       filteredProductWrappers.add(eachPW);
                   }                
            }
            for(ProductWrapper eachPW : filteredProductWrappers) {
                newProducts.add(eachPW.productRecord);
            }
            Database.SaveResult[] productSaveResults = Database.insert(newProducts, false);
            for(Integer i=0; i<productSaveResults.size(); i++) {
                if(productSaveResults[i].isSuccess()) {
                    PriceBookEntry pbe = filteredProductWrappers[i].pricebookEntryRecord;
                    pbe.Product2Id = productSaveResults[i].getId();
                    pbe.IsActive = true;
                    pbe.Pricebook2Id = Constants.STANDARD_PRICEBOOK_ID;
                    pbeList.add(pbe);
                    insertedCount++;
                }
            }
            Database.SaveResult[] pbeSaveResults = Database.insert(pbeList, false);

            //If successful clear the list and display an informational message
            apexPages.addMessage(new ApexPages.message(ApexPages.Severity.INFO,insertedCount + ' Inserted'));
            productsToInsert.clear();   //Do not remove
            addRows();  //Do not remove
        } 
        catch (Exception e){
            System.debug('Exception occured:'+e.getMessage());
            Database.rollback(sp);
            apexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR, Constants.ERROR_MESSAGE));            
        }
        return null;
    }

    public class ProductWrapper {
        public Product2 productRecord {get;set;}
        public PriceBookEntry pricebookEntryRecord {get;set;}

        public ProductWrapper() {
            productRecord = new Product2();
            pricebookEntryRecord = new PricebookEntry();
        }
    }
}

Product2New.vfp

<apex:page standardcontroller="Product2" extensions="Product2Extension">
    <apex:sectionHeader title="New Product" subtitle="Add Inventory" />
    <apex:pageMessages id="pageMessages" />
    <apex:form id="form" >
        <apex:actionRegion >
            <apex:pageBlock title="Existing Inventory" id="existingInv">
                <apex:chart data="{!Inventory}" width="600" height="400">
                    <apex:axis type="Category" fields="name" position="left" title="Product Family"/>
                    <apex:axis type="Numeric" fields="val" position="bottom" title="Quantity Remaining"/>
                    <apex:barSeries axis="bottom" orientation="horizontal" xField="val" yField="name"/>
                 </apex:chart>                
            </apex:pageBlock>
            <apex:pageBlock title="New Products" >
                <apex:pageBlockButtons location="top">
                    <apex:commandButton action="{!save}" value="Save" reRender="existingInv, orderItemTable, pageMessages"/>
                </apex:pageBlockButtons>
                <apex:pageBlockButtons location="bottom">
                    <apex:commandButton action="{!addRows}" value="Add" reRender="orderItemTable, pageMessages" />
                </apex:pageBlockButtons>

                <apex:pageBlockTable value="{!productsToInsert}" var="p" id="orderItemTable" >
                    <apex:column headerValue="{!$ObjectType.Product2.Fields.Name.Label}" >
                        <apex:inputText value="{!p.productRecord.Name}" />
                    </apex:column>
                    <apex:column headerValue="{!$ObjectType.Product2.Fields.Family.Label}" >
                        <apex:selectList value="{!p.productRecord.Family}" size="1" multiselect="false">
                            <apex:selectOptions value="{!FamilyOptions}"></apex:selectOptions>
                        </apex:selectList>
                    </apex:column>
                    <apex:column headerValue="{!$ObjectType.Product2.Fields.IsActive.Label}" >
                        <apex:inputField value="{!p.productRecord.isActive}" />
                    </apex:column>
                    <apex:column headerValue="{!$ObjectType.PricebookEntry.Fields.UnitPrice.Label}" >
                        <apex:inputText value="{!p.pricebookEntryRecord.UnitPrice}" />
                    </apex:column>
                    <apex:column headerValue="{!$ObjectType.Product2.Fields.Initial_Inventory__c.Label}" >
                        <apex:inputField value="{!p.productRecord.Initial_Inventory__c}" />
                    </apex:column>
                </apex:pageBlockTable>
            </apex:pageBlock>
        </apex:actionRegion>
    </apex:form>
</apex:page>
  • 1
    You should always explicitly declare a sharing model. Trailhead may be looking for the explicit keyword without sharing. – David Reed Jun 11 '18 at 3:36
  • Thanks David Reed. I just included without sharing and It worked perfectly. I was assuming if we do not explicitly declare a sharing then class doesn’t enforce sharing rules except if it acquires sharing rules from another class. – Sfdc_1184 Jun 11 '18 at 3:46
  • That's correct, but Trailhead's validation checker really likes you to be explicit. I'll post an answer. – David Reed Jun 11 '18 at 3:47
  • You are right. I tried all other way but this didn't clicked to me :) Thank you for quick response. – Sfdc_1184 Jun 11 '18 at 3:51
4

Trailhead's message about "system mode" is a clue here: the validation checker is looking for you to explicitly declare the sharing model, which is best practice anyway.

You need to add the without sharing keyword to the class declaration so it always runs in system mode, regardless of calling context.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.