function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
abu saleh khan 8abu saleh khan 8 

How to fetch lookup value in column.

Hi Team,

My requirement is, i have a add row component which is added to my Account record detail page. I am trying to bulk insert the records in contact as a related contact to the account. I want to fetch accountid in the column, inorder to insert into contact. Kindly look at the snippet.

AddRowEvent:

<aura:event type="COMPONENT" description="Use For Add New Row"></aura:event> 

DeleteRowEvent:

<aura:event type="COMPONENT" description="Event to remove Row" >
    <aura:attribute name="indexVar" type="Integer" description="Use For Delete Row" />
</aura:event>

User-added image

<aura:component controller="AddDeleteController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction,lightning:isUrlAddressable">
  <!--Init handler which is call doInit js function on component Load-->  
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
  
 <!--Event handler for Add and Delete Row Event which is fire from Child Component-->    
    <aura:handler name="DeleteRowEvent" event="c:DeleteRowEvt" action="{!c.removeDeletedRow}"/>
    <aura:handler name="AddRowEvt" event="c:AddRowEvent" action="{!c.addNewRow}"/>
 
 <!--Aura Attribute for store Contact Object List as Array-->    
    <aura:attribute name="contactList" type="Contact[]"/>      
 <!--Table Part-->           
    <table class="slds-table slds-table_bordered slds-table_cell-buffer"> 
        <thead>
            <tr class="slds-text-title_caps">
                <th scope="col">
                    <div class="slds-truncate">Sno</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Price Record Id">Price Record Id</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Product">Product</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="SAP Id">SAP Id</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Proposed Price">Proposed Price</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="UOM">UOM</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Validity Start">Validity Start</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Validity End">Validity End</div>
                </th>
            </tr>
        </thead>   
        <tbody>
           <!--Iterate the child Component for display Table rows 
               with pass the List Item Index for track the Every child Component 
               and pass each List Contact Instance -->         
            <aura:iteration items="{!v.contactList}" var="item" indexVar="index">
                <c:DynamicRowItem ContactInstance="{!item}" rowIndex="{!index}" />
            </aura:iteration>
        </tbody>
    </table>
    <br/>
    <!--Save Button which is call Save js function on click --> 
    <button class="slds-button slds-button_brand" onclick="{!c.Save}">Save</button>
</aura:component>

DynamicRowController:

({
 
    // function call on component Load
    doInit: function(component, event, helper) {
        // create a Default RowItem [Contact Instance] on first time Component Load
        // by call this helper function  
        helper.createObjectData(component, event);
    },
 
    // function for save the Records 
    Save: function(component, event, helper) {
        // first call the helper function in if block which will return true or false.
        // this helper function check the "first Name" will not be blank on each row.
        if (helper.validateRequired(component, event)) {
            // call the apex class method for save the Contact List
            // with pass the contact List attribute to method param.  
            var action = component.get("c.saveContacts");
            action.setParams({
                "ListContact": component.get("v.contactList")
            });
            // set call back 
            action.setCallback(this, function(response) {
                var state = response.getState();
                if (state === "SUCCESS") {
                    // if response if success then reset/blank the 'contactList' Attribute 
                    // and call the common helper method for create a default Object Data to Contact List 
                    component.set("v.contactList", []);
                    helper.createObjectData(component, event);
                    alert('record Save');
                }
            });
            // enqueue the server side action  
            $A.enqueueAction(action);
        }
    },
 
    // function for create new object Row in Contact List 
    addNewRow: function(component, event, helper) {
        // call the comman "createObjectData" helper method for add new Object Row to List  
        helper.createObjectData(component, event);
    },
 
    // function for delete the row 
    removeDeletedRow: function(component, event, helper) {
        // get the selected row Index for delete, from Lightning Event Attribute  
        var index = event.getParam("indexVar");
        // get the all List (contactList attribute) and remove the Object Element Using splice method    
        var AllRowsList = component.get("v.contactList");
        AllRowsList.splice(index, 1);
        // set the contactList after remove selected row element  
        component.set("v.contactList", AllRowsList);
    },
})

DynamicRowHelper.js

