Pages

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

No comments:

Post a Comment