lightning:recordForm – Powerful component for viewing and editing record in lightning

 

lightning:recordForm is a very powerful component for editing, viewing and adding a record in lightning.

This component is a gift of #Summer18 release and combines the power of both lightning:recordEditForm and lightning:recordViewForm.

In this blog, we will be using lightning:recordForm with lightning:dataTable for quick record editing and viewing.

 

So let’s get started:

Component:

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,force:lightningQuickAction"
                controller="CarSearchController"
                access="global" >
  
    <aura:attribute name="data" type="Object"/>
    <aura:attribute name="columns" type="List"/>
    <aura:attribute name="recordId" type="String"/>
    <aura:attribute name="showDetails" type="boolean" default="false" />
    <aura:attribute name="myCar" type="String[]" default="[Id,Name,Build_Year__c,Per_Day_Rent__c,Mileage__c,Available_For_Rent__c,Id]" />

    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>

    <lightning:layout
        <lightning:layoutItem size="8" padding="around-small">
            <lightning:card title="All Cars">
                <lightning:datatable
                                     columns="{! v.columns }"
                                     data="{! v.data }"
                                     keyField="id"
                                     onsave ="{!c.onSave}"
                                     hideCheckboxColumn="true"
                                     onrowaction="{! c.handleRowAction }" />
            </lightning:card>
        </lightning:layoutItem>
        <lightning:layoutItem size="4" padding="around-small">
            <aura:if isTrue="{!v.showDetails}">
                <lightning:card title="Record Detail">
                    <lightning:recordForm
                                          recordId="{!v.recordId}"
                                          objectApiName="Car__c"
                                          fields="{!v.myCar}"
                                          columns="1"
                                          mode="view" />
                </lightning:card>
            </aura:if>
        </lightning:layoutItem>
    </lightning:layout>
</aura:component>

Client Controller:

({
    doInit : function(component, event, helper) {
        //creating datatable columns
        component.set('v.columns', [
            {label: 'Name', fieldName: 'Name', type: 'text'},
            {label: 'Build Year', fieldName: 'Build_Year__c', type: 'number'},
            {label: 'Rent/Day', fieldName: 'Per_Day_Rent__c', type: 'currency',
                typeAttributes: { currencyCode: 'USD'}},
            {label: 'Mileage', fieldName: 'Mileage__c', type: 'number'},
            {label: 'Available', fieldName: 'Available_For_Rent__c', type: 'boolean'},
            {label: 'Action', type: 'button', initialWidth: 135, typeAttributes:
               { label: 'View', name: 'view_details', title: 'Click to View or Edit Details'}}
        ]);
        //getting Car__c records from server by calling helper methods
        helper.getCars(component, helper);

    },
    //this function will be called when view button is pressed in datatable
    handleRowAction: function (component, event, helper) {
        var action = event.getParam('action');
        var car = event.getParam('row');
        switch (action.name) {
            case 'view_details':
                component.set("v.recordId", car.Id);
                break;
            default:
                component.set("v.recordId", car.Id);
                break;
        }
        if(component.get("v.recordId")){
            component.set("v.showDetails", true);
        }
    },
})

 

Client Helper:

({
//this function will fetch Car__c records from server
getCars : function(component, helper) {
        var action = component.get("c.getAllCars");
        action.setCallback(this,function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.data", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },
})

 

Server Side Controller:

public with sharing class CarSearchController {    
    //this function returns all Car__c records to lightning component
    @AuraEnabled
    public static List<Car__c> getAllCars(){
        //If 'All Type' selected on UI, below code will execute to get all cars
        return [SELECT Id, Name, Picture__c, Contact__r.Name,
                    Build_Year__c , Per_Day_Rent__c , Mileage__c, Available_For_Rent__c,
                    Geolocation__latitude__s, Geolocation__longitude__s
                    FROM Car__c ];
    }
}

 

 

So this is how you can use lightning:recordForm component for easy record view, add and edit purpose. Below are few considerations and facts about this component:

  • If you want to create new record, ‘recordId’ attribute should be blank or should be defined.
  • You need to define either ‘layoutType’ or ‘fields’ attribute or both. This will determine which fields should be visible in this component. layoutType can be Compact or Full, the fields defined in these layout will be automatically picked up by the component
  • Attribute ‘mode’ can have three values
    • view – Record will be displayed in view mode. Can be changed to edit mode by clicking on ‘pencil’ icon on fields.
    • edit – Record will be displayed in edit mode with ‘Save’ and ‘Cancel’ button.
    • readonly – Record will be displayed in view mode but cannot be changed to edit mode.
  • ‘objectApiName’ is only required attribute which will hold the api name of object.
  • You can override standard save functionality with your code by overriding ‘onsubmit’. Define your own controller action and execute it on ‘onsubmit’ event.

 

So, it ain’t hard, is it? Now get rid of that bulky code in your org and use lightning:recordForm now.

 

 

(Visited 5454 Times)

9 thoughts on “lightning:recordForm – Powerful component for viewing and editing record in lightning

  1. Faiz Ali

    Great post Manish!
    However is there any way with which we can give preset values to any particular field while creating a form through lightning:recordForm, probable use case could be like when we want to create a form for a child object which is instatntiated from a parent detail page quick action button and we want just the parent’s field to be prefilled in the form. Any thoughts on this?

    Reply
    1. Manish Choudhari Post author

      Hi Faiz,

      Unfortunately, prefilled values are not supported as of now. However you can use recordEditForm for this purpose, you can define value attribute in recordEditForm to achieve this.

      Reply
  2. Nathan

    Would this work on a standalone app? For instance, if I have an app, that was its’ own tab in my org, and not on a record page. What I am experiencing is that the save and cancel buttons will appear, but the form itself is not there. I know this is not much info to go on, but if you could maybe test using this in an app and not on a record page. This would at least confirm to me that I’m either crazy or that it does in fact not work for standalone apps

    Reply
    1. Manish Choudhari Post author

      Hi Nathan,

      This component will only work in Lightning Experience, Lightning Communities, Salesforce Mobile App.

      Unfortunately, Lightning Standalone app is not supported for now.

      Reply
  3. salesforce user

    Hi Manish,

    Can we get lightning component in which we can have all the fields value of selected account.so we can edit them.

    We want this dynamic so that we get all fields value according to the selected object’s records.

    Thanks,

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *