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
Filipe BaradelliFilipe Baradelli 

Visualforce Error: Attempt to dereference a null object

I'm trying to send the products that are added in the Catalog Order to the list of products in Opportunity. I'm making the same commands of the Catalog with the Opportunity, but the error  appears : "Visualforce Error: Attempt to dereference a null object".
This is the code that calls the error and is from Class Catalog Controller.

    /* 
     *  prepareCart()
     *  Additional constructor helper method for initializing Cart variables. 
     */
    public pageReference prepareCart() {
        if(!Catalog_Order__c.sObjectType.getDescribe().isCreateable()) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL,'Insufficient access'));
            return null;
        }
        productSet = new Set<String>();
        myOrder = new Catalog_Order__c();
        myOpp = new Opportunity();
        
        myLineItems = new List<Catalog_Line_item__c>();
        myOppLineItems = new List<OpportunityLineItem>();
        
 /*     
        This query tries to eliminate the constant creation of more and more Orders
        It grabs the last catalog modified by the current user with the status of Cart  
*/
         
        Catalog_Order__c[] orderQuery = [SELECT Items__c,Total_Cost__c,Account__c,Id,(SELECT Id,Product__c,Product_Short_Description__c,Product_Price__c,Product_Name__c,Quantity__c,VF_Image__c FROM Catalog_Line_Items__r) FROM Catalog_Order__c WHERE Status__c = 'Cart' AND CreatedById =:UserInfo.getUserId() ORDER BY LastModifiedDate DESC NULLS FIRST LIMIT 1];
        Opportunity[] oppQuery = [SELECT Id,(SELECT Id, Name FROM Produtos__r) FROM Opportunity WHERE CreatedById =:UserInfo.getUserId() ORDER BY LastModifiedDate DESC NULLS FIRST LIMIT 1];
        
        if( orderQuery.size() > 0 ) {
            myOrder = orderQuery[0];
            myOpp = oppQuery[0];
                        
            List<Catalog_Line_Item__c> cliList =  myOrder.getSObjects('Catalog_Line_Items__r'); //Get all Line Items for Order
            List<OpportunityLineItem> opplilist = myOpp.getSObjects('Produtos__r');
       
            if (cliList == null || cliList.size() < 1) {
                // No Line Items in related list so do nothing
            } else {
                // Line Items returned, so add them to product set
               for(Catalog_Line_Item__c cli : cliList) {
                    productSet.add( cli.Product__c );
               }
               
           //    opplilist.add(myOpp.getSObject('Produtos__r'));
               
               for(OpportunityLineItem oppli : opplilist){
                    productSet.add( oppli.ProductCode);
               }
            }
        }        
        return null;
    }

Can some one help me?
Pankaj_GanwaniPankaj_Ganwani
Just wrap your code within try catch block and check where exactly error is coming as it is hard to figure out by looking at your code:
 
