lightning:recordForm Example

In this blog, I am going to show the simple example how to use lightning:recordForm .A lightning:recordForm component enables you to quickly create forms to add, view, or update a record. Using this component to create record forms is easier than building forms manually with lightning:recordEditForm and lightning:recordViewForm. This component takes care of field-level security and sharing for you, so users see only the data that they have access to.

The component accepts a mode value that determines the user interaction allowed for the form. The value for mode can be one of the following:

edit – Creates an editable form to add a record or update an existing one. When updating an existing record, specify the recordId.
view – Creates a form to display a record that the user can also edit. The record fields each have an edit button. View mode is the default, and as such, can be omitted.
readonly – Creates a form to display a record without enabling edits. The form doesn’t display any buttons.

Creating a Record

Use mode=”edit” and pass in the object API name for the record to be created. Specify the fields using the fields attribute, or layoutType attribute to load all the fields defined on the given layout.Because no recordId is passed, edit mode loads the form with input fields that aren’t populated with field data. The form displays Submit and Cancel buttons

 <aura:attribute name="sObjectName" type="String" default="Pet__c" />
    <lightning:card iconName="custom:custom19" title="lightning:recordForm">
        <div class="slds-p-left_large slds-p-right_medium">	
            <lightning:recordForm aura:id="recordViewForm" 
                                  objectApiName="{!v.sObjectName}"
                                  fields="Name,Breed__c,Gender__c,Notes__c,Type__c"
                                  columns="2"
                                  layoutType ="Full"
                                  mode="edit"
                                  onsuccess="{!c.onSuccess}"
                                  onsubmit="{!c.onSubmit}"
                                  onload="{!c.onLoad}"
                                  onerror="{!c.onError}"
                                  />

 

Editing a Record

Use mode=”edit” and pass the ID of the record and the corresponding object API name to be edited. Specify the fields using the fields attribute, or layoutType attribute to load all the fields defined on the given layout.When a recordId is passed, edit mode loads the form with input fields displaying the specified record’s field values. The form also displays Submit and Cancel buttons.

<lightning:card iconName="custom:custom19" title="Edit lightning:recordForm">
        <div class="slds-p-left_large slds-p-right_medium">	
            <lightning:recordForm aura:id="recordViewForm" 
                                  objectApiName="{!v.sObjectName}"
                                  columns="2"
                                  fields="Name,Breed__c,Gender__c,Notes__c,Type__c"
                                  recordId="a8C2F0000004FDUUA2"
                                  layoutType ="Full"
                                  mode="View"
                                  onsuccess="{!c.onSuccess}"
                                  onsubmit="{!c.onSubmit}"
                                  onload="{!c.onLoad}"
                                  onerror="{!c.onError}"
                                  />   
            
        </div>
    </lightning:card>

 

Viewing a Record Read-Only

Use mode=”readonly” and pass the ID of the record and the corresponding object API name to be displayed. Specify the fields using the fields attribute, or layoutType attribute to display all the fields defined on the given layout.The readonly mode loads the form with output fields only, and without Submit or Cancel buttons

 <lightning:card iconName="custom:custom19" title="Read Only lightning:recordForm">
        <div class="slds-p-left_large slds-p-right_medium">	
            <lightning:recordForm aura:id="recordViewForm" 
                                  objectApiName="{!v.sObjectName}"
                                  columns="2"
                                  fields="Name,Breed__c,Gender__c,Notes__c,Type__c"
                                  recordId="a8C2F0000004FDUUA2"
                                  layoutType ="Full"
                                  mode="readonly"
                                  onsuccess="{!c.onSuccess}"
                                  onsubmit="{!c.onSubmit}"
                                  onload="{!c.onLoad}"
                                  onerror="{!c.onError}"
                                  />   
            
        </div>
    </lightning:card>

 

 

Complete code

