+ Start a Discussion
Dharmendra Kumar 60Dharmendra Kumar 60 

I need to create related contacts records when pressing the "create contacts" button on the each rows of the datatable. How to create a lightning component for this ..Please help

User-added image
Best Answer chosen by Dharmendra Kumar 60
Khan AnasKhan Anas (Salesforce Developers) 
Hi Dharmendra,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Apex:
public class DatatableActionC {
    
    @AuraEnabled
    public static List < Account > fetchAccts() {
        return [ SELECT Id, Name, Industry, Type FROM Account LIMIT 10 ];
    }
    
    @AuraEnabled
    public static void saveDetails (Contact regForm1, String recordId){ 
        regForm1.AccountId = recordId;
        INSERT regForm1;
    }
}

Component:
<aura:component controller="DatatableActionC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <aura:attribute type="Account[]" name="acctList"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:attribute name="accForm" type="Contact" default="{'sobjectType' : 'Contact'}"/>
    <aura:attribute name ="accName" type="String" />
    <aura:attribute name ="accId" type="String" />
    
    <aura:handler name="init" value="{!this}" action="{!c.fetchAccounts}"/>
    
    <lightning:datatable data="{! v.acctList }" 
                         columns="{! v.mycolumns }" 
                         keyField="id"
                         hideCheckboxColumn="true"
                         onrowaction="{!c.viewRecord}"/>
    
    <div role="dialog" tabindex="-1" aria-labelledby="header43" aura:id="Modalbox1" class="slds-modal slds-modal_large">
        <div class="slds-modal__container" style="width: 65%;">
            <div class="slds-modal__header">
                CONTACT
            </div>
            
            <div aura:id="mid" class="slds-modal__content slds-p-around--medium">
                <div class="slds-p-left_xx-large slds-p-right_xx-large">
                    <div class="slds-page-header" style="padding-top: 9px; padding-bottom: 9px;, padding-right: 9px;, padding-left: 10px;">
                        <h3 style="font-size: 1rem;" title="">Contact Information</h3>
                    </div> 
                </div>    
                <div class="slds-grid slds-p-top_medium">
                    <div class="slds-size_6-of-12 slds-p-left_xx-large slds-p-horizontal_x-large " >
                        Account Name: <ui:outputText value="{!v.accName}"/> 
                    </div>
                    <div class="slds-size_5-of-12 slds-p-left_xx-small slds-p-horizontal_x-large " >
                        Account Id: <ui:outputText value="{!v.accId}"/>
                    </div>
                </div>
                <div class="slds-grid slds-p-top_medium">
                    <div class="slds-size_6-of-12 slds-p-left_xx-large slds-p-horizontal_x-large " >
                        <lightning:input label="First Name" name="myfirst" value="{!v.accForm.FirstName}"/> 
                    </div>
                    <div class="slds-size_5-of-12 slds-p-left_xx-small slds-p-horizontal_x-large " >
                        <lightning:input required="true" label="Last Name" name="mylast" value="{!v.accForm.LastName}"/> 
                    </div>
                </div>
                <div class="slds-grid slds-p-top_x-small">
                    <div class="slds-size_6-of-12 slds-p-left_xx-large slds-p-horizontal_x-large " >
                        <lightning:input label="Phone" name="myphone" value="{!v.accForm.Phone}"/> 
                    </div>
                    <div class="slds-size_5-of-12 slds-p-left_xx-small slds-p-horizontal_x-large " >
                        <lightning:input label="Email" name="myemail" value="{!v.accForm.Email}"/> 
                    </div>
                </div>
            </div>
            <div class="slds-modal__footer">
                <lightning:button label="Save" onclick="{!c.saveModal}" />
                <lightning:button label="Close" onclick="{!c.closeNewModal}" />
            </div>
        </div>
    </div>
</aura:component>

Controller:
({
    fetchAccounts : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Account Name', fieldName: 'Name', type: 'text'},
            {label: 'Industry', fieldName: 'Industry', type: 'text'},
            {label: 'Type', fieldName: 'Type', type: 'Text'},
            {type: "button", typeAttributes: {
                label: 'View',
                name: 'View',
                title: 'View',
                disabled: false,
                value: 'view',
                iconPosition: 'left'
            }},
            {type: "button", typeAttributes: {
                label: 'Create Contact',
                name: 'Create Contact',
                title: 'Create Contact',
                disabled: false,
                value: 'edit',
                iconPosition: 'left'
            }}
        ]);
        var action = component.get("c.fetchAccts");
        action.setParams({
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.acctList", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },
    
    viewRecord : function(component, event, helper) {
        var recName = event.getParam('row').Name;
        var recId = event.getParam('row').Id;
        var actionName = event.getParam('action').name;
        if ( actionName == 'Create Contact' ) {
            component.set('v.accName',recName);
            component.set('v.accId',recId);
            var cmpTarget = component.find('Modalbox1');
            var cmpBack = component.find('Modalbackdrop');
            $A.util.addClass(cmpTarget, 'slds-fade-in-open');
            $A.util.addClass(cmpBack, 'slds-backdrop--open');
        } 
        else if ( actionName == 'View') {
            var row = event.getParam('row');
            alert('You have selected View Action for '+row.Name+'(id='+row.Id+')');
        }
    },
    
    saveModal : function(component, event, helper){
        var regForm = component.get("v.accForm");
        var rid = component.get('v.accId');
        var action = component.get("c.saveDetails");
        action.setParams({regForm1  : regForm, recordId : rid});
        action.setCallback(this, function(response) {
            var state = response.getState();          
            if (state === "SUCCESS") {
                var cmpTarget = component.find('Modalbox1');
                var cmpBack = component.find('Modalbackdrop');
                $A.util.removeClass(cmpBack,'slds-backdrop--open');
                $A.util.removeClass(cmpTarget, 'slds-fade-in-open');
                
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                    errors[0].message);
                    }
                } 
                else {
                    console.log(response.getReturnValue());
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    closeNewModal : function(component, event, helper){
        component.set("v.accForm",{'LastName':''});
        var cmpTarget = component.find('Modalbox1');
        var cmpBack = component.find('Modalbackdrop');
        $A.util.removeClass(cmpBack,'slds-backdrop--open');
        $A.util.removeClass(cmpTarget, 'slds-fade-in-open');
    },
})

CSS:
.THIS {
}

.THIS .slds-section__title{
    background-color: YellowGreen;
    color: white
}
.THIS .slds-modal__header{
    background-color: OliveDrab;
    color: white
}

Application:
<aura:application extends="force:slds">
    <c:DatatableAction/>
</aura:application>

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 Dharmendra,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Apex:
public class DatatableActionC {
    
    @AuraEnabled
    public static List < Account > fetchAccts() {
        return [ SELECT Id, Name, Industry, Type FROM Account LIMIT 10 ];
    }
    
    @AuraEnabled
    public static void saveDetails (Contact regForm1, String recordId){ 
        regForm1.AccountId = recordId;
        INSERT regForm1;
    }
}

Component:
<aura:component controller="DatatableActionC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <aura:attribute type="Account[]" name="acctList"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:attribute name="accForm" type="Contact" default="{'sobjectType' : 'Contact'}"/>
    <aura:attribute name ="accName" type="String" />
    <aura:attribute name ="accId" type="String" />
    
    <aura:handler name="init" value="{!this}" action="{!c.fetchAccounts}"/>
    
    <lightning:datatable data="{! v.acctList }" 
                         columns="{! v.mycolumns }" 
                         keyField="id"
                         hideCheckboxColumn="true"
                         onrowaction="{!c.viewRecord}"/>
    
    <div role="dialog" tabindex="-1" aria-labelledby="header43" aura:id="Modalbox1" class="slds-modal slds-modal_large">
        <div class="slds-modal__container" style="width: 65%;">
            <div class="slds-modal__header">
                CONTACT
            </div>
            
            <div aura:id="mid" class="slds-modal__content slds-p-around--medium">
                <div class="slds-p-left_xx-large slds-p-right_xx-large">
                    <div class="slds-page-header" style="padding-top: 9px; padding-bottom: 9px;, padding-right: 9px;, padding-left: 10px;">
                        <h3 style="font-size: 1rem;" title="">Contact Information</h3>
                    </div> 
                </div>    
                <div class="slds-grid slds-p-top_medium">
                    <div class="slds-size_6-of-12 slds-p-left_xx-large slds-p-horizontal_x-large " >
                        Account Name: <ui:outputText value="{!v.accName}"/> 
                    </div>
                    <div class="slds-size_5-of-12 slds-p-left_xx-small slds-p-horizontal_x-large " >
                        Account Id: <ui:outputText value="{!v.accId}"/>
                    </div>
                </div>
                <div class="slds-grid slds-p-top_medium">
                    <div class="slds-size_6-of-12 slds-p-left_xx-large slds-p-horizontal_x-large " >
                        <lightning:input label="First Name" name="myfirst" value="{!v.accForm.FirstName}"/> 
                    </div>
                    <div class="slds-size_5-of-12 slds-p-left_xx-small slds-p-horizontal_x-large " >
                        <lightning:input required="true" label="Last Name" name="mylast" value="{!v.accForm.LastName}"/> 
                    </div>
                </div>
                <div class="slds-grid slds-p-top_x-small">
                    <div class="slds-size_6-of-12 slds-p-left_xx-large slds-p-horizontal_x-large " >
                        <lightning:input label="Phone" name="myphone" value="{!v.accForm.Phone}"/> 
                    </div>
                    <div class="slds-size_5-of-12 slds-p-left_xx-small slds-p-horizontal_x-large " >
                        <lightning:input label="Email" name="myemail" value="{!v.accForm.Email}"/> 
                    </div>
                </div>
            </div>
            <div class="slds-modal__footer">
                <lightning:button label="Save" onclick="{!c.saveModal}" />
                <lightning:button label="Close" onclick="{!c.closeNewModal}" />
            </div>
        </div>
    </div>
</aura:component>

Controller:
({
    fetchAccounts : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Account Name', fieldName: 'Name', type: 'text'},
            {label: 'Industry', fieldName: 'Industry', type: 'text'},
            {label: 'Type', fieldName: 'Type', type: 'Text'},
            {type: "button", typeAttributes: {
                label: 'View',
                name: 'View',
                title: 'View',
                disabled: false,
                value: 'view',
                iconPosition: 'left'
            }},
            {type: "button", typeAttributes: {
                label: 'Create Contact',
                name: 'Create Contact',
                title: 'Create Contact',
                disabled: false,
                value: 'edit',
                iconPosition: 'left'
            }}
        ]);
        var action = component.get("c.fetchAccts");
        action.setParams({
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.acctList", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },
    
    viewRecord : function(component, event, helper) {
        var recName = event.getParam('row').Name;
        var recId = event.getParam('row').Id;
        var actionName = event.getParam('action').name;
        if ( actionName == 'Create Contact' ) {
            component.set('v.accName',recName);
            component.set('v.accId',recId);
            var cmpTarget = component.find('Modalbox1');
            var cmpBack = component.find('Modalbackdrop');
            $A.util.addClass(cmpTarget, 'slds-fade-in-open');
            $A.util.addClass(cmpBack, 'slds-backdrop--open');
        } 
        else if ( actionName == 'View') {
            var row = event.getParam('row');
            alert('You have selected View Action for '+row.Name+'(id='+row.Id+')');
        }
    },
    
    saveModal : function(component, event, helper){
        var regForm = component.get("v.accForm");
        var rid = component.get('v.accId');
        var action = component.get("c.saveDetails");
        action.setParams({regForm1  : regForm, recordId : rid});
        action.setCallback(this, function(response) {
            var state = response.getState();          
            if (state === "SUCCESS") {
                var cmpTarget = component.find('Modalbox1');
                var cmpBack = component.find('Modalbackdrop');
                $A.util.removeClass(cmpBack,'slds-backdrop--open');
                $A.util.removeClass(cmpTarget, 'slds-fade-in-open');
                
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                    errors[0].message);
                    }
                } 
                else {
                    console.log(response.getReturnValue());
                }
            }
        });
        $A.enqueueAction(action);
    },
    
    closeNewModal : function(component, event, helper){
        component.set("v.accForm",{'LastName':''});
        var cmpTarget = component.find('Modalbox1');
        var cmpBack = component.find('Modalbackdrop');
        $A.util.removeClass(cmpBack,'slds-backdrop--open');
        $A.util.removeClass(cmpTarget, 'slds-fade-in-open');
    },
})

CSS:
.THIS {
}

.THIS .slds-section__title{
    background-color: YellowGreen;
    color: white
}
.THIS .slds-modal__header{
    background-color: OliveDrab;
    color: white
}

Application:
<aura:application extends="force:slds">
    <c:DatatableAction/>
</aura:application>

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
Dharmendra Kumar 60Dharmendra Kumar 60
Hi Anas,
Thanks for the help.
Is there a way to just redirect to the new contact standard page when "Create contact" is pressed ?
Khan AnasKhan Anas (Salesforce Developers) 
Hi Dharmendra,

You can use force:createRecord event. This event opens a page to create a record for the specified entityApiName. 

Also, note that you cannot use this event in the lightning app, you need to place it on the record page. This event is handled by the one.app container. It’s supported in Lightning Experience, the Salesforce app, and Lightning communities. This event presents a standard page to create a record. That is, it doesn’t respect overrides on the object’s create action.

https://developer.salesforce.com/docs/component-library/bundle/force:createRecord/documentation

Please try the below code.

Apex:
public class DatatableActionStandardC {
    
    @AuraEnabled
    public static List < Account > fetchAccts() {
        return [ SELECT Id, Name, Industry, Type FROM Account LIMIT 10 ];
    }
}



Component:
<aura:component controller="DatatableActionStandardC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <aura:attribute type="Account[]" name="acctList"/>
    <aura:attribute name="mycolumns" type="List"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.fetchAccounts}"/>
    
    <lightning:datatable data="{! v.acctList }" 
                         columns="{! v.mycolumns }" 
                         keyField="id"
                         hideCheckboxColumn="true"
                         onrowaction="{!c.viewRecord}"/>
</aura:component>

Controller:
({
    fetchAccounts : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Account Name', fieldName: 'Name', type: 'text'},
            {label: 'Industry', fieldName: 'Industry', type: 'text'},
            {label: 'Type', fieldName: 'Type', type: 'Text'},
            {type: "button", typeAttributes: {
                label: 'View',
                name: 'View',
                title: 'View',
                disabled: false,
                value: 'view',
                iconPosition: 'left'
            }},
            {type: "button", typeAttributes: {
                label: 'Create Contact',
                name: 'Create Contact',
                title: 'Create Contact',
                disabled: false,
                value: 'edit',
                iconPosition: 'left'
            }}
        ]);
        var action = component.get("c.fetchAccts");
        action.setParams({
        });
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.acctList", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },
    viewRecord : function(component, event, helper) {
        var recId = event.getParam('row').Id;
        var actionName = event.getParam('action').name;
        if ( actionName == 'Create Contact' ) {
            var createRecordEvent = $A.get("e.force:createRecord");
            createRecordEvent.setParams({
                "entityApiName": "Contact",
                "defaultFieldValues": {
                    'AccountId' : recId
                }
            });
            createRecordEvent.fire();
        } 
        else if ( actionName == 'View') {
            var viewRecordEvent = $A.get("e.force:navigateToURL");
            viewRecordEvent.setParams({
                "url": "/" + recId
            });
            viewRecordEvent.fire();
        }
    }
    
})

I hope it helps you.

Kindly mark this as solved if the information was helpful. It will help to keep this community clean.

Regards,
Khan Anas
Dharmendra Kumar 60Dharmendra Kumar 60
Thanks Anas for the help . You completely undestood my point , it is a great favour .