journey2salesforce

Call Lightning Component from Flow

Call Lightning Component from Flow

In this section, we will call a Lightning Component from a Flow. Same Assignment: Create a Contact by Lightning Component calling from a Flow. To do this assignment, we will use Lightning Data Service.

Step 1: Create a component bundle named “createContactByLDS”.

createContactByLDS.cmp | to create contact using Lightning Data Service. To refer this component to flow, you must implement “lightning:availableForFlowScreens” at the component level.

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,lightning:availableForFlowScreens">

    <aura:attribute name="account" type="Object"/>
    <aura:attribute name="loadedAccountFields" type="Object"/>
    <aura:attribute name="accountError" type="String"/>

    <aura:attribute name="newContact" type="Object"/>
    <aura:attribute name="newContactFields" type="Object"/>
    <aura:attribute name="newContactError" type="String"/>
    

    <force:recordData aura:id="accountRecordLoaderId"
        recordId="{!v.recordId}"
        fields="Name"
        targetRecord="{!v.account}"
        targetFields="{!v.loadedAccountFields}"
        targetError="{!v.accountError}"
    />

    <force:recordData aura:id="contactRecordCreatorId"
        layoutType="FULL"
        targetRecord="{!v.newContact}"
        targetFields="{!v.newContactFields}"
        targetError="{!v.newContactError}" 
        /> 

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

    <div class="slds-page-header" role="banner">
        <p class="slds-text-heading_label">{!v.loadedAccountFields.Name}</p>
        <h1 class="slds-page-header__title slds-m-right_small
            slds-truncate slds-align-left">Create New Contact</h1>
    </div>
    <lightning:card >
        <aura:if isTrue="{!not(empty(v.accountError))}">
            <div class="recordError">
                <ui:message title="Error" severity="error" closable="true">
                    {!v.accountError}
                </ui:message>
            </div>
        </aura:if>
        <aura:if isTrue="{!not(empty(v.newContactError))}">
            <div class="recordError">
                <ui:message title="Error" severity="error" closable="true">
                    {!v.newContactError}
                </ui:message>
            </div>
        </aura:if>

        <lightning:layout multiplerows="true" verticalalign="center">
            <lightning:layoutItem padding="around-small" size="12">
                <lightning:input aura:id="contactField" 
                                 name="firstName" 
                                 label="First Name"
                                 value="{!v.newContactFields.FirstName}"/>
              
                <lightning:input aura:id="contactField" 
                                 name="lastname" 
                                 label="Last Name"
                                 value="{!v.newContactFields.LastName}" 
                                 required="true"/>
                        
                <!--<lightning:input aura:id="contactField" 
                                 type="phone" 
                                 name="phone" 
                                 label="Phone Number"
                                 pattern="^(1?(-?\d{3})-?)?(\d{3})(-?\d{4})$"
                                 messageWhenPatternMismatch="The phone number must contain 7, 10, or 11 digits. Hyphens are optional."
                                 value="{!v.newContactFields.Phone}" 
                                 required="true"/>-->
                
                <lightning:input aura:id="contactField" 
                                 type="email" 
                                 name="email" 
                                 label="Email"
                                 value="{!v.newContactFields.Email}" />
                
                <div class="slds-float_right">
                    <lightning:button label="Reset" onclick="{!c.doReset}" class="slds-m-top_medium" />
                    <lightning:button label="Save" onclick="{!c.saveContact}"
                                      variant="brand" class="slds-m-top_medium"/>
                </div>                
           </lightning:layoutItem>
       </lightning:layout>    
    </lightning:card>
</aura:component>

createContactByLDSController.js | to save and reset the contact record

({
    doInit: function(component, event, helper) {
        helper.openNewContact(component);
    },

    saveContact: function(component, event, helper) {
        if(helper.validateContactForm(component)) {
            component.set("v.newContactFields.AccountId", component.get("v.recordId"));
            component.find("contactRecordCreatorId").saveRecord(function(saveResult) {
                if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {

                    var resultsToast = $A.get("e.force:showToast");
                    resultsToast.setParams({
                        "title": "Success! ",
                        "message": "The new contact was created.",
                        "type":"success"
                    });

                    $A.get("e.force:closeQuickAction").fire();
                    resultsToast.fire();

                    $A.get("e.force:refreshView").fire();
                    helper.openNewContact(component);
                }
                else if (saveResult.state === "INCOMPLETE") {
                    console.log("User is offline, device doesn't support drafts.");
                }
                else if (saveResult.state === "ERROR") {
                    console.log('Problem saving contact, error: ' +
                                 JSON.stringify(saveResult.error));
                }
                else {
                    console.log('Unknown problem, state: ' + saveResult.state +
                                ', error: ' + JSON.stringify(saveResult.error));
                }
            });
        }
    },

    doReset: function(component, event, helper) {
        //$A.get("e.force:closeQuickAction").fire();
        helper.openNewContact(component);
    },
})

createContactByLDSHelper.js | to create a blank form and validation for the contact record

({
    
    openNewContact: function(component){
        component.find("contactRecordCreatorId").getNewRecord(
            "Contact", // objectApiName
            null, // recordTypeId
            false, // skip cache?
            $A.getCallback(function() {
                var rec = component.get("v.newContact");
                var error = component.get("v.newContactError");
                if(error || (rec === null)) {
                    console.log("Error initializing record template: " + error);
                }
                else {
                    console.log("Record template initialized: " + rec.sobjectType);
                }
            })
        );
    },


    validateContactForm: function(component) {
        var validContact = true;
        var allValid = component.find('contactField').reduce(function (validFields, inputCmp) {
            inputCmp.showHelpMessageIfInvalid();
            return validFields && inputCmp.get('v.validity').valid;
        }, true);

        if (allValid) {
            var account = component.get("v.account");
            if($A.util.isEmpty(account)) {
                validContact = false;
                console.log("Quick action context doesn't have a valid account.");
            }
        	return(validContact);
            
        }  
	}
       
})

createContactByLDS.design | to define an input attribute for this component

<design:component >
	<design:attribute name="recordId" label="Current Record Id"/>
</design:component>

Step 2: Create a flow where you will refer this Lightning Component. Just drag the Screen element in the Cloud Flow Designer and Select Lightning Component from “Add a Field” tab and set the input attribute named “recordId” of the Lightning Component. Save the flow named “Create Contact by Lightning Component” and activate it.

Step 3: Now, need to add the Flow in Lightning Record Page of Account. So, just open any account record and click “Edit Page” from Settings on the page and drag the “flow” into the record page. Now, select the flow name in the Lightning Record Page and select “Pass record ID into this variable” to send the record Id from Flow to Lightning Component.

Results

Steps to Remember

1. To refer any Lightning Component into the Flow, you must implement “lightning:availableForFlowScreens” at the component level.
2. If any attributes need to send to Lightning component from Flow, you have to define the design of Lightning Component just like

<design:component >
	<design:attribute name="recordId" label="Current Record Id"/>
</design:component>

3. When you will set the Lightning Component, you must set the input attribute of the Lightning Component.
4. When you will add the Flow in Lightning Record Page, do not forget to select “Pass record ID into this variable”, if needs to send record Id to Lightning Component via Flow.

487 total views, 1 views today

Rating: 5.0/5. From 1 vote.
Please wait...

You may also like...