<aura:component implements="flexipage:availableForAllPageTypes,force:appHostable,flexipage:availableForRecordHome,force:hasRecordId,force:hasSObjectName" access="global" >
    <aura:attribute name="sObjectName" type="String" default="Pet__c" />
    <lightning:card iconName="custom:custom19" title="lightning:recordForm">
        <div class="slds-p-left_large slds-p-right_medium">	
            <lightning:recordForm aura:id="recordViewForm" 
                                  objectApiName="{!v.sObjectName}"
                                  fields="Name,Breed__c,Gender__c,Notes__c,Type__c"
                                  columns="2"
                                  layoutType ="Full"
                                  mode="edit"
                                  onsuccess="{!c.onSuccess}"
                                  onsubmit="{!c.onSubmit}"
                                  onload="{!c.onLoad}"
                                  onerror="{!c.onError}"
                                  />   
            
        </div>
    </lightning:card>
    <lightning:card iconName="custom:custom19" title="Edit lightning:recordForm">
        <div class="slds-p-left_large slds-p-right_medium">	
            <lightning:recordForm aura:id="recordViewForm" 
                                  objectApiName="{!v.sObjectName}"
                                  columns="2"
                                  fields="Name,Breed__c,Gender__c,Notes__c,Type__c"
                                  recordId="a8C2F0000004FDUUA2"
                                  layoutType ="Full"
                                  mode="View"
                                  onsuccess="{!c.onSuccess}"
                                  onsubmit="{!c.onSubmit}"
                                  onload="{!c.onLoad}"
                                  onerror="{!c.onError}"
                                  />   
            
        </div>
    </lightning:card>
    
    <lightning:card iconName="custom:custom19" title="Read Only lightning:recordForm">
        <div class="slds-p-left_large slds-p-right_medium">	
            <lightning:recordForm aura:id="recordViewForm" 
                                  objectApiName="{!v.sObjectName}"
                                  columns="2"
                                  fields="Name,Breed__c,Gender__c,Notes__c,Type__c"
                                  recordId="a8C2F0000004FDUUA2"
                                  layoutType ="Full"
                                  mode="readonly"
                                  onsuccess="{!c.onSuccess}"
                                  onsubmit="{!c.onSubmit}"
                                  onload="{!c.onLoad}"
                                  onerror="{!c.onError}"
                                  />   
            
        </div>
    </lightning:card>
    
</aura:component>
({
    onSuccess : function(component, event, helper) {
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            "title": "Success!",
            "message": "The record has been Saved successfully."
        });
        toastEvent.fire();
    },
    onSubmit : function(component, event, helper) {
    },
    onLoad : function(component, event, helper) {
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            "title": "Loaded!",
            "message": "The record has been Loaded successfully ."
        });
        toastEvent.fire();
    },
    onError : function(component, event, helper) {
        var toastEvent = $A.get("e.force:showToast");
        toastEvent.setParams({
            "title": "Error!",
            "message": "Error."
        });
        toastEvent.fire();
    }
    
    
})

 

 

Advertisement

fullcalendar.io Lightning Component

In this blog, I am going to show how to create a custom calendar using  FullCalendar .

Prerequisites

Download the  FullCalendar  and update the below js and CSS file to static resource

  1. jQuery – An insanely popular JavaScript framework that FullCalendar requires to work.
  2. Moment.js – A great JavaScript library for parsing and manipulating dates.
  3. FullCalendar – The actual FullCalendar library which contains fullcalendar.js and fullcalendar.css.

Apex Controller 

public class TaskcalendarController {
    @AuraEnabled
    public static List<Task__c> getTasks(){
        List<Task__c> result =  [Select Id, Name,Completed_Date__c,LastModifiedDate from Task__c ];
        return result ; 
    } 
}

Lightning Component 

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes" access="global" 
                controller="TaskcalendarController">
    <ltng:require scripts="{!join(',', 
                           $Resource.fullcalendar + '/jquery.min.js', 
                           $Resource.fullcalendar + '/jquery-ui.min.js',
                           $Resource.fullcalendar + '/moment.min.js', 
                           $Resource.fullcalendar + '/fullcalendar.min.js')}"
                  styles="{!$Resource.fullcalendar + '/fullcalendar.min.css'}"
                  
                  afterScriptsLoaded="{!c.scriptsLoaded}" />
    
    <div id='calendar'></div>
    
    
