function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
santhosh konathala 26santhosh konathala 26 

Can any one help me below code getting an error like "Ensure that values are preserved during pagination."

Below is my code:-

/**
* @name OrderExtension
* @description This class is provided for you to facilitate the Super Badge
**/
public class OrderExtension {
    
    public Order orderRecord {get;set;}
    public List<OrderItem> orderItemList {get;set;}
    public String selectedFamily {get;set;}
    public List<chartHelper.chartData> pieData {get;set;}
    public Decimal total {get;set;}
    public Map<Id,OrderItem> orderItemMap;
    ApexPages.standardSetController standardSetController;
    public OrderExtension(ApexPages.StandardController standardController){
        orderRecord = (Order)standardController.getRecord();
        orderItemMap = new Map<id,OrderItem>();
        if ( orderRecord.Id != null ){
            orderRecord = queryOrderRecord(orderRecord.Id);
        }
    
        
        resetSsc();
        total = 0;
        for (OrderItem oi : orderRecord.OrderItems) {
            orderItemMap.put(oi.Product2Id, oi);
            if (oi.Quantity > 0) {
                if (null == pieData) {
                    pieData = new List<ChartHelper.ChartData>();
                }
                pieData.add(new chartHelper.ChartData(oi.Product2.Name, oi.Quantity * oi.UnitPrice));
                total += oi.UnitPrice * oi.Quantity;
            }
        }
        PopulateOrderItems();
    }
    void resetSsc() {
        String query = 'SELECT Name, Product2.Family, Product2.Name, Product2Id, UnitPrice, Product2.Quantity_Remaining__c'
            + '  FROM PricebookEntry  WHERE IsActive = TRUE';
        if (selectedFamily != null && selectedFamily != Constants.SELECT_ONE) {
            query += ' AND Product2.Family = \'' + selectedFamily + '\'';
        }
        query += ' ORDER BY Name';
        standardSetController = new ApexPages.standardSetController(Database.getQueryLocator(query));
        standardSetController.setPageSize(Constants.DEFAULT_ROWS);
    }
    //ToDo: Implement your own method to populate orderItemList
    //  that you will call after pagination and/or family selection
    void PopulateOrderItems() {
        orderItemList = new List<OrderItem>();
        for (SObject obj : standardSetController.getRecords()) {
            PricebookEntry pbe = (PricebookEntry)obj;
            
            if (orderItemMap.containsKey(pbe.Product2Id)) {
                orderItemList.add(orderItemMap.get(pbe.Product2Id));
            } else {
                orderItemList.add(new OrderItem(
                    PricebookEntryId=pbe.Id,
                    Product2Id=pbe.Product2Id,
                    UnitPrice=pbe.UnitPrice,
                    Quantity=0,
                    Product2=pbe.Product2
                ));
            }
        }
    }
    /**
* @name OnFieldChange
* @description
**/
    public void OnFieldChange(){
        //ToDo: Implement logic to store the values changed on the page
        for (OrderItem oi : orderItemList) {
            orderItemMap.put(oi.Product2Id, oi);
        }
        //      and populate pieData
        pieData = null;
        total = 0;
        for (OrderItem oi : orderItemMap.values()) {
            if (oi.Quantity > 0) {
                if (null == pieData) {
                    pieData = new List<chartHelper.ChartData>();
                }
                pieData.add(new chartHelper.ChartData(oi.Product2.Name, oi.Quantity * oi.UnitPrice));
                //      and populate total
                total += oi.UnitPrice * oi.Quantity;
            }
        }
    }
    /**
* @name SelectFamily
* @description
**/
    public void SelectFamily(){
        //ToDo: Implement logic to filter based on the selected product family
        resetSsc();
        
        PopulateOrderItems();
        standardSetController = null;
    }
    /**
* @name Save
* @description
**/
    public void Save(){
        //ToDo: Implement logic to save the Order and populated OrderItems
        System.Savepoint sp = Database.setSavepoint();
        try {
            if (null == orderRecord.Pricebook2Id) {
                orderRecord.Pricebook2Id = Constants.STANDARD_PRICEBOOK_ID;
            }
            upsert orderRecord;
            List<OrderItem> orderItemsToUpsert = new List<OrderItem>();
            List<OrderItem> orderItemsToDelete = new List<OrderItem>();
            for (OrderItem oi : orderItemList) {
                if (oi.Quantity > 0) {
                    if (null == oi.OrderId) {
                        oi.OrderId = orderRecord.Id;
                    }
                    orderItemsToUpsert.add(oi);
                } else if (oi.Id != null) {
                    orderItemsToDelete.add(oi);
                }
            }
            upsert orderItemsToUpsert;
            delete orderItemsToDelete;
        } catch (Exception e) {
            Database.rollback(sp);
            apexPages.addMessage(new ApexPages.message(ApexPages.Severity.INFO,Constants.ERROR_MESSAGE));
        }
    }
    /**
* @name First
* @description
**/
    public void First(){
        standardSetController.first();
        PopulateOrderItems();
    }
    /**
* @name Next
* @description
**/
    public void Next(){
        standardSetController.next();
        PopulateOrderItems();
    }
    
    
    /**
* @name Previous
* @description
**/
    public void Previous(){
        standardSetController.previous();
        PopulateOrderItems();
    }
    /**
* @name Last
* @description
**/
    public void Last(){
        standardSetController.last();
        PopulateOrderItems();
    }
    /**
* @name GetHasPrevious
* @description
**/
    public Boolean GetHasPrevious(){
        return standardSetController.getHasPrevious();
    }
    
