Tuesday, June 11, 2019

force:createRecord in lightning

force:createRecord is an event that opens a page to create a record for specific entity.

Sample syntax:

createRecord : function (component, event, helper) {
    var createRecordEvent = $A.get("e.force:createRecord");
    createRecordEvent.setParams({
        "entityApiName": "ObjectApiName"
    });
    createRecordEvent.fire();
}

defaultFieldValues attribute inside setParams let us auto populate value on fields inside record form.

Firing the force:createRecord event tells the app to use the standard create record page.
We can specify values for fields even if they’re not available in the create record form.

NOTE:
  • If we specify Field value using defaultFieldValues and If the field is hidden i.e not on the page layout, the value specified in defaultFieldValues is saved with the new record.
  • If the current user doesn’t have create access to the field, due to field-level security, attempts to save the new record result in an error. We cannot catch this error and hence it is necessary to perform access check before firing the event.
Sample Example to create account:

COMPONENT:

<aura:component implements="flexipage:availableForAllPageTypes">
    <lightning:button label="New Account" onclick="{!c.createAccount}"/>
</aura:component>

CONTROLLER:

({
createAccount : function(component, event, helper) {
        var recordEvent=$A.get("e.force:createRecord");
        recordEvent.setParams({
            "entityApiName": "Account",
            "defaultFieldValues":{
                "Industry":"Apparel"
            }
        });
        recordEvent.fire();
}
})

2 comments:

  1. How can I get Id of the record which is created in force:createRecord event in same transaction?

    ReplyDelete
  2. I am getting error as This page has an error. You might just need to refresh it.
    Action failed: c:AccountCreationUsingForce$controller$createAccount [Cannot read property 'setParams' of undefined]
    Failing descriptor: {c:AccountCreationUsingForce$controller$createAccount}

    ReplyDelete