[SalesForce] Lightning Component redirecting to record it is creating

I am trying to create a new record using a save button on a lightning:recordEditForm

Im am fairly new to coding lightning components and have come to a bit of a standstill trying to get it to redirect to the record it is creating.

I have managed to get it to redirect to the object home but using component.get("recordId") leads to a error page doesnt exist error and tells me to input a valid url.

Here is part of my component and my controller:

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,force:hasRecordId,force:lightningQuickActionWithoutHeader,flexipage:availableForRecordHome,lightning:actionOverride" 
            access="global" >

<aura:attribute name="recordId" type="Id"/>

<lightning:recordEditForm objectApiName="Factfind__c"
                          recordId="{!v.recordId}"
                          onsubmit="{!c.handleSubmit}"
                          onsuccess="{!c.handleSuccess}">
    <lightning:messages />

and here is my controller

({
handleSubmit : function(component, event, helper) {
    console.log("this is a test");
    //Display toast message
    var toastEvent = $A.get("e.force:showToast");
    toastEvent.setParams({
        "title": "Success!",
        "message": "Factfind has been created.",
        "type": "success"
    });
    toastEvent.fire();

    // Close Quick Action Panel:
    var dismissActionPanel = $A.get("e.force:closeQuickAction");
    dismissActionPanel.fire();
    var homeEvent = $A.get("e.force:navigateToSObject");
    homeEvent.setParams({
        "recordId": component.get("v.recordId")
    });
    homeEvent.fire();

}

})

Could someone please try and show me where i'm going wrong 🙂

Best Answer

The recordId you are using should come from lightning context if record already exists. But here you are creating new record - so you need to get the new record Id in onsuccess handler method.

Also, for navigation it is recommended to use navigation library with appropriate pageReference type

In cmp:

<lightning:navigation aura:id="navService"/>

Then in onsuccess handler:

handleSuccess: function(cmp, event, helper) {
    var params = event.getParams();
    cmp.find("navService").navigate({
        "type": "standard__recordPage",
        "attributes": {
            "recordId": params.response.id,
            "objectApiName": "Factfind__c",
            "actionName": "view"
        }
    });
}
Related Topic