Aura Method,Component Event, Radio Group, Pass Data Parent Component to Child Component and Access Child Component Data to Parent Component in Lightning Component

Apex Class:- QuestionPageController
public class QuestionPageController { 
@AuraEnabled
public static string getQuizResponse(){
try{
return testParse();
}
catch(Exception ex){
system.debug('>>>>>getQuizResponse Error>>>>>> ' + ex.getMessage() + ' >>>>Line Number>>>> ' + ex.getLineNumber());
throw new AuraHandledException('System Error, Please retry : ' + ex.getMessage()+ ' '+ ex.getLineNumber());
}
}
@AuraEnabled
public static string getBonusResponse(){
try{
return getTestParse();
}
catch(Exception ex){
system.debug('>>>>>getBonusResponse Error>>>>>> ' + ex.getMessage() + ' >>>>Line Number>>>> ' + ex.getLineNumber());
throw new AuraHandledException('System Error, Please retry : ' + ex.getMessage()+ ' '+ ex.getLineNumber());
}
}

private static String testParse() {
String json = '{'+
' \"MyData\": ['+
' {'+
' \"MyDataStatus\": \"question\",'+
' \"QuestionSet\": {'+
' \"QuestionSetId\": 2097732,'+
' \"Questions\": ['+
' {'+
' \"QuestionId\": 6245402,'+
' \"Key\": 1010,'+
' \"Type\": \"singlechoice\",'+
' \"Text\": {'+
' \"Statement\": \"What is your Name?\"'+
' },'+
' \"HelpText\": {'+
' \"Statement\": \"What is your Name\"'+
' },'+
' \"Choices\": ['+
' {'+
' \"ChoiceId\": 29483422,'+
' \"Text\": {'+
' \"Statement\": \"Ram\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483432,'+
' \"Text\": {'+
' \"Statement\": \"Shyam\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483442,'+
' \"Text\": {'+
' \"Statement\": \"Mohan\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483452,'+
' \"Text\": {'+
' \"Statement\": \"Sohan\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483462,'+
' \"Text\": {'+
' \"Statement\": \"Kumar\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483472,'+
' \"Text\": {'+
' \"Statement\": \"Lakhan\"'+
' }'+
' }'+
' ]'+
' },'+
' {'+
' \"QuestionId\": 6245412,'+
' \"Key\": 30091,'+
' \"Type\": \"singlechoice\",'+
' \"Text\": {'+
' \"Statement\": \"Which of the following vehicles have you ever owned?\"'+
' },'+
' \"HelpText\": {'+
' \"Statement\": \"Which of the following vehicles have you ever owned\"'+
' },'+
' \"Choices\": ['+
' {'+
' \"ChoiceId\": 29483482,'+
' \"Text\": {'+
' \"Statement\": \"Audi A4\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483492,'+
' \"Text\": {'+
' \"Statement\": \"Volkswagen\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483502,'+
' \"Text\": {'+
' \"Statement\": \"Bmw\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483512,'+
' \"Text\": {'+
' \"Statement\": \"Isuzu\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483522,'+
' \"Text\": {'+
' \"Statement\": \"Lamborghini\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483532,'+
' \"Text\": {'+
' \"Statement\": \"None\"'+
' }'+
' }'+
' ]'+
' },'+
' {'+
' \"QuestionId\": 6245422,'+
' \"Key\": 10035,'+
' \"Type\": \"singlechoice\",'+
' \"Text\": {'+
' \"Statement\": \"What month was your born in?\"'+
' },'+
' \"HelpText\": {'+
' \"Statement\": \"What month was your born in\"'+
' },'+
' \"Choices\": ['+
' {'+
' \"ChoiceId\": 29483542,'+
' \"Text\": {'+
' \"Statement\": \"February\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483552,'+
' \"Text\": {'+
' \"Statement\": \"April\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483562,'+
' \"Text\": {'+
' \"Statement\": \"July\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483572,'+
' \"Text\": {'+
' \"Statement\": \"September\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483582,'+
' \"Text\": {'+
' \"Statement\": \"December\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483592,'+
' \"Text\": {'+
' \"Statement\": \"None\"'+
' }'+
' }'+
' ]'+
' }'+
' ]'+
' }'+
' }'+
' ]'+
'}';
return json;
}

private static String getTestParse(){
String jsonData = '{'+
' \"MyData\": ['+
' {'+
' \"MyDataStatus\": \"question\",'+
' \"QuestionSet\": {'+
' \"QuestionSetId\": 2097742,'+
' \"Questions\": ['+
' {'+
' \"QuestionId\": 6245432,'+
' \"Key\": 1030,'+
' \"Type\": \"singlechoice\",'+
' \"Text\": {'+
' \"Statement\": \"In which of the following City have your lived ?\"'+
' },'+
' \"HelpText\": {'+
' \"Statement\": \"In which of the following State have your lived\"'+
' },'+
' \"Choices\": ['+
' {'+
' \"ChoiceId\": 29483602,'+
' \"Text\": {'+
' \"Statement\": \"DELHI\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483612,'+
' \"Text\": {'+
' \"Statement\": \"NOIDA\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483622,'+
' \"Text\": {'+
' \"Statement\": \"PATNA\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483632,'+
' \"Text\": {'+
' \"Statement\": \"Banglore\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483642,'+
' \"Text\": {'+
' \"Statement\": \"HYDERABAD\"'+
' }'+
' },'+
' {'+
' \"ChoiceId\": 29483652,'+
' \"Text\": {'+
' \"Statement\": \"NONE\"'+
' }'+
' }'+
' ]'+
' }'+
' ]'+
' }'+
' }'+
' ]'+
'}';
return jsonData;
}
}
Component Event:- QuestionEvent.evt

