Friday, May 17, 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 real example.

Scenario: We are required to provide insertion of contact functionality from 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;
   
}

}

Screen Image from Account record page:

force:hasRecordId and flexipage:availableForAllPageTypes interface


No comments:

Post a Comment