</aura:component>
({
    scriptsLoaded : function(component, event, helper) {
        helper.getResponse(component);
    },
});


({
    getResponse: function(component) {
        var action = component.get("c.getTasks");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var result = response.getReturnValue();
                console.log("Data: \n" + result);
                var eventArr = [];
                result.forEach(function(key) {
                    eventArr.push({
                        'id':key.Id,
                        'start':key.Completed_Date__c,
                        'end':key.Completed_Date__c,
                        'title':key.Name
                    });
                });
                console.log(eventArr);
                this.loadCalendar(eventArr);
                
            } else if (state === "INCOMPLETE") {
            } else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + errors[0].message);
                    }
                } else {
                    console.log("Unknown error");
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    loadCalendar :function(data){   
        var m = moment();
        $('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay,listWeek'
            },
            defaultDate: m.format(),
            editable: true,
            navLinks: true, // can click day/week names to navigate views
            weekNumbers: true,
            weekNumbersWithinDays: true,
            weekNumberCalculation: 'ISO',
            editable: true,
            eventLimit: true,
            
            events:data
        });
    },
    
})

 

lightning:quickActionAPI

In this blog I am going to show how to use lightning:quickActionAPI  component  that allows you to access methods for programmatically controlling quick actions on record pages. lightning:quickActionAPIcomponent is supported in Lightning Experience only. For Example, if you wanted to reuse the existing quick action across the different places like on the detail page or custom lightning component you can able to use lightning:quickActionAPI  to access the quick actions programmatically. To access the methods, create an instance of the lightning:quickActionAPI component inside your Lightning component or page and assign an aura:id attribute to it

<lightning:quickActionAPI aura:id="quickActionAPI"/>

In this example, I create a quick action that deactivates the Notification Opt-In Type from Active to inactive with configuration. Here is the simple quick action

Now you could be able to access that quick action programmatically by using lightning:quickActionAPI .

Here is the simple component I created for testing

<aura:component implements="flexipage:availableForRecordHome,force:lightningQuickAction" description="My Lightning Component">
    <lightning:quickActionAPI aura:id="quickActionAPI" />
    <div>
        <lightning:button label="updateNotifications" onclick="{!c.updateNotifications}"/>
    </div>
</aura:component>

The button call the following client-side controller.

({
    
    updateNotifications : function( cmp, event, helper ) {
        var actionAPI = cmp.find("quickActionAPI");
        var fields = {Active__c: {value:false }, Name: 
                      {value: "Update from the Quick Action API"}};
        var args = {actionName: "Notification_Opt_In_Type__c.Update_Notification", entityName: "Notification_Opt_In_Type__c", targetFields: fields};
        actionAPI.setActionFieldValues(args).then(function(){
            actionAPI.invokeAction(args);
        }).catch(function(e){
            console.error(e.errors);
        });
    }
    
})

Now I added the component to the lightning record page as shown below. On click of the Update Notification button, the javascript controller will call the quick action API and perform the update the based on the quick action.

Code Walkthrough 

  1. Below line will help javascript controller to find the Quick Action API
        var actionAPI = cmp.find("quickActionAPI");

2.Set the target Fields with the values you wanted to update as shown below

  var fields = {Active__c: {value:false }, Name: 
                      {value: "Update from the Quick Action API"}};

3. Creta an arguments to pass it the quick action API method setActionFieldValues that allow custom components to select a quick action on a record pace and then specify field values for that action.

 var args = {actionName: "Notification_Opt_In_Type__c.Update_Notification", entityName: "Notification_Opt_In_Type__c", targetFields: fields};
        actionAPI.setActionFieldValues(args).then(function(){
            actionAPI.invokeAction(args);
        }).catch(function(e){
            console.error(e.errors);
        });

4. Use the invokeAction method that allows custom components to save or submit the quick action on a record page.

            actionAPI.invokeAction(args);

 