    /**
* @name GetHasNext
* @description
**/
    public Boolean GetHasNext(){
        return standardSetController.getHasNext();
    }
    
    /**
* @name GetTotalPages
* @description
**/
    public Integer GetTotalPages(){
        return (Integer)Math.ceil(standardSetController.getResultSize() / (Decimal)Constants.DEFAULT_ROWS);
    }
    
    /**
* @name GetPageNumber
* @description
**/
    public Integer GetPageNumber(){
        return standardSetController.getPageNumber();
    }
    
    /**
* @name GetFamilyOptions
* @description
**/
    public List<SelectOption> GetFamilyOptions() {
        List<SelectOption> options = new List<SelectOption>{
            new SelectOption(Constants.SELECT_ONE, Constants.SELECT_ONE)
        };

        for (Schema.PicklistEntry ple : Constants.PRODUCT_FAMILY) {
            options.add(new SelectOption(ple.getValue(), ple.getLabel()));
        }
        return options;
    }
    /**
* @name QueryOrderRecord
* @description
**/
    public static Order QueryOrderRecord(Id orderId){
        return [
            SELECT Id, AccountId, EffectiveDate, Name, Status, Pricebook2Id,
            (
                SELECT Id, OrderId, Quantity, UnitPrice, PricebookEntryId, Product2Id,
                Product2.Name, Product2.Family, Product2.Quantity_Remaining__c
                FROM OrderItems
            )
            FROM Order
            WHERE Id = :orderId
        ];
    }
}
HarshHarsh (Salesforce Developers) 
Hi Santhosh,

Try the code given below.
/**
 * @name OrderExtension
 * @description This class is provided for you to facilitate the Super Badge
**/
public class OrderExtension {

    public Order orderRecord {get;set;}
    public List<OrderItem> orderItemList {get;set;}
    public String selectedFamily {get;set;}
    public List<chartHelper.chartData> pieData {get;set;}
    public Decimal total {get;set;}

    public Map<Id,OrderItem> orderItemMap;
    ApexPages.StandardSetController standardSetController;

    public OrderExtension(ApexPages.StandardController standardController){
        orderRecord = (Order)standardController.getRecord();
        orderItemMap = new Map<id,OrderItem>();
        if ( orderRecord.Id != null ){
            orderRecord = queryOrderRecord(orderRecord.Id);
        }
        loadPaginationData();
        total = 0;
        pieData = new List<chartHelper.chartData>();
        //loop through the order Items for the orderRecord
        for(OrderItem item : orderRecord.OrderItems){
            orderItemMap.put(item.Product2Id,item);
            if(item.Quantity > 0){
                pieData.add(new ChartHelper.chartData(item.Product2.Name,item.Quantity * item.UnitPrice));
                total += item.Quantity * item.UnitPrice;
            }
        }
    }

