Welcome Guest, Not a member yet? Register   Sign In
Form validation on dynamically generated form
#1

[eluser]philstan[/eluser]
Hi everyone,

Although the form validation seems to stop the input of an incomplete form, I'm having difficulty getting CI to give me a validation message on a dynamically generated form.

Here is the code in the View:

Code:
case "Agree Disagree";
     echo "<div class=\"question\">".$fieldset->question."</div>";

    //put in the answer options
    echo "<div class=\"answer\">";

    echo form_error($fieldset->qid);

    echo "<select name=".$fieldset->qid.">";
    echo "<option select=\"selected\" value=\"\"  >Select one...</option>";

    foreach($answers as $value)
    {                        
        if($value->group_name == "Agree Disagree")
        {
            echo "<option value=".$value->id.">".$value->answer."</option>";                                
        }
    }                                            
    echo "</select>";
    echo "</div>";
    //clear the floats
    echo "<div class=\"clear\"> </div>";
    break;

Here is the submit() in the controller:

Code:
$validate = $_POST;
    
        foreach($validate as $key => $value)
        {
            $this->form_validation->set_rules('.$key.', 'Question', 'required');            
        }

Dies anyone know why this doesn't work or how to get the thing to work.

Thanks Philip
#2

[eluser]philstan[/eluser]
Solved! Just in case anyone has the same problem here was the problem.

The CI form validation class determines if the input fields are strings or not. The class will only work on strings. Therefore, the solution is double quotes around the variable:

eg:

Code:
$validate = $_POST;
    
        foreach($validate as $key => $value)
        {
            $this->form_validation->set_rules("$key", 'Question', 'required');            
        }
#3

[eluser]Ryuuzaki92[/eluser]
you can also remove the double quotes:

Code:
$this->form_validation->set_rules($key, 'Question', 'required');
#4

[eluser]philstan[/eluser]
Thank you.

It was on this very point that I was pulling out my hair as I saw:
Code:
($key, 'Question', 'required');
on another post and couldn't figure out why it wouldn't work. My $key is an integer and CI kept rejecting it, hence the necessity of the double quotes.




Theme © iAndrew 2016 - Forum software by © MyBB