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
Surya PSurya P 

How to create multiple Contacts for an Account from account detail page using quick action or button in Lightning?

I have created Lightning componet and added the component as quick action on Account object, by using this action I'm able to create contacts but these contacts are not related to the account record. I have also used the interface "force:hasRecordId", but still i could not create contacts related to that particular record.
Kindly help me how to create multiple contact records for a particular account record using lightning components.

Thanks
Surya
Best Answer chosen by Surya P
Devi ChandrikaDevi Chandrika (Salesforce Developers) 
Hi surya,
I have gone through your apex class.In your apex class you are iterating and updating the same list.We cannot modify a list which is being iterated.That is why you are not able to update contact with accountid.

Try below code
public class InsertContactsToAccount {
    
   @AuraEnabled
    public static void saveContacts(List<Contact> listContact, Id recordId)
    {
        list<contact> conlist = new list<contact>();
        Insert listContact;
        for(Contact a:listContact){
            a.AccountId = recordId;
            conlist.add(a);
        }
        update conlist;
    } 
}

​​​​​​​Hope this helps you
Let me know if this helps you. Kindly mark it as solved so that it may help others in future.

Thanks and Regards

All Answers

Devi ChandrikaDevi Chandrika (Salesforce Developers) 
Hi surya,
Can you post your code here.So that i can help you
Surya PSurya P
Hi Devi,
Here is the Code.

Parent Component:
<aura:component controller="InsertContactsToAccount" 
                Implements="flexipage:availableForRecordHome,
                            force:hasRecordId,
                            flexipage:availableForAllPageTypes,
                            force:lightningQuickActionWithoutHeader"> 
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:handler name="DeleteRowEvent" event="c:DeleteRowEvent" action="{!c.removeDeletedRow}"/>
    <aura:handler name="AddNewRowEvent" event="c:AddNewRowEvent" action="{!c.addNewRow}"/>
   
    <aura:attribute name="contactList" type="Contact[]"/> 
      <aura:attribute name="recordId" type="Id" /> 
      
    <div class="slds-page-header">
        <h1 class="slds-page-header__title">Create Contacts</h1>
    </div>
             
    <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>
                <th scope="col">
                    <div class="slds-truncate" title="Email">Email</div>
                </th>
            </tr>
        </thead>   
        <tbody>      
            <aura:iteration items="{!v.contactList}" var="item" indexVar="index">
                <c:AddRowChildComponent ContactInstance="{!item}" rowIndex="{!index}" />
            </aura:iteration>
        </tbody>
    </table>
    <br/>
    <div class="modal-footer slds-modal__footer slds-size_1-of-1">
        <lightning:button class="slds-button slds-button_brand" onclick="{!c.save}">Save</lightning:button>
        <lightning:button variant="Neutral" class="slds-button" label="Cancel" onclick="{!c.handleClose}"/>
    </div>
</aura:component>

Parent Controller:
({
    doInit: function(component, event, helper) { 
        helper.createObjectData(component, event);
    },
    
    save: function(component, event, helper) {
        if (helper.validateRequired(component, event)) {
            var action = component.get("c.saveContacts");
            action.setParams({
                "listContact":component.get("v.contactList"),
                "recordId":component.get("v.recordId")
            });
            action.setCallback(this, function(response) {
                var state = response.getState();
                if (state === "SUCCESS") {
                    component.set("v.contactList", []);
                    helper.createObjectData(component, event);
                    alert('Contact Records are Saved');
                }
            });
            $A.enqueueAction(action);
        }
    },
  
    addNewRow: function(component, event, helper) {
        helper.createObjectData(component, event);
    },
 
    removeDeletedRow: function(component, event, helper) {
        var index = event.getParam("indexVar");    
        var allRowsList = component.get("v.contactList");
        allRowsList.splice(index, 1);
        component.set("v.contactList", allRowsList);
    },
    
    handleClose : function(component, event, helper) {
        $A.get("e.force:closeQuickAction").fire() 
    }
})

