0

I have created a custom object named AssetLookup which has a lookup to an Asset record.

I added it to my controller:

public class LicenseActivationController {
    public Asset_Lookup__c assetLookup { get; set; }

    public void activateLicense() {
        // assetLookup.Asset__r is null here, despite me selecting an asset using the lookup control.
        // I need to get the serial number of the asset here: assetLookup.Asset__r.SerialNumber
    }
}

I wrapped it inside a form in my VisualForce page:

<apex:form>
    <apex:inputField value="{!assetLookup.Asset__c}" id="assetLookup" />
    <apex:commandButton value="Activate" action="{!ActivateLicense}" />
</apex:form>

But, the problem is that it seems to be null on post. Why is it null and what can I do to get the record back on a from post? Specifically I tried getting the serial number using assetLookup.Asset__r.SerialNumber but it tries to de-reference a null object, despite me selecting an asset using the lookup relationship.

1

You're missing the concept of a lookup field.

What a lookup field essentially is, is an ID field. So, when you're selecting the 'Asset' record with the lookup field, you're setting the 'Asset_Lookup__c' records 'Asset__c' ID to be equal to the selected assets ID.

So, you have to query the asset record.

public void activateLicense() {
    // Essential NULL check
    if(assetLookup == null || assetLookup.Asset__c == null) {
        // NULL Values, error message maybe?
        return;
    }
    // Here you need a query
    Asset selected = [SELECT SerialNumber FROM Asset WHERE Id = :assetLookup.Asset__c];

    // You can now access the 'SerialNumber' field of the asset record
    String serial = selected.SerialNumber;
}

Also, in the constructor, you have to initialize the "assetLookup" variable:

public LicenseActivationController() {
    assetLookup = new Asset_Lookup__c();
}

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.