<aura:event type="Component" description=" Component Event template" >
<aura:attribute name="QstionEvent" type="String"/>
<aura:attribute name="ErrorMessage" type="String"/>
</aura:event>
LightningComponent:- QuestionPageComponent

<aura:component controller="QuestionPageController" implements="flexipage:availableForAllPageTypes,lightning:actionOverride,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:appHostable,lightning:isUrlAddressable" access="global">
<aura:handler name="init" value="{!this}" action="{!c.doinit}"/>
<aura:attribute name="questionData" type="List"/>
<aura:handler name="questionEventRegister" event="c:QuestionEvent" action="{!c.handleComponentEvent}"/> <!-- "questionEventRegister" Register Event in Child Components "QuestionListItemCmp" -->
<aura:attribute name="errorMssg" type="String" />
<aura:attribute name="questionsLength" type="string" />
<table class="slds-table slds-table_bordered">
<tbody>
<aura:iteration items="{!v.questionData}" var="question" indexVar="rowIndex">
<c:QuestionListItemCmp aura:id="ChildCmpQuestionListItem" questionRecords="{!question}" dataindexVar="{!rowIndex}" questionTot="{!v.questionsLength}" />
</aura:iteration>
</tbody>

</table>
<div style="margin-left:50%;">
<br/>
<lightning:button aura:id="Next" label="Next" class="slds-button_brand" onclick="{!c.NextClick}" /> <br/>
</div>
</aura:component>
Controller:- QuestionPageComponent.Js

({
doinit : function(component, event, helper) {
var action = component.get("c.getQuizResponse");
action.setCallback(this, function(response){
debugger;
var state = response.getState();
if (state === "SUCCESS"){
let respData=response.getReturnValue();
helper.HelperEvent(component, event, helper,respData);
}
else if(state=="ERROR"){
var errr = response.getError();
var str = JSON.stringify(errr[0].message);
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
"title": "Error",
"type" : "error",
"duration": 'dismissible',
"message": str
});
toastEvent.fire();
}
});
$A.enqueueAction(action);
},
NextClick: function(component, event, helper) {
debugger;
var childComponentListItem = component.find("ChildCmpQuestionListItem");
if(childComponentListItem.length>0){
for(var i = 0;i < childComponentListItem.length;i++){
childComponentListItem[i].selectedQuestionMethod(); //Access Child Component event (selectedQuestionMethod) from Parent Component using Aura Method.
}
}
debugger;
var totqstion=component.get('v.questionsLength');
var err='';
if(totqstion==1){
err='Select Question';
}else{
err='Select All Question';
}
let errorMssg=component.get("v.errorMssg");
if(errorMssg=='undefined'){
component.set("v.errorMssg",null);
var toastEvent = $A.get("e.force:showToast");
toastEvent.setParams({
"title": "Error",
"type" : "Error",
"duration": 'dismissible',
"message": err
});
toastEvent.fire();
}
},
handleComponentEvent : function(component, event,helper){
debugger;
var qstionEventResp = event.getParam("QstionEvent");
var errMsgResp = event.getParam("ErrorMessage");
component.set("v.errorMssg", errMsgResp);
if(qstionEventResp!=null && typeof(qstionEventResp)!=undefined){
helper.HelperEvent(component, event, helper,qstionEventResp);
}
}
})
Helper:- QuestionPageComponentHelper.js

