[SalesForce] Lightning server-side method returning “undefined”

I have a very simple Lightning controller class that upserts a Contact record:

@AuraEnabled
public static String saveContact(Contact newContact) {
    Contact c = newContact;
    upsert c;
    return c.Id;
}

The issue I am having is that although the upsert goes through just fine after calling from client's controller, the returned ID (String) from the server is coming back as "undefined".

Here's what the client controller's relative function looks like:

handleClick : function(component, event, helper) {
    // grab component's new Contact holder attribute
    var con = component.get("v.newContact");

    // setup action
    var action = component.get("c.saveContact");
    action.setParams({ 
        "newContact" : con
    });
    action.setCallback(this, function(a) {
        var conId = a.getReturnValue();
        console.log('Contact ID: '+ conId); // returns "undefined"
    });
    $A.enqueueAction(action);
}, 

The Contact passed to saveContact is generated on the component, so it has all of its necessary field values before it reaches the server, where all that's left to do is the DML.

Can anyone see something that I might be missing here? Can't understand why the returned ID value isn't coming through to the client. Thanks!

Best Answer

You are not getting the ID because it's probably erroring on upsert but you don't know that since you're not checking the state of the action. Make your callback look like this:

action.setCallback(this, function(a) {
    console.log('Was I successful? ' + a.getState()); // THIS IS NEW
    var conId = a.getReturnValue();
    console.log('Contact ID: '+ conId); // returns "undefined"
});

You should check if you're in a success or error callback: https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/controllers_server_actions_call.htm

Related Topic