({
    createObjectData: function(component, event) {
        // get the contactList from component and add(push) New Object to List  
        var RowItemList = component.get("v.contactList");
        RowItemList.push({
            'sobjectType': 'Contact',
            'FirstName': '',
            'LastName': '',
            'Phone': ''
        });
        // set the updated list to attribute (contactList) again    
        component.set("v.contactList", RowItemList);
    },
    // helper function for check if first Name is not null/blank on save  
    validateRequired: function(component, event) {
        var isValid = true;
        var allContactRows = component.get("v.contactList");
        for (var indexVar = 0; indexVar < allContactRows.length; indexVar++) {
            if (allContactRows[indexVar].FirstName == '') {
                isValid = false;
                alert('First Name Can\'t be Blank on Row Number ' + (indexVar + 1));
            }
        }
        return isValid;
    },
})

DynamicRowItem:

<aura:component >    
    <!-- Aura Attribute for store single Contact[standard Object] Instance
         And Store Index of Particular Instance --> 
    <aura:attribute name="ContactInstance" type="Contact"/>
    <aura:attribute name="rowIndex" type="String"/>
    
    <!-- Register 2 Lightning Event for handle add or Delete rows on Parent Component  --> 
    <aura:registerEvent name="DeleteRowEvent" type="c:DeleteRowEvt"/> 
    <aura:registerEvent name="AddRowEvt" type="c:AddRowEvent"/> 
    
    <!-- Table Row -->   
    <tr class="slds-text-title_caps">
        <td> 
            {!v.rowIndex + 1}
        </td>
        <td>
            <lightning:input class="slds-input" value="{!v.ContactInstance.FirstName}"/>
        </td>
        <td>
            <lightning:input class="slds-input" value="{!v.ContactInstance.LastName}"/>
        </td>
        <td>
            <lightning:input class="slds-input" value="{!v.ContactInstance.Phone}"/>
        </td>
        <td>
            <lightning:input class="slds-input" value="{!v.ContactInstance.FirstName}"/>
        </td>
        <td>
            <lightning:input class="slds-input" value="{!v.ContactInstance.LastName}"/>
        </td>
        <td>
            <lightning:input class="slds-input" value="{!v.ContactInstance.Phone}"/>
        </td>
        <td>
            <lightning:input class="slds-input" value="{!v.ContactInstance.FirstName}"/>
        </td>
        <td>
            <!-- conditionally Display Add or Delete Icons
                 if rowIndex is 0 then show Add New Row Icon else show delete Icon
             --> 
            <aura:if isTrue="{!v.rowIndex == 0}">
                <a onclick="{!c.AddNewRow}">
                  <lightning:icon iconName="utility:add" class="slds-icon slds-icon_small" size="small" alternativeText="add"/>
                  <span class="slds-assistive-text">Add Icon</span>
                </a>    
              <aura:set attribute="else">
                  <a onclick="{!c.removeRow}">
                   <lightning:icon variant="error" iconName="utility:delete" class="slds-icon slds-icon_small" size="small" alternativeText="icon"/>
                   <span class="slds-assistive-text">Delete Icon</span>
                  </a>
              </aura:set> 
            </aura:if>
        </td> 
    </tr>
</aura:component>

DynamicRowItemController.js

({
    AddNewRow : function(component, event, helper){
       // fire the AddNewRowEvt Lightning Event 
        component.getEvent("AddRowEvt").fire();     
    },
    
    removeRow : function(component, event, helper){
     // fire the DeleteRowEvt Lightning Event and pass the deleted Row Index to Event parameter/attribute
       component.getEvent("DeleteRowEvent").setParams({"indexVar" : component.get("v.rowIndex") }).fire();
    }, 
  
})
Best Answer chosen by abu saleh khan 8
Khan AnasKhan Anas (Salesforce Developers) 
Hi Abu,

Greetings to you!

Firstly, you can use add/remove row functionality without parent-child component i.e.; you can create a single component. Below is the sample code for that:

