0

I am deleting rows based on checkbox click.But when i select a checkbox and click delete , i am displayed this error " DML statement found null SObject at position 0 Error is in expression '{!del}' in component in page forecastbywarehouse: Class.ForecastByWarehouseController.del: line 269, column 1"

Could you please help me in this.

VF page

<apex:page controller="ForecastByWarehouseController" title="Forecast By Warehouse">

    <script>
        var elementFocus = null;
        function retainFocus()
        {
            document.getElementById(elementFocus.name).focus();
        }

        function JS_QtyChanged(ele)
        {
            console.log(ele);
            console.log(ele.parentNode.parentNode.childNodes);
            var sum = 0;
            var i;
            var nodes=ele.parentNode.parentNode.childNodes;
            for(i in ele.parentNode.parentNode.childNodes)
            {
                console.log(nodes[i].className);
                if(nodes[i].className == "quantityTableCell"){
                    var className = nodes[i].childNodes[0].className;
                    if((className=="quantityCellRed" || className=="quantityCell"))
                    {
                        var val = nodes[i].childNodes[0].value;
                        console.log(val);
                        if(!isNaN(val) && val !='undefined' && val != null && val != '')
                        {
                            //alert(val);
                            sum += parseFloat(val);
                        }

                    }                   
                }


                if(nodes[i].className == "quantityTotalCell"){
                    oldvalue = parseInt(nodes[i].innerHTML);
                    if(oldvalue != sum){
                        ele.className = "quantityCellRed";
                    }
                    var n = sum.toFixed(2);
                    nodes[i].innerHTML = n;
                }
            }
            //call_qtyChanged();
        }
    </script>
    <apex:form id="frm">
        <apex:pageblock >
            <apex:pageBlockSection columns="3" title="Select Warehouse">
                <apex:inputField value="{!objProdInventory.gii__Warehouse__c}" label="Warehouse"/>
                <apex:inputField value="{!objForecast.Sales_Year__c}" label="Sales Year"/>
                <apex:commandButton value="Submit" action="{!fetchProducts}" rerender="frm"/>
            </apex:pageBlockSection>
        </apex:pageblock>
        <apex:pageblock id="pb_filter" rendered="{!warehouseSelected }">
            <apex:pageBlockSection columns="3" title="Filter Products">
                <apex:selectList size="1" label="Search By" value="{!strFilterBy}">
                    <apex:selectOptions value="{!filterBy}"/>
                </apex:selectList>
                <apex:inputText value="{!searchText}" label="Search Text"/>
                <apex:commandButton value="Search" action="{!searchProducts}" rerender="pb_products"/>
            </apex:pageBlockSection>
        </apex:pageblock>
        <apex:outputpanel id="pb_products" >
        <apex:pageBlock rendered="{!IF(lstProdWrapper.size>0,true,false)}">            
            <apex:pageBlockButtons >
                <apex:commandButton value="Delete" action="{!del}"/>
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandButton value="Save & Exit" action="{!saveNexit}"/>                

            </apex:pageBlockButtons>
            <center>
                <apex:outputPanel layout="block" styleClass="pSearchShowMore" id="otpNav">

                    <apex:image url="/img/search_prevarrow_disabled.gif" styleClass="prevArrow" rendered="{!NOT(Con.HasPrevious)}"/>
                    <apex:image url="/img/search_prevarrow.gif" title="Previous Page" styleClass="prevArrow" rendered="{!Con.HasPrevious}"/>
                    <apex:commandLink action="{!Previous}" title="Previous Page" value="Previous Page" rendered="{!HasPrevious}" reRender="pb_products"/>
                    <apex:outputPanel styleClass="pShowLess noLink" style="color:grey" rendered="{!NOT(HasPrevious)}">Previous Page</apex:outputPanel>         
                    &nbsp;({!IF(PageNumber == 0,1,(PageNumber * PageSize)+1)}-{!IF(CountTotalRecords != null && CountTotalRecords < PageSize,CountTotalRecords,((PageNumber+1) * PageSize))})&nbsp;
                    <apex:outputPanel styleClass="pShowLess noLink" style="color:grey" rendered="{!NOT(HasNext)}" >Next Page</apex:outputPanel>         
                    <apex:commandLink title="Next Page" value="Next Page" rendered="{!HasNext}" action="{!Next}" reRender="pb_products"/>&nbsp;
                    <apex:image url="/img/search_nextarrow.gif" title="Next Page" styleClass="nextArrow" rendered="{!Con.HasNext}"/>
                    <apex:image url="/img/search_nextarrow_disabled.gif" rendered="{!NOT(Con.HasNext)}"/>          
                </apex:outputPanel>
            </center><br/>

            <apex:outputpanel id="tablevalues" >
            <table style="width:100%">
                <tr>
                    <th>{!$Label.Action}</th>                    
                    <th>{!$Label.Forecast_Product_Code}</th>
                    <th>{!$Label.Forecast_Product_SKU}</th>
                    <apex:repeat value="{!allMonths}" var="month">
                        <th align="center">{!month}</th>
                    </apex:repeat>
                    <th>{!$Label.Forecast_Total}</th>
                </tr>
                <apex:repeat value="{!lstProdWrapper}" var="prod">
                    <tr>
                        <td><apex:inputCheckbox value="{!prod.checked}"/></td>                        
                        <td width="140px">{!prod.productSKU}</td>
                        <td width="80px">{!prod.productCode}</td>
                        <apex:variable value="{!0}" var="count"/>
                        <apex:repeat value="{!allMonths}" var="mon">
                            <td class="quantityTableCell">
                                <apex:inputText value="{!prod.monthQty[mon]}" styleClass="{!if(prod.cellEdited[mon],'quantityCellRed','quantityCell')}" onchange="JS_QtyChanged(this)"/>                                
                            </td>
                        </apex:repeat>
                        <td align="right" padding-top= "2px" class="quantityTotalCell">
                            <b><apex:outputText value="{!prod.total}"/></b>
                        </td>
                    </tr>
                </apex:repeat>
            </table> 
            </apex:outputpanel>           
        </apex:pageBlock>       
        <apex:outputpanel rendered="{!IF(lstProdWrapper.size==0 && warehouseSelected ,true,false)}">
            <apex:pageBlock >
                {!$Label.No_Result_Found}
            </apex:pageBlock>
        </apex:outputpanel>
        </apex:outputpanel>
    </apex:form>