Parent Helper:
({
    createObjectData: function(component, event) { 
        var RowItemList = component.get("v.contactList");
        RowItemList.push({
            'sobjectType': 'Contact',
            'FirstName': '',
            'LastName': '',
            'Phone': '',
            'Email': ''
        });  
        component.set("v.contactList", RowItemList);
    },  
    validateRequired: function(component, event) {
        var isValid = true;
        var allContactRows = component.get("v.contactList");
        for (var indexVar = 0; indexVar < allContactRows.length; indexVar++) {
            if (allContactRows[indexVar].LastName == '') {
                isValid = false;
                alert('Last Name Cannot be Blank on Row Number ' + (indexVar + 1));
            }
        }
        return isValid;
    },
})

Apex Class:
public class InsertContactsToAccount {
    
   @AuraEnabled
    public static void saveContacts(List<Contact> listContact, Id recordId)
    {
        Insert listContact;
        for(Contact a:listContact){
            a.AccountId = recordId;
            listContact.add(a);
        }
        update listContact;
    } 
}

I have used this code as reference. Source: http://sfdcmonkey.com/2017/08/09/add-delete-rows-dynamic/#comment-25935

 
Devi ChandrikaDevi Chandrika (Salesforce Developers) 
Hi surya,
I have gone through your apex class.In your apex class you are iterating and updating the same list.We cannot modify a list which is being iterated.That is why you are not able to update contact with accountid.

Try below code
public class InsertContactsToAccount {
    
   @AuraEnabled
    public static void saveContacts(List<Contact> listContact, Id recordId)
    {
        list<contact> conlist = new list<contact>();
        Insert listContact;
        for(Contact a:listContact){
            a.AccountId = recordId;
            conlist.add(a);
        }
        update conlist;
    } 
}

​​​​​​​Hope this helps you
Let me know if this helps you. Kindly mark it as solved so that it may help others in future.

Thanks and Regards
This was selected as the best answer
Surya PSurya P
Thank you Devi. This worked fine.

Regards
Surya
Pooja Singh 157Pooja Singh 157
@surya : can you please share the code for AddRowChildComponent component. I have similar requirement. Thanks.
Surya PSurya P
@Pooja : please find the code for AddRowChildComponent
 
<aura:component >    
    <aura:attribute name="ContactInstance" type="Contact"/>
    <aura:attribute name="rowIndex" type="String"/>
    
    <aura:registerEvent name="DeleteRowEvent" type="c:DeleteRowEvent"/> 
    <aura:registerEvent name="AddNewRowEvent" type="c:AddNewRowEvent"/> 
      
    <tr class="slds-text-title_caps">
        <td> 
            {!v.rowIndex + 1}
        </td>
        <td>
            <ui:inputText class="slds-input" value="{!v.ContactInstance.FirstName}"/>
        </td>
        <td>
            <ui:inputText class="slds-input" value="{!v.ContactInstance.LastName}"/>
        </td>
        
        <td>
            <ui:inputPhone class="slds-input" value="{!v.ContactInstance.Phone}"/>
        </td>
        <td>
            <ui:inputPhone class="slds-input" value="{!v.ContactInstance.Email}"/>
        </td>
        <td>
            <aura:if isTrue="{!v.rowIndex == 0}">
                    <a onclick="{!c.addRow}">
                      <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.addRow}">
                          <lightning:icon iconName="utility:add" class="slds-icon slds-icon_small" size="small" alternativeText="add"/>
                          <span class="slds-assistive-text">Add Icon</span>
                        </a> 
                       <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>
 
({
    addRow : function(component, event, helper){
        component.getEvent("AddNewRowEvent").fire();     
    },
    
    removeRow : function(component, event, helper){
       component.getEvent("DeleteRowEvent").setParams({
           "indexVar" : component.get("v.rowIndex") 
       }).fire();
    }, 
})