Component:
<aura:component controller="AddOrDeleteRowC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <!--Init handler which is call doInit js function on component Load-->  
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <!--Aura Attribute for store Contact Object List as Array-->    
    <aura:attribute name="contactList" type="Contact[]"/> 
    
    <!--Header Part-->        
    <div class="slds-page-header">
        <h1 class="slds-page-header__title">Create Multiple Contacts, With Add/Delete Rows Dynamically</h1>
    </div>
    
    <!--Table Part-->           
    <table class="slds-table slds-table_bordered slds-table_cell-buffer"> 
        <thead>
            <tr class="slds-text-title_caps">
                <th scope="col">
                    <div class="slds-truncate">S.No</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="First Name">First Name</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Last Name">Last Name</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Phone">Phone</div>
                </th>
            </tr>
        </thead>   
        
        <tbody>    
            <aura:iteration items="{!v.contactList}" var="ContactInstance" indexVar="rowIndex">
                <tr class="slds-text-title_caps">
                    <td> 
                        {!rowIndex + 1}
                    </td>
                    <td>
                        <ui:inputText class="slds-input" value="{!ContactInstance.FirstName}"/>
                    </td>
                    <td>
                        <ui:inputText class="slds-input" value="{!ContactInstance.LastName}"/>
                    </td>
                    <td>
                        <ui:inputPhone class="slds-input" value="{!ContactInstance.Phone}"/>
                    </td>
                    <td>
                        <aura:if isTrue="{!rowIndex == 0}">
                            <!--<aura:if isTrue="{!lessthanorequal(v.contactList.length,10)}">-->
                                <a onclick="{!c.addNewRow}">
                                    <lightning:icon iconName="utility:add" class="slds-icon slds-icon_small" size="small" alternativeText="add"/>
                                    <span class="slds-assistive-text">Add Icon</span>
                                </a>
                                <aura:set attribute="else">
                                    <lightning:buttonIcon size='large' iconName="utility:add" variant="bare"  alternativeText="Add" disabled='true'  />  
                                </aura:set>
                            <!--</aura:if>   -->
                            
                            <aura:set attribute="else">
                                <a onclick="{!c.removeDeletedRow}" data-value="{!rowIndex}">
                                    <lightning:icon variant="error" iconName="utility:delete" class="slds-icon slds-icon_small" size="small" alternativeText="icon"/>
                                    <span class="slds-assistive-text">Delete Icon</span>
                                </a>
                            </aura:set> 
                        </aura:if>
                    </td> 
                </tr>
                
                
            </aura:iteration>
        </tbody>
    </table>
    <br/>
    
    <!--Save Button which is call Save js function on click --> 
    <lightning:button label="Save" 
                      variant="brand" 
                      iconName="utility:save"
                      iconPosition="left"
                      onclick="{!c.Save}"/>
    
</aura:component>

Controller:
({    
    // function call on component Load
    doInit: function(component, event, helper) {
        // create a Default RowItem [Contact Instance] on first time Component Load
        // by call this helper function  
        helper.createObjectData(component, event);
    },
    
    // function for save the Records 
    Save: function(component, event, helper) {
        // first call the helper function in if block which will return true or false.
        // this helper function check the "first Name" will not be blank on each row.
        if (helper.validateRequired(component, event)) {
            // call the apex class method for save the Contact List
            // with pass the contact List attribute to method param.  
            var action = component.get("c.saveContacts");
            action.setParams({
                "ListContact": component.get("v.contactList")
            });
            // set call back 
            action.setCallback(this, function(response) {
                var state = response.getState();
                if (state === "SUCCESS") {
                    // if response if success then reset/blank the 'contactList' Attribute 
                    // and call the common helper method for create a default Object Data to Contact List 
                    component.set("v.contactList", []);
                    helper.createObjectData(component, event);
                    alert('Record Saved Successfully');
                }
            });
            // enqueue the server side action  
            $A.enqueueAction(action);
        }
    },
    
    // function for create new object Row in Contact List 
    addNewRow: function(component, event, helper) {
        // call the comman "createObjectData" helper method for add new Object Row to List  
        helper.createObjectData(component, event);
    },
    
    // function for delete the row 
    removeDeletedRow: function(component, event, helper) {
        // get the selected row Index for delete, from Lightning Event Attribute  
        
        var ctarget = event.currentTarget;
        var index = ctarget.dataset.value;
        // get the all List (contactList attribute) and remove the Object Element Using splice method    
        var AllRowsList = component.get("v.contactList");
        AllRowsList.splice(index, 1);
        // set the contactList after remove selected row element  
        component.set("v.contactList", AllRowsList);
    },
})