</apex:page>

My apex class

global class ForecastByWarehouseController
{
    public ApexPages.StandardSetController con{get; set;}
    public List<gii__ProductInventory__c> lstProdInventory{get;set;}
    public gii__ProductInventory__c objProdInventory{get;set;}
    public gii__Warehouse__c objWarehouse{get;set;}
    public Forecast__c objForecast{get;set;}
    public String Searchtext{get;set;}
    public List<ProductWrapper> lstProdWrapper{get;set;}
    public String strFilterBy{get;set;}
    public boolean noResultFound {get;set;}
    public boolean warehouseSelected {get;set;}
    public Integer CountTotalRecords{get;set;}
    public Integer NoOfPages{get;set;}
    public Integer PageSize{get;set;}
    public Integer PageNumber{get;set;}
    public String soql;
    public List<Forecast__c> allForecast;
    public gii__Warehouse__c selectedWarehouse;
    public Sales_Year__c selectSalesYear;
    public List<String> allMonths{get;set;}
    public String filterQueryPart;

    public ForecastByWarehouseController()
    {
        Searchtext = '';
        strFilterBy = '';
        objProdInventory = new gii__ProductInventory__c();
        lstProdInventory = new List<gii__ProductInventory__c>();
        objForecast = new Forecast__c();
        lstProdWrapper = new List<ProductWrapper>();
        PageSize = 10;
        PageNumber = 0;
        warehouseSelected = false;
        allMonths = new List<String>{'January','February','March','April','May','June','July','August','September','October', 'November','December'};
    }

    public List<SelectOption> getFilterBy() 
    {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('All','All Products'));
        options.add(new SelectOption('gii__Family__c','Product Family'));
        options.add(new SelectOption('gii__Color__r.name','Color'));
        options.add(new SelectOption('gii__ProductStyle__r.name','Style'));
        options.add(new SelectOption('gii__Size__c','Size'));
        return options;
    }

    public void addFilters()
    {
        system.debug('\n--strFilterBy--'+strFilterBy+'\n--Constants.STYLEFILTER--'+Constants.STYLEFILTER);        
        if((strFilterBy != '' && searchText != '')&& (strFilterBy != 'All')  && ((strFilterBy == Constants.STYLEFILTER) || (strFilterBy == Constants.COLORFILTER) || (strFilterBy == Constants.FAMILYFILTER) ))
        {
            filterQueryPart = ' AND gii__Product__r.' + strFilterBy + ' LIKE \'%' + searchText + '%\'';
        }
        else if((strFilterBy != '' && searchText != '') && (strFilterBy == 'All') )
        {
            filterQueryPart = ' AND gii__Product__r.Name LIKE \'%' + searchText + '%\'';
        }
        else
            filterQueryPart = '';
        system.debug('\n--filterQueryPart--'+filterQueryPart);
    }

    public PageReference searchProducts() 
    {
        fetchProducts();
        return null;
    }

    public PageReference fetchProducts() 
    {
        PageSize = 10;
        PageNumber = 0;
        warehouseSelected = true;
        selectedWarehouse = [select id,name from gii__Warehouse__c where id=:objProdInventory.gii__Warehouse__c];
        selectSalesYear = [select id,name from Sales_Year__c where id=:objForecast.Sales_Year__c];
        createWrapper();
        return null;
    }

    public void createWrapper()
    {
        lstProdWrapper = new List<ProductWrapper>();        
        addFilters();
        system.debug('\n--searchText--'+searchText);
        soql = 'Select id,gii__Product__r.gii__ProductStyle__r.name,name,gii__Product__c,gii__Product__r.name,gii__Product__r.gii__ProductCode__c,gii__Warehouse__c from gii__ProductInventory__c where gii__Product__r.gii__Style__c <> true AND gii__Warehouse__c =\'' + selectedWarehouse.id + '\' ' + filterQueryPart  + ' Order By gii__Product__r.gii__ProductStyle__r.name NULLS LAST,gii__Product__r.name limit ' + PageSize + ' offset ' + PageNumber*PageSize;
        String soql4count = 'Select count() from gii__ProductInventory__c where gii__Warehouse__c =\'' + selectedWarehouse.id + '\'';
        CountTotalRecords= Database.countQuery(soql4count);
        NoOfPages = CountTotalRecords/PageSize;
        if(NoOfPages * PageSize < CountTotalRecords)
            NoOfPages++;
        System.debug(soql);
        lstProdInventory = Database.query(soql);
        allForecast = [select id,Product_Inventory__c,Sales_Year__c, (select id,name,Quantity__c,Month__c from Forecast_Details__r) from Forecast__c where Product_Inventory__c IN: lstProdInventory and Sales_Year__c =: selectSalesYear.id ];
        Decimal totalForecast = 0;
        for(gii__ProductInventory__c pi : lstProdInventory)
        {
            ProductWrapper pw = new ProductWrapper();
            pw.productstyle = pi.gii__Product__r.gii__ProductStyle__r.name;
            pw.monthQty = new Map<String,String>();
            pw.oldMonthQty = new Map<String,String>();
            pw.idMonthQty = new Map<String,String>();
            pw.cellEdited = new Map<String,Boolean>();
            pw.productSKU = pi.gii__Product__r.name;
            pw.productCode = pi.gii__Product__r.gii__ProductCode__c;
            pw.ProForecast = createForecast(pi,selectSalesYear);
            totalForecast = 0;
            for(Forecast_Detail__c fd :  pw.ProForecast.Forecast_Details__r)
            {
                pw.monthQty.put(fd.Month__c,String.valueOf(fd.Quantity__c));
                pw.oldMonthQty.put(fd.Month__c,String.valueOf(fd.Quantity__c));
                pw.IdMonthQty.put(fd.Month__c,fd.id);
                system.debug('\n--fd.Quantity__c;--'+fd.Quantity__c);
                totalForecast += fd.Quantity__c;
            }
            pw.total = String.valueOf(totalForecast);
            system.debug('\n--pw.total--'+pw.total);
            for(integer i=0;i<12;i++)
            {
                if(!pw.monthQty.keyset().contains(allMonths[i]))
                {
                    pw.monthQty.put(allMonths[i],'');
                    pw.oldMonthQty.put(allMonths[i],'xxx');
                }
                pw.cellEdited.put(allMonths[i],false);
            }
            system.debug('\n--pw.total--'+pw.total);
            system.debug('\n--SIZEFILTER --'+Constants.SIZEFILTER );
            // case when user do filter by size 
            if(strFilterBy == Constants.SIZEFILTER )
            {
                if(!string.isEmpty(Searchtext))
                {
                    if(Integer.valueOf(Searchtext) == Integer.valueOf(pw.total))
                    {
                        lstProdWrapper.add(pw);
                    }               
                }
                else
                {
                    lstProdWrapper.add(pw);
                }

            }
            else
            {
                lstProdWrapper.add(pw);
            }
        }
        lstProdWrapper.sort();
    }

    public Forecast__c createForecast(gii__ProductInventory__c proInv, Sales_Year__c  syear)
    {
        for(Forecast__c f : allForecast)
        {
            if(f.Product_Inventory__c == proInv.id && f.Sales_Year__c == syear.id)
            return f;
        }
        Forecast__c fore = new Forecast__c();
        fore.name = proInv.gii__Product__r.name + '-' + proInv.name + '-' + syear.name;
        fore.Product_Inventory__c = proInv.id;
        fore.Sales_Year__c = syear.id;
        fore.Warehouse__c = proInv.gii__Warehouse__c;
        fore.Product_Reference__c = proInv.gii__Product__c;
        insert fore;
        return fore;
    }

    public PageReference save() 
    {
        List<Forecast_Detail__c> lstChild = new List<Forecast_Detail__c>();
        for(ProductWrapper objProdWrap : lstProdWrapper)
        {
            for(integer i=0;i<12;i++)
            {
                if(objProdWrap.monthQty.get(allMonths[i]) != null && objProdWrap.monthQty.get(allMonths[i]) != '')
                {
                    if(objProdWrap.oldMonthQty.get(allMonths[i]) == 'xxx')
                    {
                        lstChild.add(new Forecast_Detail__c(name=allMonths[i]+'-'+selectSalesYear.name, Month__c=allMonths[i], Quantity__c=Decimal.valueOf(objProdWrap.monthQty.get(allMonths[i])), Forecast__c=objProdWrap.ProForecast.id));
                    }
                    else
                    {
                        lstChild.add(new Forecast_Detail__c(id=objProdWrap.IdMonthQty.get(allMonths[i]),name=allMonths[i]+'-'+selectSalesYear.name, Month__c=allMonths[i], Quantity__c=Decimal.valueOf(objProdWrap.monthQty.get(allMonths[i])), Forecast__c=objProdWrap.ProForecast.id));
                    }
                }           
            }
        }
        upsert lstChild;
        createWrapper();
        return null;
    }

    public PageReference saveNexit() 
    {
        save();
        PageReference pref = new PageReference(Label.Forecast_RetURL);
        return pref;
    }

    global class ProductWrapper implements Comparable
    {
        public string productstyle {get;set;}
        public String productSKU{get;set;}
        public String productCode{get;set;}
        public Forecast__c ProForecast{get;set;}
        public String total{get;set;}
        public Map<String, String> monthQty{get;set;}
        public Map<String, String> oldMonthQty{get;set;}
        public Map<String, Id> IdMonthQty{get;set;}
        public Map<String, Boolean> cellEdited{get;set;}
        public Boolean checked {get;set;}
        public gii__ProductInventory__c emp {get;set;}

        global Integer compareTo(Object compareTo) {
            ProductWrapper compareToEmp = (ProductWrapper)compareTo;
            if (productstyle == compareToEmp.productstyle) return 0;
            if (productstyle > compareToEmp.productstyle) return 1;
            return -1;
        }
    }

    public Boolean hasNext
    {
        get
        {
            return (PageNumber+1)<NoOfPages;
        }
        set;
    }

    public Boolean hasPrevious
    {
        get
        {
            return PageNumber>0;
        }
        set;
    }


    public void previous()
    {
        PageNumber--;
        createWrapper();
    }

    public void next()
    {
        PageNumber++;
        createWrapper();
    }    

    public void del() {
        List<gii__ProductInventory__c> listEmpForDel = new List<gii__ProductInventory__c>();
        List<ProductWrapper> listTempWrapper = new List<ProductWrapper>();
        for(ProductWrapper w : lstProdWrapper) {
            if(w.checked) {
                listEmpForDel.add(w.emp);
            } else {
                listTempWrapper.add(w);
            }
        }
        System.debug('++++++++++++Size++++++++++++++++++ :'+listEmpForDel.size());
        System.debug('+++++++++++++++++++++++++++++++++++++++'+listTempWrapper+'\n');
        if(listEmpForDel.size() > 0) {
            delete listEmpForDel;
            lstProdWrapper= listTempWrapper;
        } else {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Select atleast one Account to delete'));
        }
    }

}
2

