Pages

Wednesday, 4 September 2019

Missing Fields Request Creation Lightning Component which is using Record Edit Form and Custom Events Salesforce

Lightning Events -
1. NotifyCloseCasePopupEvent
2. NotifyCloseCasePopupAppEvent
Lightning Components -
1. CasePopup.cmp
2. MissingFieldsRequestCreation.cmp
Main Component -
MissingFieldsRequestCreation.cmp
Apex Classes -
1. Utility
2. CasePopupContrl
3. ProjectMissingFieldsSerContrl
Utility Class -
-------
public class Utility {
public static SObject createDynamicObject(String objectApiName) {
return (SObject)Type.forName(objectApiName).newInstance();
}
public static List<SObject> createDynamicList4object(String objectApiName) {
return (List<SObject>)Type.forName('List<'+objectApiName+'>').newInstance();
}
/*** Usage ***
List<SObject> recs = Utility.createDynamicList4object('Contact');
SObject rec1 = Utility.createDynamicObject('Contact');
rec1.put('LastName','March2017-3');
SObject rec2 = Utility.createDynamicObject('Contact');
rec2.put('LastName','March2017-4');
recs.add(rec1);
recs.add(rec2);
insert recs;
*/
//Method which accepts object name and field setname. It will return the fields seperated by commna in string format
public static String getFieldsStr(String objectApiName, String fieldsetName) {
String fieldsToQuery = '';
for(Schema.FieldSetMember fsm : getFieldsOfFieldset(objectApiName, fieldsetName)) {
if(String.isBlank(fieldsToQuery))
fieldsToQuery = fsm.getFieldPath();
else
fieldsToQuery += ','+fsm.getFieldPath();
}
system.debug('***fieldsToQuery: '+fieldsToQuery);
return fieldsToQuery;
}
public static List<Schema.FieldSetMember> getFieldsOfFieldset(String objectApiName, String fieldsetName) {
List<Schema.FieldSetMember> fieldsetFields = new List<Schema.FieldSetMember>(
Schema.getGlobalDescribe().get(objectApiName).getDescribe().FieldSets.getMap().get(fieldsetName).getFields()
);
return fieldsetFields;
}
public static String getQueryStr(String objectApiName,String fieldsToQuery, String whereCaluse) {
return 'Select '+fieldsToQuery+' from '+objectApiName+whereCaluse;
}
//To get the picklist values based on the object api name and field api name
public static List<String> getPicklistValues(String objectApiName, String fieldApiName) {
List<String> options = new List<String>();
for(Schema.PicklistEntry pickEntry : Schema.getGlobalDescribe().get(objectApiName).getDescribe().fields.getMap().get(fieldApiName).getDescribe().getPickListValues()) {
options.add(pickEntry.getLabel());
}
return options;
}
}
NotifyCloseCasePopupEvent -
--------------------------
<aura:event type="COMPONENT" description="To notify parent to hide the popup.">
<aura:attribute name="showPopup" type="Boolean" default="false"/>
</aura:event>
NotifyCloseCasePopupAppEvent -
--------------------------
<aura:event type="APPLICATION">
<aura:attribute name="showPopup" type="Boolean" default="false"/>
</aura:event>
CasePopup Lightning Component -
------------------------------
Apex Class -
public class CasePopupContrl {
@AuraEnabled
public static Map<String,Object> initData(Map<String,Object> inputParams) {
String objectApiName = (String)inputParams.get('objectApiName'),
fieldsetName = (String)inputParams.get('fieldsetName');
Map<String,Object> contrlResp = new Map<String,Object>();
List<FieldInfo> fields = new List<FieldInfo>();
for(Schema.FieldSetMember fsm : Utility.getFieldsOfFieldset(objectApiName,fieldsetName)) {
FieldInfo fInfo = new FieldInfo();
fInfo.label = fsm.getLabel();
fInfo.fieldName = fsm.getFieldPath();
fInfo.type = fsm.getType().name();
fields.add(fInfo);
}
contrlResp.put('fields',fields);
return contrlResp;
}
public class FieldInfo {
@AuraEnabled
public String label;
@AuraEnabled
public String fieldName;
@AuraEnabled
public String type;
@AuraEnabled
public List<String> options;
}
}
Component UI -
<aura:component controller="CasePopupContrl">
<aura:attribute name="fieldsetName" type="String" required="true"/>
<aura:attribute name="objectApiName" type="String" required="true"/>
<aura:attribute name="parentId" type="String"/>
<aura:attribute name="fields" type="List"/>
<aura:attribute name="headerMsg" type="String"/>
<aura:attribute name="selectedRows" type="Object"/>
<aura:handler name="init" value="{!this}" action="{!c.init}"/>
<!-- Component Event -->
<aura:registerEvent name="caseClsPopupCompEvent" type="c:NotifyCloseCasePopupEvent"/>
<!-- Application Event -->
<aura:registerEvent name="NotifyCloseCasePopupAppEvent" type="c:NotifyCloseCasePopupAppEvent"/>
<aura:method name="hMsgMethod" action="{!c.doAction}" description="Sample method with parameters">
<aura:attribute name="param1" type="String" default="parameter 1"/>
</aura:method>
<div class="demo-only" style="height: 640px;">
<section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" aria-describedby="modal-content-id-1" class="slds-modal slds-fade-in-open">
<div class="slds-modal__container">
<header class="slds-modal__header">
<lightning:buttonIcon iconName="utility:close" variant="container" alternativeText="close" class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" size="large" onclick="{!c.closePopup}"/>
<h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">
New Case Request for the Project Missing Fields
</h2>
</header>
<div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
<div class="slds-p-bottom_large slds-p-left_large" style="width:500px">
<lightning:recordEditForm aura:id="recordEditForm"
onsubmit="{!c.handleSubmit}"
onsuccess="{!c.handleSuccess}"
onerror = "{!c.handleError}"
objectApiName="{!v.objectApiName}">
<lightning:messages />
<aura:iteration items="{!v.fields}" var="fld">
<aura:if isTrue="{!fld.fieldName == 'Project__c'}">
<lightning:inputField fieldName="{!fld.fieldName}" value="{!v.parentId}"/>
<aura:set attribute="else">
<lightning:inputField fieldName="{!fld.fieldName}"/>
</aura:set>
</aura:if>
</aura:iteration>
<lightning:button aura:id="submit" type="submit" label="Save" class="slds-m-top_medium slds-button slds-button_brand" />
</lightning:recordEditForm>
</div>
</div>
</div>
</section>
<div class="slds-backdrop slds-backdrop_open"></div>
</div>
</aura:component>
Controller Js -
({
init : function(cmp, event, helper) {
var action = cmp.get("c.initData");
var inputMap = {
"objectApiName" : cmp.get("v.objectApiName"),
"fieldsetName" : cmp.get("v.fieldsetName")
};
action.setParams({
inputParams : inputMap
});
action.setCallback(this,function(response){
debugger;
var state = response.getState();
if(state == "SUCCESS") {
var res = response.getReturnValue();
console.log('fields: '+JSON.stringify(res['fields']));
cmp.set("v.fields",res.fields);
}
else {
alert('error.');
}
});
$A.enqueueAction(action);
},
doAction : function(cmp, event, helper) {
debugger;
var params = event.getParam('arguments');
if (params) {
var param1 = params.param1;
alert(param1);
cmp.set("v.headerMsg",param1+' From Child Component.');
}
},
handleSubmit : function(cmp, event, helper) {
event.preventDefault(); // stop the form from submitting
var fields = event.getParam('fields');
var missingInfo = cmp.get("v.selectedRows");
console.log('missingInfo: '+JSON.stringify(missingInfo));
fields['Missing_Fields_Json__c'] = JSON.stringify(missingInfo);
console.log('fields: '+JSON.stringify(fields));
cmp.find('recordEditForm').submit(fields);
},
handleSuccess : function(cmp, event, helper) {
var payload = event.getParams().response;
console.log(JSON.stringify(payload));
/*var urlEvent = $A.get("e.force:navigateToURL");
urlEvent.setParams({
"url": "/"+payload.id
});
urlEvent.fire();*/ //this will only work in lightning experience
if(confirm('Are you sure you want to see case detail?')) {
window.location.replace('/apex/CaseDetail?id='+payload.id);
}
},
handleSuccess : function(cmp, event, helper) {
var payload = event.getParams().response;
alert('You cannot edit the case. I cannot give edit access to the case. It supposed to save -');
var missingInfo = cmp.get("v.selectedRows");
console.log('missingInfo: '+JSON.stringify(missingInfo));
alert(JSON.stringify(missingInfo));
window.location.replace('/apex/CaseDetail?id='+payload.id);
},
closePopup : function(cmp, event, helper) {
var compEvent = cmp.getEvent("caseClsPopupCompEvent");
compEvent.setParams({"showPopup" : false});
compEvent.fire();
var appEvent = $A.get("e.c:NotifyCloseCasePopupAppEvent");
appEvent.setParams({"showPopup" : false});
appEvent.fire();
}
})
MissingFieldsRequestCreation Lightning Component -
--------------------------------------------------
Apex Class -
public class ProjectMissingFieldsSerContrl {
@AuraEnabled
public static Map<String,Object> initData(Map<String,Object> inputParams) {
//String recId, String objectApiName, String fieldsetName
String recId = (String)inputParams.get('recId'),
objectApiName = (String)inputParams.get('objectApiName'),
fieldsetName = (String)inputParams.get('fieldsetName'),
fieldsToQuery = Utility.getFieldsStr(objectApiName,fieldsetName),
whereCaluse = ' where id = \''+recId+'\'',
query = Utility.getQueryStr(objectApiName,fieldsToQuery, whereCaluse);
system.debug('query: '+query);
Map<String,Object> contrlRes = new Map<String,Object>();
List<Sobject> sobjLst = Database.query(query);
List<FieldInfo> fieldsInfoLst = new List<FieldInfo>();
for(Schema.FieldSetMember fsm : Utility.getFieldsOfFieldset(objectApiName, fieldsetName)) {
FieldInfo fInfo = new FieldInfo();
fInfo.label = fsm.getLabel();
fInfo.fieldName = fsm.getFieldPath();
fInfo.type = fsm.getType().name();
if(fInfo.type == 'PICKLIST') {
fInfo.options = Utility.getPicklistValues(objectApiName,fInfo.fieldName);
}
fieldsInfoLst.add(fInfo);
}
List<RecInfo> recInLst = new List<RecInfo>();
if(sobjLst != null && sobjLst.size() > 0) {
for( FieldInfo fi : fieldsInfoLst) {
String val = (String)sobjLst[0].get(fi.fieldName);
if(String.isBlank(val)) {
RecInfo rInfo = new RecInfo();
rInfo.fieldLabel = fi.label;
rInfo.fieldApiName = fi.fieldName;
rInfo.dataType = fi.type;
rInfo.options = fi.options;
recInLst.add(rInfo);
}
}
}
contrlRes.put('records',recInLst);
//contrlRes.put('fields',JSON.serialize(fieldsInfoLst)); --> not working
FieldInfo fi1 = new FieldInfo();
fi1.label = 'Field Label';
fi1.fieldName = 'fieldLabel';
fi1.type = 'TEXT';
FieldInfo fi2 = new FieldInfo();
fi2.label = 'Field Api Name';
fi2.fieldName = 'fieldApiName';
fi2.type = 'TEXT';
List<FieldInfo> fieldsInfoModifiedLst = new List<FieldInfo>{fi1,fi2};
contrlRes.put('fields',fieldsInfoModifiedLst);
system.debug('***contrlRes: '+contrlRes);
return contrlRes;
}
public class RecInfo {
@AuraEnabled
public String fieldLabel;
@AuraEnabled
public String fieldApiName;
@AuraEnabled
public String dataType;
@AuraEnabled
public List<String> options;
}
public class FieldInfo {
@AuraEnabled
public String label;
@AuraEnabled
public String fieldName;
@AuraEnabled
public String type;
@AuraEnabled
public List<String> options;
}
}
UI -
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" controller="ProjectMissingFieldsSerContrl">
<aura:attribute name="data" type="Object"/>
<aura:attribute name="columns" type="List"/>
<aura:attribute name="objectApiName" type="String" default="Project__c" required="true"/>
<aura:attribute name="fieldsetName" type="String" default="Project_Key_Fields" required="true"/>
<aura:attribute name="headerMsg" type="String" default="Missing Fields Table"/>
<aura:attribute name="selectedRows" type="Object"/>
<aura:attribute name="showPopup" type="Boolean" default="false"/>
<!-- handlers-->
<aura:handler name="init" value="{! this }" action="{! c.init }"/>
<!-- Handling Component Event -->
<aura:handler name="caseClsPopupCompEvent" event="c:NotifyCloseCasePopupEvent" action="{!c.closePopup}"/>
<!-- Handling Application Event -->
<aura:handler event="c:NotifyCloseCasePopupAppEvent" action="{!c.closePopup}"/>
<div>
<div align="left" class="slds-m-left_medium">
<h1 class="slds-section__title slds-theme_shade">{!v.headerMsg}</h1>
<lightning:button label="Change Header" title="Change Header" onclick="{! c.changeHeader}" />
</div>
<div align="right" class="slds-m-right_medium">
<lightning:button variant="brand" label="Create Request" title="Create Request" onclick="{! c.handleRequest}" disabled="{!if(v.selectedRows.length > 0,false,true)}"/>
</div>
</div>
<!-- the container element determine the height of the datatable -->
<div style="height: 300px">
<lightning:datatable
keyField="id"
data="{! v.data }"
columns="{! v.columns }"
hideCheckboxColumn="false"
onrowselection="{! c.getSelectedName }"/>
</div>
<aura:if isTrue="{!v.showPopup}">
<c:CasePopup objectApiName="Case" fieldsetName="CasePopupFields" aura:id="child1" headerMsg = "{#v.headerMsg}" parentId="{!v.recordId}" selectedRows="{!v.selectedRows}"/>
</aura:if>
</aura:component>
Controller Js -
({
init: function (cmp, event, helper) {
helper.handleInit(cmp,event);
},
getSelectedName : function (cmp, event, helper) {
var selectedRows = event.getParam('selectedRows');
console.log('***'+JSON.stringify(selectedRows));
cmp.set("v.selectedRows",selectedRows);
},
handleRequest : function (cmp, event, helper) {
cmp.set("v.showPopup",true);
},
closePopup : function (cmp, event, helper) {
var param = event.getParam("showPopup");
console.log('**'+JSON.stringify(param));
cmp.set("v.showPopup",param);
},
changeHeader : function (cmp, event, helper) {
debugger;
//Calling aura:method in child comp
var child1Cmp = cmp.find("child1");
child1Cmp.hMsgMethod(cmp.get("v.headerMsg"));
}
})
Helper Js -
({
handleInit : function(cmp,event) {
debugger;
var action = cmp.get("c.initData");
var inputMap = {
"recId" : cmp.get("v.recordId"),
"objectApiName" : cmp.get("v.objectApiName"),
"fieldsetName" : cmp.get("v.fieldsetName")
};
action.setParams({
inputParams : inputMap
});
action.setCallback(this,function(response){
debugger;
var state = response.getState();
if(state == "SUCCESS") {
var res = response.getReturnValue();
console.log('fields: '+res['fields']);
cmp.set("v.columns",res.fields);
//cmp.set('v.columns', [{label: 'Name', fieldName: 'Name__c', type: 'text'}]);
console.log('records: '+JSON.stringify(res.records));
cmp.set("v.data",res.records);
}
else {
alert('error.');
}
});
$A.enqueueAction(action);
}
})

Live Demo -

Missing Fields Request Creation

1 comment:

  1. This is amazing, thank you for the share. Also, check this out if you are looking for professional website or logo design services:


    Buy Logo

    ReplyDelete