force:createRecord Example

This simple lightning component is designed to simply show a button that will open a new record – for a different object type and allow you to set some default values at the same time.

This example will also use the force:recordData to get the record so that some default values can be passed to the new record screen.

The code for the lightning component is

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >

<aura:attribute name="record" type="Object"/>
<aura:attribute name="simpleRecord" type="Object"/>
<aura:attribute name="recordError" type="String"/>

<force:recordData aura:id="recordLoader"
recordId="{!v.recordId}"
layoutType="FULL"
targetRecord="{!v.record}"
targetFields="{!v.simpleRecord}"
targetError="{!v.recordError}"
recordUpdated="{!c.recordUpdated}"
/>

<lightning:card title="Common Actions" iconName="custom:custom103" footer="">
<ul class="slds-button-group-list">
<li>
<button class="slds-button slds-button_neutral" onclick="{!c.newMissedBin}">Missed Bin</button>
</li>
</ul>
</lightning:card>

</aura:component>

This is pretty straightforward but we use force:recordData to get the record from the page to be able to pass this for default values in the new record.

In the controller we have a simple call to the e.force:createRecord

    newRecord: function(component, event, helper) {
        var recordId = component.get("v.recordId");
        var simpleRecord = component.get("v.simpleRecord");
        var createRecordEvent = $A.get("e.force:createRecord");
        createRecordEvent.setParams({
            "entityApiName": "Object Name",
            "recordTypeId": "0120Y000000BGQBQA4",
            "defaultFieldValues": {
                'field1' : recordId,
                'field2' : simpleRecord.fields
            }
        });
        createRecordEvent.fire();
    },

This is really simple code and allows control over a two main areas:

  • The record type can be set on entry (see this post for a scenario where setting the record type is useful)
  • Default values can be set up programatically, and with this code the recordId and fields from the main record are available

Leave a Reply

Your email address will not be published.