    public void loadPaginationData(){
        String query = 'SELECT Name, Product2.Family, Product2.Name, Product2Id, UnitPrice, Product2.Quantity_Remaining__c FROM PricebookEntry';
        query += ' ';
        query += 'where IsActive = True';
        if(selectedFamily != null && selectedFamily != Constants.SELECT_ONE){
            query += ' AND Product2.Family=:selectedFamily';
        }
        standardSetController = new ApexPages.StandardSetController(Database.getQueryLocator(query));
        standardSetController.setPageSize(Constants.DEFAULT_ROWS);
        System.debug('standardSetController==='+standardSetController);
    }

    public void loadOrderItemdata(){
        System.debug('loadOrderData=====');
        orderItemList = new List<OrderItem>();
        for(SObject record : standardSetController.getRecords()){
            System.debug('for=====');
            PricebookEntry pbeRecord = (PricebookEntry)record;
            if(orderItemMap.containsKey(pbeRecord.Product2Id)) {
                System.debug('if=====');
                orderItemList.add(orderItemMap.get(pbeRecord.Product2Id));
            } else{
                System.debug('else======');
                OrderItem orderItem = new OrderItem(
                PricebookEntryId = pbeRecord.Id,
                Product2Id = pbeRecord.Product2Id,
                UnitPrice = pbeRecord.UnitPrice,
                Quantity = 0,
                Product2 = pbeRecord.Product2
                );
                orderItemList.add(orderItem);
                orderItemMap.put(pbeRecord.Product2Id,orderItem);
            }
        }
        System.debug('orderItemList===='+orderItemList);
        System.debug('orderItemMap==='+orderItemMap);
    }


    /**
     * @name OnFieldChange
     * @description
    **/
    public void OnFieldChange(){
        pieData = new List<chartHelper.chartData>();
        total = 0;
        for(OrderItem item : orderItemMap.values()){
            pieData.add(new ChartHelper.chartData(item.Product2.Name,item.Quantity * item.UnitPrice));
            total += item.Quantity * item.UnitPrice;
        }
    }

    /**
     * @name SelectFamily
     * @description
    **/
    public void SelectFamily(){
        loadPaginationData();
        loadOrderItemdata();
    }

    /**
     * @name Save
     * @description
    **/
    public void Save(){
        Savepoint sp = Database.setSavepoint();
        List<OrderItem> lOrderItemsToInsert = new List<OrderItem>();
        List<OrderItem> lOrderItemsToDelete = new List<OrderItem>();
        try{
            if(orderRecord.Pricebook2Id == null){
                orderRecord.Pricebook2Id = Constants.STANDARD_PRICEBOOK_ID;
            }
            upsert orderRecord;
            for(OrderItem oItem : orderItemMap.values()){
                System.debug('for=======');
                if(oItem.Quantity > 0 ){
                    oItem.OrderId = orderRecord.Id;
                    lOrderItemsToInsert.add(oItem);
                }else{
                    lOrderItemsToDelete.add(oItem);
                }
            }
            upsert lOrderItemsToInsert;
            delete lOrderItemsToDelete;
        }catch(Exception ex){
            Database.rollback(sp);
            apexPages.addMessage(new ApexPages.message(ApexPages.Severity.Error,Constants.ERROR_MESSAGE));
        }
    }


    /**
     * @name First
     * @description
    **/
    public void First(){
        System.debug('first====');
        standardSetController.first();
        loadOrderItemdata();
    }


    /**
     * @name Next
     * @description
    **/
    public void Next(){
        System.debug('next=====');
        standardSetController.next();
        loadOrderItemdata();
    }


    /**
     * @name Previous
     * @description
    **/
    public void Previous(){
        System.debug('prevopus=====');
        standardSetController.previous();
        loadOrderItemdata();
    }

    /**
     * @name Last
     * @description
    **/
    public void Last(){
        System.debug('last====');
        standardSetController.last();
        loadOrderItemdata();
    }

    /**
     * @name GetHasPrevious
     * @description
    **/
    public Boolean GetHasPrevious(){
        return standardSetController.getHasPrevious();
    }

    /**
     * @name GetHasNext
     * @description
    **/
    public Boolean GetHasNext(){
        return standardSetController.getHasNext();
    }

