Saturday, May 18, 2019

force:hasRecordId and flexipage:availableForAllPageTypes interface

By using force:hasRecordId interface in lightning component we can assigned the id of the current record to lightning component. This interface adds an attribute named "recordId" to the component. The type of attribute is string and has 18-character Salesforce record ID.

Sample example:

<aura:component implements="force:hasRecordId">
</aura:component>

Now let us understand the use of force:hasRecordId with a real example.

Scenario: We are having a requirement to provide the mechanism for the insertion of the contact record from the account detail page.

Solution:

1) Component: 

We have implemented interface force:hasRecordId to obtain accountid using recordId attribute from account detail page and to make our component available for record page and any other type of page, we need to implement the interface flexipage:availableForAllPageTypes interface.

<aura:component controller="ContactInsertClass" implements="force:hasRecordId,flexipage:availableForAllPageTypes"> 
    <aura:attribute name="firstName" type="string"/>
    <aura:attribute name="lastName" type="string"/>
    <lightning:input label="Enter First Name" value="{!v.firstName}"/>
    <lightning:input label="Enter Last Name" value="{!v.lastName}"/>
    <lightning:button label="Add contact" onclick="{!c.addContact}"/>
</aura:component>

2) Javascript controller:

({

 addContact : function(component, event, helper) {

        var fName=component.get("v.firstName");

        var lName=component.get("v.lastName");

        var action=component.get('c.insertContact');  // Calling Apex Controller method

        action.setParams({

            parentAccountId:component.get("v.recordId"),  // Passing parameter

            firstName1:component.get("v.firstName"),

            lastName1:component.get("v.lastName")

        });

        action.setCallback(this,function(response){

            var state=response.getState();

            if(state==="SUCCESS")

            {
                alert('Contact inserted successfully');              
            }
        });

        $A.enqueueAction(action);
 }

})

3) Apex controller:

public class ContactInsertClass {
@AuraEnabled
public static contact insertContact(string parentAccountId,string firstName1,string lastName1)
{
    system.debug('Test');
    contact con=new contact();
    con.firstName=firstName1;
    con.lastName=lastName1;
    con.accountid=parentAccountId;
    insert con;
    return con;
   
}

}

Image from Account record page:

force:hasRecordId and flexipage:availableForAllPageTypes interface

6 comments:

  1. Really Good Blog....Explaining concepts with simple examples .. Thanks for sharing

    ReplyDelete
  2. Good place to learn SFDC lightning

    ReplyDelete
  3. Superb blog... Appreciate your efforts!

    ReplyDelete
  4. Very Nice explanation!! thanks

    ReplyDelete