0

I have a requirement to display the set of questions in VF Page. The set of questions will be available in Custom object. I need to display the question field and answer field for the user to answer. I have a Is_Mandatory check box in custom object where user can set the questions as mandatory. What I need to do is I have to populate the mandatory questions with (*) symbol. And I have to do a validation check when the user click the submit button whether all the mandatory question are filled or not. Can anyone please guide me on this?

3

I'm assuming your object structure is:

Your Object
    Is_Mandatory__c
    Question_1__c, Answer_1__c
    Question_2__c, Answer_2__c
    Question_3__c, Answer_3__c
    ...
    Question_N__c, Answer_N__c

You should include the <apex:pageMessages/> in your Visualforce page to display the error message(s).

You can use conditional output to render the asterisk (*). You might have to play with the formatting a bit for your specific Visualforce layout.

<apex:outputText value="*" rendered="{!yourRecord.Is_Mandatory__c}"/> <apex:inputField value="{!yourRecord.Question_1__c}"/> 
<apex:outputText value="*" rendered="{!yourRecord.Is_Mandatory__c}"/> <apex:inputField value="{!yourRecord.Question_2__c}"/> 
<apex:outputText value="*" rendered="{!yourRecord.Is_Mandatory__c}"/> <apex:inputField value="{!yourRecord.Question_3__c}"/>
<apex:outputText value="*" rendered="{!yourRecord.Is_Mandatory__c}"/> <apex:inputField value="{!yourRecord.Question_N__c}"/>

For the validation, you could create a Validation Rule that doesn't allow the record to be saved if Is_Mandatory__c = true and any of the Answer__c fields are blank. Then in your controller you will have to catch the DMLException and disply the error message.

public PageReference submit() {
    try {
        //insert/update/upsert your record
        upsert yourRecord;
     } catch(DmlException ex){
         ApexPages.addMessages(ex);
     }
}

Alternatively, you could validate in your Controller:

public PageReference submit() {
    if (yourRecord.Is_Mandatory__c) {
        if (hasBlankAnswer()) {
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'All answers are required');
            ApexPages.addMessage(myMsg);
            return null;
        }
    }
}

private Boolean hasBlankAnswer() {
    // check for blank answers...
    // return true if there are any, false otherwise.
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.