    /**
     * @name GetTotalPages
     * @description
    **/
    public Integer GetTotalPages(){
        System.debug('total pages==='+standardSetController.getResultSize());
        return (Integer)Math.ceil(standardSetController.getResultSize() / (Decimal)Constants.DEFAULT_ROWS);
    }

    /**
     * @name GetPageNumber
     * @description
    **/
    public Integer GetPageNumber(){
        return standardSetController.getPageNumber();
    }

    /**
     * @name GetFamilyOptions
     * @description
    **/
    public List<SelectOption> GetFamilyOptions(){
        List<SelectOption> productFamilyOptions = new List<SelectOption>();
        productFamilyOptions.add(new SelectOption(Constants.SELECT_ONE ,Constants.SELECT_ONE));
        for(Schema.PicklistEntry picklistEntry : Constants.PRODUCT_FAMILY){
            productFamilyOptions.add(new SelectOption(picklistEntry.getLabel(),picklistEntry.getValue()));
        }
        return productFamilyOptions;
    }

    /**
     * @name QueryOrderRecord
     * @description
    **/
    public static Order QueryOrderRecord(Id orderId){
        return [
            SELECT Id, AccountId, EffectiveDate, Name, Status, Pricebook2Id,
                (
                    SELECT Id, OrderId, Quantity, UnitPrice, PricebookEntryId, Product2Id,
                         Product2.Name, Product2.Family, Product2.Quantity_Remaining__c
                    FROM OrderItems
                )
            FROM Order
            WHERE Id = :orderId
        ];
    }

}
Please mark it as Best Answer if the above information was helpful.

Thanks.
 
santhosh konathala 26santhosh konathala 26
Hi Harsh,
Getting an error while using the above code as "System.NullPointerException: Attempt to de-reference a null object"
HarshHarsh (Salesforce Developers) 
Hi Santhosh,

Try the code given below.
/**
 * @name OrderExtension
 * @description This class is provided for you to facilitate the Super Badge
 **/
