0

I'm making a system for our custom packages. When attempting to assign the packages from a visualforce page to the Opportunity I end up getting this the error. This error only happens when clicking the Add Packages button. Otherwise the page appears to be working fine.

Line 91 is the line with:

PageReference cancel = controller.cancel();

Visualforce Error:

public class MetadataPackageEditor{
//------------------------------ Extension Code-----------------
private final Package__c pPackage;

private final Opportunity_Package__c oppPackage;

private final Opportunity opp;    
    // The extension constructor initializes the private member
    // variable acct by using the getRecord method from the standard
    // controller.


    public MetadataPackageEditor(ApexPages.StandardController stdController) {

        sObjectType oType = stdController.getRecord().getsObjectType();

        if (oType == Package__c.sObjectType){
            this.pPackage = (Package__c)stdController.getRecord();
        }

        else if (oType == Opportunity_Package__c.sObjectType) {
            this.oppPackage = (Opportunity_Package__c)stdController.getRecord();
        }

        else if (oType == Opportunity.sObjectType)
        {
            this.opp = (Opportunity)stdController.getRecord();
        }
    }
// Reference for page returns
Private ApexPages.StandardSetController controller;

public MetadataPackageEditor(ApexPages.StandardSetController stdController) {

        sObjectType oType = stdController.getRecord().getsObjectType();

        this.controller = stdController;

        if (oType == Package__c.sObjectType){
            this.pPackage = (Package__c)stdController.getRecord();
        }

        else if (oType == Opportunity_Package__c.sObjectType) {
            this.oppPackage = (Opportunity_Package__c)stdController.getRecord();
        }

        else if (oType == Opportunity.sObjectType)
        {
            this.opp = (Opportunity)stdController.getRecord();
        }
    }    
//-------------------------------------End of Extension code------------------


public List<pPackage> packageList {get;set;}

public List<pPackage> getPackages() {
    if(packageList == null) {
        packageList = new List<pPackage>();
        for(Package__c p: [SELECT Id, Name, PPU_Discount__c, Expiration_Date__c, Products__c FROM Package__c]) {
            packageList.add(new pPackage(p));
        }
    }
    return packageList;
}

public List<Package__c> selectedPackages {get;set;}

public PageReference processSelectedPackages() {
    selectedPackages = new List<Package__c>();

    for(pPackage pPack: getPackages()) {
        if(pPack.selected == true){
            selectedPackages.add(pPack.pack);
        }
    }
    packageList=null;
    return null;
}

//Add all of the selected packages and return to the previous page
public String oppId {get;set;}

public PageReference processAndAddSelected(){
if(controller != null){
if(oppId != null){
    Opportunity opp = new Opportunity(id=oppId);
    processSelectedPackages();
if(selectedPackages != null && selectedPackages.size()>0){    
    for(Package__c pack: selectedPackages){
        Opportunity_Package__c oppPack = new Opportunity_Package__c();
        oppPack.Name = pack.Name;
        oppPack.Opp_Package_Rel__c = opp.Id;
        oppPack.Package_Opp_Rel__c = pack.Id;
        insert oppPack;
    }
   }

   else{
       throw new MetadataServiceExamplesException('Request failed due to selectedPackages being NULL.');
   }

    return controller.cancel();
    }
    else{
        throw new MetadataServiceExamplesException('Request failed due to oppId being NULL.');
        }
        }
    else{
        throw new MetadataServiceExamplesException('Request failed due to Controller being NULL.');
    }
}

public void pullStandardProducts () {

  MetadataService.MetadataPort service = createService();     
        MetadataService.CustomField customField = new MetadataService.CustomField();
        customField.fullName = 'Package__c.Products__c';
        customField.label = 'Products';
        customField.type_x = 'MultiselectPicklist';
        customField.visibleLines = 7;
        metadataservice.Picklist pt = new metadataservice.Picklist();
        pt.sorted= false;


    Id stdPricebook = [
        SELECT ID
        FROM Pricebook2
        WHERE IsStandard = true].Id;

    List<PricebookEntry> products = [
        SELECT Name
        FROM PricebookEntry
        WHERE Pricebook2Id = :stdPricebook];

    List<MetadataService.PicklistValue> valuesToAdd = new List<MetadataService.PicklistValue>();

    for (Integer j = 0; j < products.size(); j++){
        MetadataService.PicklistValue tempValue = new MetadataService.PicklistValue();
        tempValue.fullName = products.get(j).Name;
        tempValue.default_x = false;
        valuesToAdd.add(tempValue);
    }

    pt.picklistValues = new List<MetadataService.PicklistValue>();

    pt.picklistValues.addAll(valuesToAdd);

        customField.picklist = pt ;
        List<MetadataService.SaveResult> results =      
            service.updateMetadata(
                new MetadataService.Metadata[] { customField });
        handleSaveResults(results[0]);

}


public static MetadataService.MetadataPort createService()
    { 
        MetadataService.MetadataPort service = new MetadataService.MetadataPort();
        service.SessionHeader = new MetadataService.SessionHeader_element();
        service.SessionHeader.sessionId = UserInfo.getSessionId();
        return service;     
    }

public static void handleSaveResults(MetadataService.SaveResult saveResult)
    {
        // Nothing to see?
        if(saveResult==null || saveResult.success)
            return;
        // Construct error message and throw an exception
        if(saveResult.errors!=null) 
        {
            List<String> messages = new List<String>();
            messages.add(
                (saveResult.errors.size()==1 ? 'Error ' : 'Errors ') + 
                    'occured processing component ' + saveResult.fullName + '.');
            for(MetadataService.Error error : saveResult.errors)
                messages.add(
                    error.message + ' (' + error.statusCode + ').' + 
                    ( error.fields!=null && error.fields.size()>0 ? 
                        ' Fields ' + String.join(error.fields, ',') + '.' : '' ) );
            if(messages.size()>0)
                throw new MetadataServiceExamplesException(String.join(messages, ' '));
        }
        if(!saveResult.success)
            throw new MetadataServiceExamplesException('Request failed with no specified error.');
    }
    }

