I am trying to navigate to an object's record page once it is created after a button click but the recordId is currently showing as undefined when I print it to the console. Any idea how to retrieve the object's recordId correctly in the helper?
2 Answers
Actually, problem is ...you are trying to find out wrong aura:I'd
<lightning:navigation aura:id="navigation"/>
But in code you are using,
var navService = component.find("navService");
Change it to correct id:
var navService = component.find("navigation");
-
Thank you, this fixed the error but now I am printing the recordId to the console and it is showing as undefined. Any idea how I can retrieve the id?– JeremyJun 2, 2019 at 13:21
In addition to Ayub's note, you have two issues with how you're making your navigation request.
- You're making the URL-generation call synchronously, but it needs to be asynchronous (within the callback for your server call to create the account).
- You have a
recordId
attribute you're trying to use that seems to be spurious. That attribute will be populated by the Lightning Experience if (a) your component implementsforce:hasRecordId
and (b) it's surfaced on a Record Page. Even if you did those two things, though, that attribute wouldn't hold the Id of a newly-created record - you need the server return value to tell you that.
So essentially, all of this code:
var recordId = component.get("v.recordId");
var navService = component.find("navigation");
var pageReference = {
type: 'standard__recordPage',
attributes: {
recordId: recordId,
objectApiName: 'Account',
actionName: 'view'
}
};
component.set("v.pageReference", pageReference);
var defaultUrl = "#";
navService.generateUrl(pageReference)
.then($A.getCallback(function(url) {
component.set("v.url", url ? url : defaultUrl);
}), $A.getCallback(function(error) {
component.set("v.url", defaultUrl);
}));
needs to be inside the callback from c.saveAccount
. But rather than using v.recordId
, the record Id for the new Account will be response.getReturnValue().Id
.