force:createRecord example in Salesforce Lightning

Sample Code:

CreateAccountComponent.cmp

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

CreateAccountComponentcontroller.js

({
createAccount: function (component) {
        var createRecordEvent = $A.get('e.force:createRecord');
        if ( createRecordEvent ) {
            createRecordEvent.setParams({
                'entityApiName': 'Account',
                'defaultFieldValues': {
                    'Type' : 'Prospect',
                    'Industry' : 'Apparel',
                    'Rating' : 'Hot'
                }
            });
            createRecordEvent.fire();
        } else {
            /* Create Record Event is not supported */
            alert("Account creation not supported");
        }
    }
})

Add the lightning component to any page. I have added it to the Account detail page.

Output:



Cheers!!!

3 comments:

  1. I tried putting this in a Lighting Application:



    But the call to force:createRecord failed. Any idea why?

    ReplyDelete
    Replies
    1. This event is handled by the one.app container. It’s supported in Lightning Experience, the Salesforce app, and Lightning communities. This event presents a standard page to create a record. That is, it doesn’t respect overrides on the object’s create action.

      Delete
  2. Good post on how to pre-populate fields.
    Thanks it solved my problem.

    ReplyDelete