3

I have a form that displays questions from a questionnaire. Some questions are True/False (radio buttons) but some are free text input. Each questionnaire can have any number of questions, which are stored in a lookup table along with the answer provided by the user. To take advantage of CodeIgniters form validation library, I figured I would use an array for the input names and store the primary key of the survey question as the index:

View:

<input type="radio" name="question[<?=$id;?>]" value="<?=$answer?> <?=set_radio('question['. $id . ']', $answer) ?> />

Controller:

$this->form_validation->set_rules('question[]', 'Questions', 'required');

CodeIgniter doesn't seem to validate radio buttons properly when there is no default value set. Any ideas on whether or not I am doing this correctly?

1 Answer 1

2

Reference: http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#arraysasfields

Check the arrays as fields reference, but you need to call the specific array, if your input is question[pie], your validation needs to check for question[pie] and not questions[].

I'm just making assumptions here as I don't know what you get as a response or what you have tried.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply. I have several true/false questions on my form, and the names are dynamically generated: question[11], question[13], question[15], etc. The validation of $this->form_validation->set_rules('question[]', 'Questions', 'required'); does appear to work but only if no radio buttons are selected. As soon as one is selected, all of the others pass validation.
well if you validate question[] you validate the ENTIRE array (so a single TRUE) makes the required TRUE. You need to dynamically create single ..validation->set_rules('question[XX]') for each question in your form. Don't run it on the root array question[]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.