Helper:
({
    createObjectData: function(component, event) {
        // get the contactList from component and add(push) New Object to List  
        var RowItemList = component.get("v.contactList");
        RowItemList.push({
            'sobjectType': 'Contact',
            'FirstName': '',
            'LastName': '',
            'Phone': ''
        });
        
        // set the updated list to attribute (contactList) again            
        component.set("v.contactList", []);      
        component.set("v.contactList", RowItemList);
    },
    
    // helper function for check if first Name is not null/blank on save  
    validateRequired: function(component, event) {
        var isValid = true;
        var allContactRows = component.get("v.contactList");
        for (var indexVar = 0; indexVar < allContactRows.length; indexVar++) {
            if (allContactRows[indexVar].FirstName == '') {
                isValid = false;
                alert('First Name Can\'t be Blank on Row Number ' + (indexVar + 1));
            }
        }
        return isValid;
    },
})

Apex:
public with sharing class AddOrDeleteRowC {
    
    @AuraEnabled
    public static void saveContacts(List<Contact> ListContact){
        Insert ListContact;
    }
}

There's an idea which is active on the success community to include lookup field in lightning component for which you can upvote so that it gets available in the future.

https://success.salesforce.com/ideaView?id=08730000000Dom1AAC

However, you can create a reusable custom lookup and include it in your component to use lookup input field. Please refer to below link which might help you further.

http://sfdcmonkey.com/2017/07/17/re-usable-custom-lookup/

This is a dynamic Re-Usable Lightning Component, you can use it in any component. You just need to pass the objectAPIName, IconName, selected Record and Field Label Name Attribute when using this Custom Lookup component.

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi Abu,

Greetings to you!

Firstly, you can use add/remove row functionality without parent-child component i.e.; you can create a single component. Below is the sample code for that:

Component:
<aura:component controller="AddOrDeleteRowC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <!--Init handler which is call doInit js function on component Load-->  
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <!--Aura Attribute for store Contact Object List as Array-->    
    <aura:attribute name="contactList" type="Contact[]"/> 
    
    <!--Header Part-->        
    <div class="slds-page-header">
        <h1 class="slds-page-header__title">Create Multiple Contacts, With Add/Delete Rows Dynamically</h1>
    </div>
    
    <!--Table Part-->           
    <table class="slds-table slds-table_bordered slds-table_cell-buffer"> 
        <thead>
            <tr class="slds-text-title_caps">
                <th scope="col">
                    <div class="slds-truncate">S.No</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="First Name">First Name</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Last Name">Last Name</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Phone">Phone</div>
                </th>
            </tr>
        </thead>   
        
        <tbody>    
            <aura:iteration items="{!v.contactList}" var="ContactInstance" indexVar="rowIndex">
                <tr class="slds-text-title_caps">
                    <td> 
                        {!rowIndex + 1}
                    </td>
                    <td>
                        <ui:inputText class="slds-input" value="{!ContactInstance.FirstName}"/>
                    </td>
                    <td>
                        <ui:inputText class="slds-input" value="{!ContactInstance.LastName}"/>
                    </td>
                    <td>
                        <ui:inputPhone class="slds-input" value="{!ContactInstance.Phone}"/>
                    </td>
                    <td>
                        <aura:if isTrue="{!rowIndex == 0}">
                            <!--<aura:if isTrue="{!lessthanorequal(v.contactList.length,10)}">-->
                                <a onclick="{!c.addNewRow}">
                                    <lightning:icon iconName="utility:add" class="slds-icon slds-icon_small" size="small" alternativeText="add"/>
                                    <span class="slds-assistive-text">Add Icon</span>
                                </a>
                                <aura:set attribute="else">
                                    <lightning:buttonIcon size='large' iconName="utility:add" variant="bare"  alternativeText="Add" disabled='true'  />  
                                </aura:set>
                            <!--</aura:if>   -->
                            
                            <aura:set attribute="else">
                                <a onclick="{!c.removeDeletedRow}" data-value="{!rowIndex}">
                                    <lightning:icon variant="error" iconName="utility:delete" class="slds-icon slds-icon_small" size="small" alternativeText="icon"/>
                                    <span class="slds-assistive-text">Delete Icon</span>
                                </a>
                            </aura:set> 
                        </aura:if>
                    </td> 
                </tr>
                
                
            </aura:iteration>
        </tbody>
    </table>
    <br/>
    
    <!--Save Button which is call Save js function on click --> 
    <lightning:button label="Save" 
                      variant="brand" 
                      iconName="utility:save"
                      iconPosition="left"
                      onclick="{!c.Save}"/>
    