public without sharing class OrderExtension {

    public Order orderRecord {get; set;}
    public List<OrderItem> orderItemList {get; set;}
    public String selectedFamily {get; set;}
    public List<chartHelper.chartData> pieData {get; set;}
    public Decimal total {get; set;}
    public Integer defaultRowsInTable {
        get {
            return Constants.DEFAULT_ROWS;
        }
    }

    public Map<Id,OrderItem> orderItemMap;
    ApexPages.StandardSetController standardSetController;

    public OrderExtension(ApexPages.StandardController standardController){
        orderRecord = (Order)standardController.getRecord();
        orderItemMap = new Map<Id, OrderItem>();
        if( orderRecord.Id != null ) {
            orderRecord = queryOrderRecord(orderRecord.Id);
        }

        refreshStandardSetController();
        total = 0;

        for (OrderItem oi : orderRecord.OrderItems) {
            orderItemMap.put(oi.PricebookEntryId, oi);
            if(oi.Quantity > 0) {
                if(null == pieData) {
                    pieData = new List<ChartHelper.ChartData>();
                }
                pieData.add(new chartHelper.ChartData(oi.Product2.Name, oi.Quantity * oi.UnitPrice));
                total += oi.UnitPrice * oi.Quantity;
            }
        }


        loadData();
    }

    void refreshStandardSetController(){
        String query = 'SELECT Name, Product2.Family, Product2.Name, Product2Id, UnitPrice, Product2.Quantity_Remaining__c FROM PricebookEntry WHERE IsActive = TRUE';

        if(selectedFamily != null && selectedFamily != Constants.SELECT_ONE) {
            query += ' AND Product2.Family = \'' + selectedFamily + '\'';
        }
        query += ' ORDER BY Name';

        standardSetController = new ApexPages.StandardSetController(Database.getQueryLocator(query));
        standardSetController.setPageSize(Constants.DEFAULT_ROWS);
    }

    void loadData(){
        orderItemList = new List<OrderItem>();
        for (SObject obj : standardSetController.getRecords()) {
            PricebookEntry pbe = (PricebookEntry)obj;

            if(orderItemMap.containsKey(pbe.Id)) {
                orderItemList.add(orderItemMap.get(pbe.Id));
            } else{
                OrderItem ot = new OrderItem(
                        PricebookEntryId = pbe.Id,
                        Product2Id = pbe.Product2Id,
                        UnitPrice = pbe.UnitPrice,
                        Quantity = 0,
                        Product2 = pbe.Product2
                );
                orderItemList.add(ot);
                orderItemMap.put(pbe.Id, ot);
            }
        }
        OnFieldChange();
    }


    /**
     * @name OnFieldChange
     * @description
     **/
    public void OnFieldChange(){
        for (OrderItem oi : orderItemList) {
            orderItemMap.put(oi.PricebookEntryId, oi);
        }

        pieData = null;
        total = 0;
        for (OrderItem oi : orderItemMap.values()) {
            if(oi.Quantity > 0) {
                if(null == pieData) {
                    pieData = new List<chartHelper.ChartData>();
                }
                pieData.add(new chartHelper.ChartData(oi.Product2.Name, oi.Quantity * oi.UnitPrice));
                //      and populate total
                total += oi.UnitPrice * oi.Quantity;
            }

        }

    }

    /**
     * @name SelectFamily
     * @description
     **/
    public void SelectFamily(){
        refreshStandardSetController();
        loadData();
    }

    /**
     * @name Save
     * @description
     **/
    public void Save(){
        System.Savepoint sp = Database.setSavepoint();

        try {
            if(orderRecord.Pricebook2Id == null) {
                orderRecord.Pricebook2Id = Constants.STANDARD_PRICEBOOK_ID;
            }
            upsert orderRecord;

            List<OrderItem> orderItemsToUpsert = new List<OrderItem>();
            List<OrderItem> orderItemsToDelete = new List<OrderItem>();

            for (OrderItem oi : orderItemMap.values()) {
                if(oi.Quantity > 0) {
                    if(oi.OrderId == null) {
                        oi.OrderId = orderRecord.Id;
                    }
                    orderItemsToUpsert.add(oi);
                } else if(oi.Id != null) {
                    orderItemsToDelete.add(new OrderItem(id=oi.Id));
                    oi.Id = null;
                }
            }

            upsert orderItemsToUpsert;
            delete orderItemsToDelete;
        } catch (Exception e){
            Database.rollback(sp);
            apexPages.addMessage(new ApexPages.message(ApexPages.Severity.INFO,Constants.ERROR_MESSAGE));
        }
    }

    /**
     * @name First
     * @description
     **/
    public void First(){
        standardSetController.first();
        loadData();
    }

    /**
     * @name Next
     * @description
     **/
    public void Next(){
        standardSetController.next();
        loadData();
    }

    /**
     * @name Previous
     * @description
     **/
    public void Previous(){
        standardSetController.previous();
        loadData();
    }

    /**
     * @name Last
     * @description
     **/
    public void Last(){
        standardSetController.last();
        loadData();
    }

    /**
     * @name GetHasPrevious
     * @description
     **/
    public Boolean GetHasPrevious(){
        return standardSetController.getHasPrevious();
    }

    /**
     * @name GetHasNext
     * @description
     **/
    public Boolean GetHasNext(){
        return standardSetController.getHasNext();
    }

    /**
     * @name GetTotalPages
     * @description
     **/
    public Integer GetTotalPages(){
        return (Integer)Math.ceil(standardSetController.getResultSize() / (Decimal)Constants.DEFAULT_ROWS);
    }

    /**
     * @name GetPageNumber
     * @description
     **/
    public Integer GetPageNumber(){
        return standardSetController.getPageNumber();
    }

    /**
     * @name GetFamilyOptions
     * @description
     **/

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

    /**
     * @name QueryOrderRecord
     * @description
     **/
    public static Order QueryOrderRecord(Id orderId){
        return [SELECT Id, AccountId, EffectiveDate, Name, Status, Pricebook2Id,(SELECT Id, OrderId, Quantity, UnitPrice, PricebookEntryId, Product2Id, Product2.Name, Product2.Family, Product2.Quantity_Remaining__c FROM OrderItems) FROM Order WHERE Id = : orderId];
    }

}

Please mark it as Best Answer if the above information was helpful.

Thanks.
santhosh konathala 26santhosh konathala 26
Hi Harsh,
Now Facing this error "Ensure that you implement all the pagination methods using the corresponding StandardSetController methods." when i using the above code.