The error message says that your list contains null record at position 0.

You cannot delete null.

I believe if you add additional check if you have wrappers around null object it should work fine.

Check this:

public void del() {
    List<gii__ProductInventory__c> listEmpForDel = new     List<gii__ProductInventory__c>();
    List<ProductWrapper> listTempWrapper = new List<ProductWrapper>();
    for(ProductWrapper w : lstProdWrapper) {
        if(w.checked) {
            if ( w.emp != null )
               listEmpForDel.add(w.emp);
        } else {
            listTempWrapper.add(w);
        }
    }
    System.debug('++++++++++++Size++++++++++++++++++ :'+listEmpForDel.size());
    System.debug('+++++++++++++++++++++++++++++++++++++++'+listTempWrapper+'\n');
    if(listEmpForDel.size() > 0) {
        delete listEmpForDel;
        lstProdWrapper= listTempWrapper;
    } else {
        ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR,'Select atleast one Account to delete'));
    }
}

======================================

Update:

the reason why emp is null is because you never populate it.

This is like in the matrix: why do my eyes hurt - because you've never used them. why do my eyes hurt - matrix why do my eyes hurt - matrix ^_^ :)

Please consider adding line

pw.emp = pi;

to your createWrapper method overthere

for(gii__ProductInventory__c pi : lstProdInventory)
    {
        ProductWrapper pw = new ProductWrapper();
        pw.emp = pi;
        pw.productstyle = pi.gii__Product__r.gii__ProductStyle__r.name;
        pw.monthQty = new Map<String,String>();
  • thanks for help..but even if i am selecting the checkboxes ..nothing is deleting – Samir Feb 12 '16 at 12:24
  • i dont know why the records related to checked checkbox are coming as null – Samir Feb 12 '16 at 12:37
  • 1
    Do you populate anywhere emp? If you never populate it then it will be always null. I think I understand what is wrong with your code – Patlatus Feb 12 '16 at 13:22
  • by the way, does emp stand for Electromagnetic pulse from Matrix? matrix.wikia.com/wiki/Electromagnetic_pulse – Patlatus Feb 12 '16 at 13:30
  • 1
    I have updated my answer: please trying adding line pw.emp = pi; – Patlatus Feb 12 '16 at 14:04

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.