</aura:component>

Controller:
({    
    // function call on component Load
    doInit: function(component, event, helper) {
        // create a Default RowItem [Contact Instance] on first time Component Load
        // by call this helper function  
        helper.createObjectData(component, event);
    },
    
    // function for save the Records 
    Save: function(component, event, helper) {
        // first call the helper function in if block which will return true or false.
        // this helper function check the "first Name" will not be blank on each row.
        if (helper.validateRequired(component, event)) {
            // call the apex class method for save the Contact List
            // with pass the contact List attribute to method param.  
            var action = component.get("c.saveContacts");
            action.setParams({
                "ListContact": component.get("v.contactList")
            });
            // set call back 
            action.setCallback(this, function(response) {
                var state = response.getState();
                if (state === "SUCCESS") {
                    // if response if success then reset/blank the 'contactList' Attribute 
                    // and call the common helper method for create a default Object Data to Contact List 
                    component.set("v.contactList", []);
                    helper.createObjectData(component, event);
                    alert('Record Saved Successfully');
                }
            });
            // enqueue the server side action  
            $A.enqueueAction(action);
        }
    },
    
    // function for create new object Row in Contact List 
    addNewRow: function(component, event, helper) {
        // call the comman "createObjectData" helper method for add new Object Row to List  
        helper.createObjectData(component, event);
    },
    
    // function for delete the row 
    removeDeletedRow: function(component, event, helper) {
        // get the selected row Index for delete, from Lightning Event Attribute  
        
        var ctarget = event.currentTarget;
        var index = ctarget.dataset.value;
        // get the all List (contactList attribute) and remove the Object Element Using splice method    
        var AllRowsList = component.get("v.contactList");
        AllRowsList.splice(index, 1);
        // set the contactList after remove selected row element  
        component.set("v.contactList", AllRowsList);
    },
})

Helper:
({
    createObjectData: function(component, event) {
        // get the contactList from component and add(push) New Object to List  
        var RowItemList = component.get("v.contactList");
        RowItemList.push({
            'sobjectType': 'Contact',
            'FirstName': '',
            'LastName': '',
            'Phone': ''
        });
        
        // set the updated list to attribute (contactList) again            
        component.set("v.contactList", []);      
        component.set("v.contactList", RowItemList);
    },
    
    // helper function for check if first Name is not null/blank on save  
    validateRequired: function(component, event) {
        var isValid = true;
        var allContactRows = component.get("v.contactList");
        for (var indexVar = 0; indexVar < allContactRows.length; indexVar++) {
            if (allContactRows[indexVar].FirstName == '') {
                isValid = false;
                alert('First Name Can\'t be Blank on Row Number ' + (indexVar + 1));
            }
        }
        return isValid;
    },
})

Apex:
public with sharing class AddOrDeleteRowC {
    
    @AuraEnabled
    public static void saveContacts(List<Contact> ListContact){
        Insert ListContact;
    }
}

There's an idea which is active on the success community to include lookup field in lightning component for which you can upvote so that it gets available in the future.

https://success.salesforce.com/ideaView?id=08730000000Dom1AAC

However, you can create a reusable custom lookup and include it in your component to use lookup input field. Please refer to below link which might help you further.

http://sfdcmonkey.com/2017/07/17/re-usable-custom-lookup/

This is a dynamic Re-Usable Lightning Component, you can use it in any component. You just need to pass the objectAPIName, IconName, selected Record and Field Label Name Attribute when using this Custom Lookup component.

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
This was selected as the best answer
abu saleh khan 8abu saleh khan 8
Thank you, khan.