Sunday, July 8, 2018

Displaying lightning:radioGroup dynamically from SOQL query

Use Case


Sometimes we receive a use case to display dynamic radio button with dynamic options querying the data from database via SOQL query.

Let's say, questions and answers to be populated and displayed in lightning components.

I was answering this question lightning:radioGroup - not able to select the options in stackexchange and able to produce a small poc with an approach.

Approach


Create Question and Answer custom object with following attributes.

Question Object (Question__c)
  • Question Name (Auto number)
  • Question Text (QuestionText__c, TextArea(255)).
Answer Object (Answer__c)
  • Question (Master-Detail (Question)
  • Option (TextArea (255))
  • Correct Answer (Checkbox)
Following things to considered when implementing this solution:

  1. To group the options for individual question, the name should be unique. Here QuestionText has been used. You can use QuestionId.
  2. We can see in the reference Radio group in Lightning Component Library that options attribute takes label and value as follows. So we need to pull the options as AnswerText__c from Answer object and assign those values as label and value.


<aura:component>
    <aura:attribute name="options" type="List" default="[
    {'label': 'Sales', 'value': 'option1'},
    {'label': 'Force', 'value': 'option2'}
    ]"/>
    <aura:attribute name="value" type="String" default="option1"/>

    <lightning:radioGroup name="radioGroup"
                          label="Radio Group"
                          options="{! v.options }"
                          value="{! v.value }"
                          type="radio"/>
</aura:component>

So, the component code will look like this.

Quiz.cmp

 <aura:component controller="QuestionAnswerClass" access="global" >  
      <aura:attribute name="Questions" type="List"/>  
   <aura:attribute name="radioGrpValue" type="List"/>   
   <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>  
   <aura:iteration items="{!v.Questions}" var="ques">  
     <lightning:radioGroup name="{!ques.QuestionText__c}"  
                           label="{! ques.QuestionText__c}"   
                           options="{!ques.Answers__r}"  
                           value="{! v.radioGrpValue}"  
                           type="radio"  
                           required="true"/>  
   </aura:iteration>   
 </aura:component>  

QuizController.js


({
 doInit : function(component, event, helper) {
  helper.doInit(component, event,helper);       
 }
})

QuizHelper.js


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
({
 doInit : function(component, event, helper) {
        
  var action = component.get("c.getQuestionAnswers");
        
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var returnVal = response.getReturnValue();
                var finalList = [];
                for(var i=0; i<returnVal.length; i++)
                {
                    var answers = returnVal[i].Answers__r;
                    //append label and values into the list so it can be displayed as options
                    for(var j=0; j<answers.length; j++)
                    {
                        answers[j].label = answers[j].Option__c;
                        answers[j].value = answers[j].Option__c;
                    }
                    finalList.push(returnVal[i]);         
                }
                
                component.set("v.Questions", finalList);
            }
            else {
                console.log("Failed with state: " + state);
            }
        });
        // Send action off to be executed
        $A.enqueueAction(action);
 }
})

Apex Controller


public class QuestionAnswerClass
{
 @AuraEnabled
 public static List<Question__c> getQuestionAnswers()
 {
  List<Question__c> lstQues = [SELECT Name, QuestionText__c, 
     (SELECT Name, Option__c, Correct_Answer__c FROM Answers__r)
     FROM Question__c];
  return lstQues;
  
 } 
}

Quiz.app


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

Desired Results


If we load the application clicking on preview, it will display like this.

User can see the dynamic questions with options and able to select options respective to questions.


For more information, refer Radio group in Lightning Component Library

1 comment:

  1. AWS Training in Bangalore - Live Online & Classroom
    myTectra Amazon Web Services (AWS) certification training helps you to gain real time hands on experience on AWS. myTectra offers AWS training in Bangalore using classroom and AWS Online Training globally. AWS Training at myTectra delivered by the experienced professional who has atleast 4 years of relavent AWS experince and overall 8-15 years of IT experience. myTectra Offers AWS Training since 2013 and retained the positions of Top AWS Training Company in Bangalore and India.

    IOT Training in Bangalore - Live Online & Classroom
    IOT Training course observes iot as the platform for networking of different devices on the internet and their inter related communication. Reading data through the sensors and processing it with applications sitting in the cloud and thereafter passing the processed data to generate different kind of output is the motive of the complete curricula. Students are made to understand the type of input devices and communications among the devices in a wireless media.

    ReplyDelete