2

I am attempting to get a map of a custom object so I can display every record of that object on a visualforce page.

APEX Code:

Map<Integer, Package__c> packageMap { get; set; }

public Map<Integer, Package__c> getPackageMap() {

    Integer i = 0;

    for (Package__c pack : [SELECT Name, Products__c, PPU_Discount__c FROM Package__c]) {
        packageMap.put(i, pack);
        i++;
        }

    return packageMap;

}

Visualforce Code:

<table style="width:100%;">
          <tbody>
              <tr>
                  <th>Select</th>
                  <th>Package</th>
                  <th>Products</th>
                  <th>PPU Discount</th>
                  <th>Expiration Date</th>
              </tr>

              <apex:repeat value="{!packageMap}" var="oppPackage">
              <tr>
                  <td></td>
                  <td><apex:inputField value="{!packageMap[oppPackage].Name}" /></td>
                  <td><apex:inputField value="{!packageMap[oppPackage].Products__c}" /></td>
                  <td><apex:inputField value="{!packageMap[oppPackage].PPU_Discount__c}" /></td>
                  <td></td>
              </tr>
              </apex:repeat>
          </tbody>
      </table>

The Controller and extension I'm using are working correctly, and the error specifies that it is occuring in "{!getPackageMap}" at the line where I use packageMap.put();

2 Answers 2

8

Just instantiate the map.

Map<Integer, Package__c> packageMap = new Map<Integer, Package__c>();

Before using it in the controller.

public Map<Integer, Package__c> getPackageMap() {

    Integer i = 0;

    // you need to instantiate packageMap before adding to it
    packageMap = new Map<Integer, Package__c>();

    for (Package__c pack : [
            SELECT Name, Products__c, PPU_Discount__c
            FROM Package__c
    ]) {
        packageMap.put(i, pack);
        i++;
    }

    return packageMap;

}
1
  • Like this? packageMap = new Map<Integer, Package__c>(); After the declaration? If not, how so? Feb 23, 2015 at 16:30
1

This error is caused by a line of code that is trying to use an object that has not been instantiated, or an object's attribute that has not been initialized.

So probably Packagemap is null, check it out, if it isn't i'm not sure if it could be the Query returning null, but i'm betting for the first option.

Tell me if this helped you some way :)

Greetings.

2
  • How would I go about checking if it is null? Feb 23, 2015 at 16:14
  • Maruf gave you the right path to go ;) Feb 24, 2015 at 10:09

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .