New Batch#100 (10th Nov 2021) - Salesforce Admin + Dev Training (WhatsApp: +91 - 8087988044) :https://t.co/p4F3oeQagK

Friday, 30 August 2019

Datatable Input Form with adding or removing row dynamically (Salesforce Lightning Component)

Live Example -
Datatable Input Form
Apex Class -
public class DatatableInputContrl {
@AuraEnabled
public static Map<String,Object> fetchData(Map<String,Object> inputMap) {
String recordId = (String)inputMap.get('recordId');
Map<String,Object> contrlRes = new Map<String,Object>();
contrlRes.put('records',[select Id, Project__c, Quantity__c, Resource__c, Salary__c from Resource__c
where Project__c =: recordId]);
List<String> options = new List<String>();
for(Schema.PicklistEntry pe : Resource__c.Resource__c.getDescribe().getPicklistValues()) {
options.add(pe.getLabel());
}
contrlRes.put('resourcPickVals',options);
return contrlRes;
}
@AuraEnabled
public static String upsertResources(List<Resource__c> records) {
system.debug('records: '+records);
String msg = '';
try {
system.debug('records: '+records);
List<Resource__c> insertResLst = new List<Resource__c>();
List<Resource__c> updateResLst = new List<Resource__c>();
if(records != null && records.size() > 0) {
for(Resource__c res : records) {
if(res.Id != null) {
updateResLst.add(res);
}
else {
insertResLst.add(res);
}
}
}
if(insertResLst.size() > 0) insert insertResLst;
if(updateResLst.size() > 0) update updateResLst;
system.debug('insertResLst: '+insertResLst);
system.debug('updateResLst: '+updateResLst);
msg = 'Success';
}
catch(Exception e) {
msg = 'Error: '+e.getMessage();
}
return msg;
}
@AuraEnabled
public static String deleteRec(String recId) {
String msg;
Resource__c resource = new Resource__c(Id = recid);
try {
delete resource;
msg = 'Success';
}
catch(Exception e) {
msg = 'Error: '+e.getMessage();
}
return msg;
}
}
----------------
Component -
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" controller="DatatableInputContrl">
<aura:attribute name="records" type="List"/>
<aura:attribute name="resourcPickVals" type="List"/>
<aura:attribute name="isSpinner" type="Boolean" default="false"/>
<aura:attribute name="title" type="String" default="Resources Estimation"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<div class="slds-section slds-is-open" id="titleOfTable">
<h3 class="slds-section__title slds-theme_shade">
<span class="slds-truncate slds-p-horizontal_small" title="Section Title">
{!v.title}
</span>
</h3>
</div>
<aura:if isTrue="{!v.isSpinner}">
<lightning:spinner alternativeText="Loading" size="medium" />
</aura:if>
<table class="slds-table slds-table_cell-buffer slds-table_bordered">
<thead>
<tr class="slds-line-height_reset">
<th class="" scope="col">
<div class="slds-truncate" title="Resource">Resource</div>
</th>
<th class="" scope="col">
<div class="slds-truncate" title="Salary">Salary</div>
</th>
<th class="" scope="col">
<div class="slds-truncate" title="Quantity">Quantity</div>
</th>
<th class="" scope="col">
<lightning:button label="Add" title="Add" onclick="{! c.add }"/>
<lightning:button variant="brand" label="save" title="Save" onclick="{! c.save }" />
</th>
</tr>
</thead>
<tbody>
<aura:iteration items="{!v.records}" var="record" indexVar="index">
<tr class="slds-hint-parent">
<td data-label="Resource">
<lightning:select name="Resource" label="Resource" variant="label-hidden" value="{!record.Resource__c}">
<aura:iteration items="{!v.resourcPickVals}" var="pickVal">
<option value="{!pickVal}">{!pickVal}</option>
</aura:iteration>
</lightning:select>
</td>
<td data-label="Salary">
<lightning:input type="number" name="Salary" label="Salary" value="{!record.Salary__c}" formatter="currency" step="0.01" variant="label-hidden"/>
</td>
<td data-label="Quantity">
<lightning:input type="number" name="Quantity" label="Quantity" variant="label-hidden" value="{!record.Quantity__c}"/>
</td>
<td data-label="Delete">
<a href="" id="{!index+':'+record.Id}" onclick="{!c.delete}">
<lightning:icon iconName="utility:delete" alternativeText="delete" variant="error"/>
</a>
</td>
</tr>
</aura:iteration>
</tbody>
</table>
<div class="slds-box">
<div class="demo-only" style="padding:0.5rem;background:#16325c">
<div class="slds-text-color_inverse">For the more variations, please refer -</div>
</div><br/>
<div class="slds-p-left_large">
<ol class="slds-list_ordered">
<li><a href="http://www.salesforce-interviewquestions.com/2019/08/datatable-input-form-with-adding-or.html">Datatable InputForm Component Logic</a></li>
</ol>
</div>
</div>
<c:FooterComponent />
</aura:component>
-----------------
Controller JS -
({
doInit : function(cmp, event, helper) {
helper.handleDoInit(cmp,event);
},
add : function(cmp, event, helper) {
var records = cmp.get("v.records");
records.push({'Resource__c':'','Salary__c':0,'Quantity__c':0,'sobjectType': 'Resource__c','Project__c':cmp.get("v.recordId")});
cmp.set("v.records",records);
},
delete : function(cmp, event, helper) {
cmp.set("v.isSpinner",true);
if(event.target) {
var elmtId = event.target.id;
console.log(elmtId);
var ids = elmtId.split(":");
var records = cmp.get("v.records");
records.splice(ids[0],1);
cmp.set("v.records",records);
//Deleting form server
if(ids.length > 1 && ids[1]) {
var recId = ids[1];
console.log(recId);
var action = cmp.get("c.deleteRec");
action.setParams({
recId : recId
});
action.setCallback(this,function(response){
cmp.set("v.isSpinner",false);
var state = response.getState();
if(state === 'SUCCESS') {
console.log(response.getReturnValue());
}
});
$A.enqueueAction(action);
}
else {
cmp.set("v.isSpinner",false);
}
}
},
save: function(cmp, event, helper) {
helper.handleSave(cmp, event)
}
})
------------------------
Helper JS -
({
handleDoInit : function(cmp,event) {
var action = cmp.get("c.fetchData");
var inputMap = {
"recordId": cmp.get("v.recordId")
};
action.setParams({
inputMap:inputMap //inputMap should not be enclosed in double quotes
});
action.setCallback(this,function(response){
var state = response.getState();
if(state === "SUCCESS") {
var res = response.getReturnValue();
var records = res.records;
if(records.length == 0) {
records.push({'Resource__c':'','Salary__c':0,'Quantity__c':0,'sobjectType': 'Resource__c','Project__c':cmp.get("v.recordId")});
}
cmp.set("v.records",records);
cmp.set("v.resourcPickVals",res.resourcPickVals);
}
else {
alert('Something went wrong...');
}
});
$A.enqueueAction(action);
},
handleSave : function(cmp, event) {
cmp.set("v.isSpinner",true);
var action = cmp.get("c.upsertResources");
var records = cmp.get("v.records");
console.log(JSON.stringify(records));
action.setParams({
"records" : records
});
action.setCallback(this,function(response){
cmp.set("v.isSpinner",false);
debugger;
var state = response.getState();
if(state == 'SUCCESS') {
var res = response.getReturnValue();
console.log('after save: '+res);
this.handleDoInit(cmp, event);
/*var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
"title": "Success!",
"message": "The records have been updated successfully.",
"type" : "success"
});
toastEvent.fire();*/ //Only working in lighting exeprience
}
});
//To call the server method (Asynchronous)
$A.enqueueAction(action);
}
})
-----------------------------------
CSS -
.THIS {
}
.THIS label {
display:none;
}

Live Demo -

Datatable Input Form

No comments:

Post a Comment