Multiple forms on one page / controller and form validation

Sometimes it’s required to place two forms on one page in codeigniter like displaying login form and register form on same page. Although the views may be different but you can face conflict while displaying validation errors if the form actions are not separate (aren’t calling different methods in controller). Here is a workaround to validate one form at a time while placing multiple forms on one page in codeigniter.

The scenario

  1. I have a view having both login and register forms (You should use two different views to keep code clean).
  2. The form action is same for both login/register buttons.
  3. If any of form validation fails, I have to check which form is being submitted and have to show errors within that particular form.

If both forms are calling different actions (controller/method) then there would be no problem but if you didn’t follow the right approach then the both form will display the same error messages whenever you submit either of them as they are handled by the same controller method.

The solution

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. Let us see how can implement the concept.

Multiple forms on one page / controller and form validation

According to the solution specified above you can modify the form to satisfy either one of the given three approach:

Now under your controller/action, you can check either for:

And instead of using validation_errors() directly, you can assign errors to different variables, pass them to view and  check if they exist. 

Now in this way you can correctly process the forms and deal with multiple forms on one page / controller and form validation.

You Might Interested In


Leave a Reply

Enclose a code block like: <pre><code>Your Code Snippet</code></pre>.