/* 
     *  prepareCart()
     *  Additional constructor helper method for initializing Cart variables. 
     */
    public pageReference prepareCart() {
	
	try
	{
        if(!Catalog_Order__c.sObjectType.getDescribe().isCreateable()) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL,'Insufficient access'));
            return null;
        }
        productSet = new Set<String>();
        myOrder = new Catalog_Order__c();
        myOpp = new Opportunity();
        
        myLineItems = new List<Catalog_Line_item__c>();
        myOppLineItems = new List<OpportunityLineItem>();
        
 /*     
        This query tries to eliminate the constant creation of more and more Orders
        It grabs the last catalog modified by the current user with the status of Cart  
*/
         
        Catalog_Order__c[] orderQuery = [SELECT Items__c,Total_Cost__c,Account__c,Id,(SELECT Id,Product__c,Product_Short_Description__c,Product_Price__c,Product_Name__c,Quantity__c,VF_Image__c FROM Catalog_Line_Items__r) FROM Catalog_Order__c WHERE Status__c = 'Cart' AND CreatedById =:UserInfo.getUserId() ORDER BY LastModifiedDate DESC NULLS FIRST LIMIT 1];
        Opportunity[] oppQuery = [SELECT Id,(SELECT Id, Name FROM Produtos__r) FROM Opportunity WHERE CreatedById =:UserInfo.getUserId() ORDER BY LastModifiedDate DESC NULLS FIRST LIMIT 1];
        
        if( orderQuery.size() > 0 ) {
            myOrder = orderQuery[0];
            myOpp = oppQuery[0];
                        
            List<Catalog_Line_Item__c> cliList =  myOrder.getSObjects('Catalog_Line_Items__r'); //Get all Line Items for Order
            List<OpportunityLineItem> opplilist = myOpp.getSObjects('Produtos__r');
       
            if (cliList == null || cliList.size() < 1) {
                // No Line Items in related list so do nothing
            } else {
                // Line Items returned, so add them to product set
               for(Catalog_Line_Item__c cli : cliList) {
                    productSet.add( cli.Product__c );
               }
               
           //    opplilist.add(myOpp.getSObject('Produtos__r'));
               
               for(OpportunityLineItem oppli : opplilist){
                    productSet.add( oppli.ProductCode);
               }
            }
        }   
    }
    catch(Exception ex)
	{
		system.debug('============='+ex.getStackTraceString());
		system.debug('==get line no=='+ex.getLineNumber());
	}	
        return null;
    }

 
Filipe BaradelliFilipe Baradelli
Thank you. Now the code is not calling the error and the catalog is oppening. But the Opportunity's not being created. I don't know if the problem with it is in this part of the code. I've made in Process Builder a condition that creates an Opportunoty when the status of the Catalog is "Submited". If I active the Process Builder, the error is :

caused by: System.DmlException: Update failed. First exception on row 0; first error: MISSING_ARGUMENT, Id not specified in an update call: []

Class.Catalog_Controller.updateAccount: line 300, column 1

The code of this part is this : 
    /* 
     *  updateAccount(String ID) 
     *  Updates the Account field of the Order with the given Id 
     */
    public PageReference updateAccount() {
        if(!Catalog_Order__c.sObjectType.getDescribe().isUpdateable()) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL,'Insufficient access'));
            return null;
        }
        myOrder.Account__c = accountId;
        update myOrder;               // LINE 300
        // Stay on current page
        return null;
    }
If I don't activate the Process Builder, the Opportunity is not created.
Pankaj_GanwaniPankaj_Ganwani
I think, you are not giving myOrder Id while updating the Catalog_Order__c object record in updateAccount method. Just use below mentioned code and check your debug logs in org:
 
public PageReference updateAccount() {
 try
 {
        if(!Catalog_Order__c.sObjectType.getDescribe().isUpdateable()) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.FATAL,'Insufficient access'));
            return null;
        }
        myOrder.Account__c = accountId;
		system.debug('====myorder======='+myOrder);
        update myOrder;               // LINE 300
        // Stay on current page
	}
	catch(Exception ex)
	{
		system.debug('=========='+ex.getLineNumber());
	}
        return null;
    }

Just check for '===myorder====' in your debug log and see what comes.
Filipe BaradelliFilipe Baradelli
Thank you again. This time the Opportunity was created. The only thing that I need now is put inside Opportunity the products.
Filipe BaradelliFilipe Baradelli
By the Process Builder I can create the Opportunity, but with these codes I cannot insert products the new Opportunity. With the try/catch the program doesn't call any error, but the code isn't executed. This time I don't received e-mails pointing error. 
Pankaj_GanwaniPankaj_Ganwani
To see the errors, you will have to check your debug logs and you can fix them accordingly. I have already put some debug statements in your code. Please see what comes after you click on the button.
Filipe BaradelliFilipe Baradelli
I'm testing here this command in the code but the error message doesn't appears anymore when I press the button of the Catalog for confirm the Order.