Codeigniter 2 forms on one page, validation_errors problem

前端 未结 2 1484
野性不改
野性不改 2020-12-09 23:07

On one of my websites I have 2 forms on one page, I am having a problem, with validation_errors(); basically what is happening, is for one of the forms I am che

相关标签:
2条回答
  • 2020-12-09 23:48

    What I did was divide both forms. The view would be like

        <?php echo validation_errors(); ?>
        <?php echo form_open('form1'); ?>
        <form id="form1" action="some_action">
        //Inputs
        </form> 
        <?php echo form_open('form2'); ?>
        <form id="form2" action="other_action">
        //Inputs
        </form>
    

    Now, in the controller you can have two different functions for each validation:

        //Controller
        function some_action(){
        //validate form and code
        } 
    
        function other_action(){
        //validate form2 and code
        }
    

    Now, all validation messages will appear in the same place but will only show the messages of each form. Hope that helps

    0 讨论(0)
  • 2020-12-09 23:50

    Your question is a bit hard to read, but if I understand correctly - you're having trouble validating 2 separate forms from one controller, or issues dealing with errors from different forms using validation_errors() which afaik prints ALL errors:

    Before running validation, check for the existence of either a hidden field, a field that is unique to the form, or you can check the value of the particular submit button.

    <form>
    <input type="hidden" name="form1" value="whatever">
    <input name="form1_email" />
    <input type="submit" value="Submit Form 1" />
    </form>
    

    Then you can use any of these methods to check which form was submitted (This example checks if "form1" was submitted):

    <?php
    // Choose one:
    if ($this->input->post('form1')): // check the hidden input
    if ($this->input->post('form1_email')): // OR check a unique value
    if ($this->input->post('submit') == 'Submit Form 1'): // OR check the submit button value
    
        if ($this->form_validation->run()):
    
            // process form
    
        else:
                // Create a variable with errors assigned to form 1
                // Make sure to pass this to your view
                $data['form1_errors'] = validation_errors();
        endif;
    
    endif;
    // Do same for form 2
    

    Then in your view, instead of using validation_errors() you would use:

    if (isset($form1_errors)) echo $form1_errors; // Print only form1's errors
    

    If this doesn't help let me know, and clarify your question by posting your code.

    0 讨论(0)
提交回复
热议问题