Visualforce:

<apex:page standardController="Opportunity_Package__c" extensions="MetadataPackageEditor" sidebar="false" showHeader="false">
  <apex:form >

      <apex:outputField value="{!Opportunity_Package__c.Opp_Package_Rel__c}"/>

      <apex:pageBlock title="Select Package(s)">
      <apex:pageMessages />

          <apex:pageBlockTable value="{!packages}" var="o" id="table">
              <apex:column title="Select" headerValue="Select">
                  <apex:inputCheckbox value="{!o.selected}"/>
              </apex:column>
              <apex:column value="{!o.pack.Name}"/>
              <apex:column value="{!o.pack.Products__c}"/>
              <apex:column value="{!o.pack.PPU_Discount__c}" headerValue="Price per Unit Discount"/>
          </apex:pageBlockTable>
      <apex:commandButton value="Add Packages" action="{!processAndAddSelected}">
          <apex:param name="oppIdParam" value="{!Opportunity_Package__c.Opp_Package_Rel__c}" assignTo="{!oppId}"/>
      </apex:commandButton>
      <apex:commandButton action="{!cancel}" value="Cancel"/>
      </apex:pageBlock>



  </apex:form>
</apex:page>
  • The error is saying that you are trying to use a variable that is null. The error is happening in MetadataPackageEditor.processAndAddSelected on line 96. If you can show which line is 96 then people will be able to provide more help. – BarCotter Mar 4 '15 at 17:07
  • Okay, made an edit to the main post. It is the like with PageReference cancel on it – Cody Beaner Mar 4 '15 at 17:11
  • That means that controller is null for some reason. – BarCotter Mar 4 '15 at 17:13
  • Any idea why? It very clearly gets an assignment. And it's saying it's de-referencing a null object, not that it's a null value assignment issue – Cody Beaner Mar 4 '15 at 17:16
  • 1
    I have added all my code to the post. I also simultaneously realized my issue. I have this within a set constructor, and not a standard constructor – Cody Beaner Mar 4 '15 at 17:28
1

The error means that the controller variable is null. You have two constructors and are only setting controller in one of them.

This is the constructor that is getting called:

public MetadataPackageEditor(ApexPages.StandardController stdController)

Where as you only set the controller variable in the constructor below

public MetadataPackageEditor(ApexPages.StandardSetController stdController)  
  • 1
    You posted before I could, thank you though this was the correct answer. – Cody Beaner Mar 4 '15 at 17:32
0

//Add null check around this for loop

public PageReference processAndAddSelected(){
    Opportunity opp = new Opportunity(id=oppId);
    processSelectedPackages();
if(selectedPackages != null && selectedPackages.size()>0){
    for(Package__c pack: selectedPackages){
        Opportunity_Package__c oppPack = new Opportunity_Package__c();
        oppPack.Name = pack.Name;
        oppPack.Opp_Package_Rel__c = opp.Id;
        oppPack.Package_Opp_Rel__c = pack.Id;
        insert oppPack;
    }
}
    PageReference cancel = controller.cancel();
    return cancel;
}
  • Added this, and even added an else statement to throw an exception if it's null. Yet I still get the same error. – Cody Beaner Mar 4 '15 at 17:04
  • What part of code is falling under line 91 before you make change. – Suresh Mar 4 '15 at 17:08
  • line 91: PageReference cancel = controller.cancel(); – Cody Beaner Mar 4 '15 at 17:10
  • there might issue with the opportunity, you are just passing as opp.id, Try passing the OppId directly instead of writing this line Opportunity opp = new Opportunity(id=oppId); beacuse you are getting that value directly from page and you no need to do the above line. do null checkon OppId too. – Suresh Mar 4 '15 at 17:11
  • I can't as it needs to be passed as a param from the page, so it can dynamically know which opportunity it is adding it to. – Cody Beaner Mar 4 '15 at 17:15

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.