({
HelperEvent : function(component, event, helper,respData) {
debugger;
var jsonData=[];
var jsonRespVal = JSON.parse(respData);
for(var i=0; i<jsonRespVal.MyData.length; i++){
if(jsonRespVal.MyData[i].MyDataStatus=="question"){
var questionSetId=jsonRespVal.MyData[i].QuestionSet.QuestionSetId;
for(var j=0; j<jsonRespVal.MyData[i].QuestionSet.Questions.length; j++){
var questionId=jsonRespVal.MyData[i].QuestionSet.Questions[j].QuestionId;
var questionName=jsonRespVal.MyData[i].QuestionSet.Questions[j].Text.Statement;
var item = {};
item ["QuestionSetID"]=questionSetId;
item ["QuestionName"] =questionName;
var jsonChoices=[];
component.set("v.questionsLength",jsonRespVal.MyData[i].QuestionSet.Questions.length);
for(var k=0; k<jsonRespVal.MyData[i].QuestionSet.Questions[j].Choices.length; k++){
var itemChoices={};
var choiceId=jsonRespVal.MyData[i].QuestionSet.Questions[j].Choices[k].ChoiceId;
var choiceName=jsonRespVal.MyData[i].QuestionSet.Questions[j].Choices[k].Text.Statement;
itemChoices ["label"] =choiceName;
itemChoices ["value"] =questionId+'_'+choiceId;
jsonChoices.push(itemChoices);
item ["Choices"] =jsonChoices;
}
jsonData.push(item);
}
}
}
component.set('v.questionData',jsonData);
var totqstion=component.get('v.questionsLength');
if(totqstion==1){
var btn = component.find("Next"); // get button component
btn.set("v.label", "Done"); // Change Label Name
}
}
})
Child Component :- QuestionListItemCmp

<aura:component controller="QuestionPageController" >
<aura:attribute name="questionRecords" type="List"/>
<aura:attribute name="dataindexVar" type="List"/>
<aura:attribute name="radioGrpValue" type="String" />
<aura:attribute name="radioGrpQuestionDetails" type="String" />
<aura:attribute name="questionTot" type="String" />
<aura:method name="selectedQuestionMethod" action="{!c.getSelectedQuestion}"/> <!-- selectedQuestionMethod accesing from ParentController-->
<aura:registerEvent name="questionEventRegister" type="c:QuestionEvent"/>
<aura:attribute name="questionListDetails" type="List" />
<tr>
<td>
<div class="slds-truncate" title="{!v.questionRecords.QuestionName}"><b>{!v.dataindexVar+1}. {!v.questionRecords.QuestionName}</b></div>
</td>
</tr>
<tr>
<td>
<div class="slds-truncate slds-form-element__label">
<lightning:radioGroup
aura:id="{!v.dataindexVar+1}"
name="{!'radioGroup'+v.dataindexVar}"
label=''
options="{!v.questionRecords.Choices}"
value="{! v.radioGrpValue }"
type="radio"
onchange="{!c.handleRadioGroupChange}"
/>
</div>
</td>
</tr>
</aura:component>
Child Component Controller:- QuestionListItemCmpController.js
({
handleRadioGroupChange : function(component, event, helper) {
debugger;
var questionTot=component.get("v.questionTot");
if(questionTot==1){
helper.variableList=[];
}
var radioGrpValue = component.get("v.radioGrpValue");
component.set('v.radioGrpQuestionDetails',radioGrpValue);
var splitData=radioGrpValue.split('_');
for(var i=0; i<helper.variableList.length;i++){
var elemData=helper.variableList[i];
var index = elemData.indexOf(splitData[0]);
if(index>-1){
helper.variableList.splice(i, 1);
}
}
helper.variableList.push(radioGrpValue);
helper.RadioGroupChangeHelper(component, event, helper);
},
getSelectedQuestion : function(component, event,helper){
debugger;
var radioGrpQuestionDetails=component.get("v.radioGrpQuestionDetails");
if( typeof(radioGrpQuestionDetails) == 'undefined' ){
var compEvent = component.getEvent("questionEventRegister"); // Pass Data, Child component to Parent Componet using component Event,"questionEventRegister" has registered in Child Componnet.
compEvent.setParams({
"ErrorMessage" : 'undefined' // "ErrorMessage" is an Event Attributes of "QuestionEvent"
});
compEvent.fire();
}
else{
var questionListDetails=component.get("v.questionListDetails");
var questionTot=component.get("v.questionTot");
debugger;
if(questionTot==questionListDetails.length){
var action = component.get("c.getBonusResponse");
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS"){
var comp_event = component.getEvent("questionEventRegister"); // Pass Data, Child component to Parent Componet using component Event.
comp_event.setParams({
"QstionEvent" : response.getReturnValue()});
comp_event.fire();
}
});
$A.enqueueAction(action);
}

}
}
})
Child Component Helper :- QuestionListItemCmpHelper.Js

({
variableList: [], //Declare global Array variable
RadioGroupChangeHelper : function(component, event, helper) {
debugger;
var questionArray = [];
for (var i = 0; i < helper.variableList.length; i++) {
questionArray.push(helper.variableList[i]);
}
component.set('v.questionListDetails',questionArray);
}
})
Lightning App:-DemoAppExample

<aura:application extends="force:slds">
<c:QuestionPageComponent></c:QuestionPageComponent>
</aura:application>
OutPut:-

Leave a Reply