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!!!

5 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
  3. Magulan, hope you remember me! I have question on this - with force:createRecord when it opens record creation page, looks like, it is not opening record type selector. it is taking profile's default record type. Is there any way, we could open record type selector page? User has access to multiple record type.

    ReplyDelete
    Replies
    1. Nope. There is no straight forward way for this. First show them the screen to show the record types, then call the event.

      Delete