I have two objects in my org question and answer which has a lookup relationship between them. I wanted to create a LWC component which displays one question with multiple answers but I am unable to display it.
I have written the following apex code which I am using in my LWC to components to render on the UI
Apex Controller:
public with sharing class ControllerClass {
@AuraEnabled(cacheable = true)
public static List<wrapperClass> getWrapperClassList() {
List<wrapperClass> wrapperList = new List<wrapperClass>();
Map<Id, Ques__c> mapOfQuestions = new Map<Id, Ques__c>([SELECT Id, Content__c FROM Ques__c]);
List<Ans__c> listOfAnswers = [SELECT Id, Name, Ques__r.Id, Ques__r.Content__c
FROM Ans__c
WHERE Ques__r.Id
IN :mapOfQuestions.keyset()];
System.debug('listOfAnswers==='+listOfAnswers);
for(Ans__c answer : listOfAnswers){
wrapperClass wc = new wrapperClass();
wc.questionId = answer.Ques__r.Id;
wc.questionContent = answer.Ques__r.Content__c;
wc.answerId = answer.Id;
wc.answerName = answer.Name;
wrapperList.add(wc);
}
return wrapperList;
}
public class wrapperClass{
@AuraEnabled
public String questionId;
@AuraEnabled
public String questionContent;
@AuraEnabled
public String answerId;
@AuraEnabled
public String answerName;
}
}
Question.html
<template>
<lightning-card title="Question">
<template for:each={wrapperList.data} for:item="wrapper" >
<p class="slds-m-left_medium" key={wrapper.questionId}>
{wrapper.questionContent}
</p>
</template>
</lightning-card>
</template>
Question.js
import { LightningElement, wire } from 'lwc';
import getWrapperClassList from '@salesforce/apex/ControllerClass.getWrapperClassList';
export default class Question extends LightningElement {
@wire(getWrapperClassList)
wrapperList;
}
Answer.html:
<template>
<lightning-card class="slds-m-around_medium">
<template for:each={answers.data} for:item='answer'>
<p key={answer.answerId}>
<lightning-input class="slds-m-left_medium" label={answer.answerName} name="radios" type="radio" ></lightning-input>
</p>
</template>
</lightning-card>
</template>
Answer.js
import { LightningElement, wire } from 'lwc';
import getWrapperClassList from '@salesforce/apex/ControllerClass.getWrapperClassList';
export default class IBAnswer extends LightningElement {
@wire(getWrapperClassList)
answers
}
The current code returns multiple questions related to each options i.e. One question which has 4 answers will return 4 questions for one answer each.