Lightning Chart.js example

In this blog, I am going to show how to use the Chart.js in the lightning component with different types of charts. Using chart.js easy to get started. All that’s required is the script included in your page along with a single  node to render the chart.

Step 1: Add Chart.js to the static resource

Go to this link  and download the latest version of chart.js and upload the static resource

Step 2: Apex Class

Here is the simple apex class which I created to get the aggregate data from the Task__c custom object.

public class TaskManagerChart {
    
    @AuraEnabled
    public static List<DataSet> getAllTasksByStatus(){
        List<AggregateResult> result =  [Select Count(Id) cnt, Status__c from Task__c group by Status__c ];
        List<DataSet> dataSet = new List<DataSet>();
        for(AggregateResult ar:result){
            String status =  (String)ar.get('Status__c') ;
            Integer total =(Integer)ar.get('cnt'); 
            dataSet.add(new DataSet(status ,total));
            
        }
        System.debug('dataSet'+dataSet);
        return dataSet ; 
    }
    
    public class DataSet{
        public DataSet(String label ,Integer count){
            this.label  = label ; 
            this.count = count ;
        }
        @AuraEnabled
        public String label {get;set;}
        @AuraEnabled
        public Integer  count {get;set;}
        
        
    }
    
}

 

Step 3: Lightning Component Pie chart

Here is the simple lightning component that shows the task by status as a pie chart. I am loading the chart.js libraries by using ltng:require and using afterScriptsLoaded method to fetch controller logic

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes" access="global" controller="TaskManagerChart">
    <ltng:require scripts="{!$Resource.Chartjs+ '/Chart.min.js'}"
                  afterScriptsLoaded="{!c.scriptsLoaded}" />
    <canvas id="pie-chart" width="950" height="250"></canvas>
 </aura:component>
({
    scriptsLoaded : function(component, event, helper) {
        var action = component.get("c.getAllTasksByStatus");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                let val = response.getReturnValue() ;
                var labelset=[] ;
                var dataset=[] ;
                val.forEach(function(key) {
                    labelset.push(key.label) ; 
                    dataset.push(key.count) ; 
                });
                new Chart(document.getElementById("pie-chart"), {
                    type: 'pie',
                    data: {
                        labels:labelset,
                        datasets: [{
                            label: "Count of Task",
                            backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9"],
                            data: dataset
                        }]
                    },
                    options: {
                        title: {
                            display: true,
                            text: 'Total Tasks by Status'
                        }
                    }
                });
            }
        });
        $A.enqueueAction(action);
        
    }
})

 

Bar Chart 

Bar charts are created by setting type to bar

 new Chart(document.getElementById("pie-chart"), {
                    type: 'bar',
                    data: {
                        labels:labelset,
                        datasets: [{
                            label: "Count of Task",
                            backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9"],
                            data: dataset
                        }]
                    },
                    options: {
                        title: {
                            display: true,
                            text: 'Total Tasks by Status'
                        }
                    }
                });
            }
        })

 

Polar area chart

A polar area chart is created by setting typepolarArea. Polar area charts are closely related to pie charts, with the difference that in addition to the angles representing the relative size of the data points, the radius of each element is set in relation to its value.

 new Chart(document.getElementById("pie-chart"), {
                    type: 'polarArea',
                    data: {
                        labels:labelset,
                        datasets: [{
                            label: "Count of Task",
                            backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9"],
                            data: dataset
                        }]
                    },
                    options: {
                        title: {
                            display: true,
                            text: 'Total Tasks by Status'
                        }
                    }
                });
            }

 

Doughnut chart

Doughnut charts are created by setting type to doughnut.

   new Chart(document.getElementById("pie-chart"), {
                    type: 'doughnut',
                    data: {
                        labels:labelset,
                        datasets: [{
                            label: "Count of Task",
                            backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9"],
                            data: dataset
                        }]
                    },
                    options: {
                        title: {
                            display: true,
                            text: 'Total Tasks by Status'
                        }
                    }
                });