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

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.

 

 

Manish Choudhari

I am a certified Salesforce Application & System Architect and Developer working on Salesforce Technology since 2014. Currently, I have 14 Salesforce certifications along with OCPJP (Oracle Certified Profession JavaSE6 Programmer) working in Salesforce.com Hyderabad as a Technical Engineer. Writing technical blogs, learning new technologies and frameworks and sharing knowledge is my hobby.

This Post Has 17 Comments

  1. Avatar

    Great Post and good use case.

  2. Avatar

    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?

    1. Avatar

      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.

  3. Avatar

    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

    1. Avatar

      Hi Nathan,

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

      Unfortunately, Lightning Standalone app is not supported for now.

  4. Avatar

    Hi,

    Are you able to override Cancel button behavior?

  5. Avatar

    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,

  6. Avatar

    I have few required fields at page layout level.how we can achieve this by using recordforme

    1. Avatar

      Required fields will automatically be taken care by recordForm if you are using layouts. It will throw an error as well if the user miss any of the require field.

  7. Avatar

    Hi Manish can u share data model for this Rent a car Application

  8. Avatar

    Hi Sir ,

    I am trying to create a case record using <lightning:recordEditForm and added all the fields using <lightning:inputfield.
    Now could you tell me how to capture the entered values and save to the server.Do we have any functions similar to saverecord.
    please help me

    1. Avatar

      The data will be automatically saved on the server. You don’t have to save these by your own.

  9. Avatar

    Hello Manish,

    Is it possible use lightning:recordForm to display a record details from a record that is linked with lookup.
    For example under Contact page layout to display the account details via lightning:recordForm in which the contact is associated.

    ideally I would like to define the
    recordId=”{!v.recordId}” as the record ID of the account that a contact is associated.

    Thanks in advance
    Dimi

Leave a Reply

Close Menu