18

I have been dealing with a problem for a while. How can I set the validation errors using redirect in a function? This is the code I have in my controller :

function send()
{
    $this->form_validation->set_rules('e-mail', 'Email', 'trim|required|valid_email');
    $this->form_validation->set_rules('cellphone', 'Cellphone Number', 'trim|required|is_natural');
    $this->form_validation->set_message('required', '%s is required.');
    $this->form_validation->set_message('valid_email', '%s is not a valid Email Address');
    $this->form_validation->set_message('is_natural', '%s can only contain numbers.');
    $this->form_validation->set_error_delimiters('<li>', '</li>');

    if($this->form_validation->run() == FALSE)
    {
        redirect ('/');
    }
    else
    {
        echo '<pre>';
        print_r($_POST);
        echo '<pre>';
    }
}

And this is the code I use in my view file:

<? if (validation_errors())
{   
echo '<div id="validation_errors" title="Error:">';
echo '<div class="response-msgs errors ui-corner-all"><span>Errors:</span><br /><ul>';
echo validation_errors();
echo '</ul></div>';
echo '</div>';
}
?>
Afshin
  • 2,427
  • 5
  • 36
  • 56
  • Is there any particular reason why you'd want to redirect? Usually when you show errors, they are shown on the page that they are input in so they can be corrected. You "could" possible use flashdata to store the result of `validation_errors()` which can then be accessed on the redirected to page? – Gavin Jun 14 '12 at 10:59
  • Yes, of course I know that. But the reason which made me to redirect is that the form is in the main page of the website and it should send all the data to a method called "send". After getting any kinds of errors, It should return to the previous method "index". – Afshin Jun 14 '12 at 11:03
  • Is the method `send` being used by anything else, other than for the `index` page? – Gavin Jun 14 '12 at 11:06
  • no, it's not. Just the main method "index". – Afshin Jun 14 '12 at 11:08
  • Then I would put the code that is in Send, in Index. See my answer for example. – Gavin Jun 14 '12 at 11:09
  • 2
    It might also work by doing `return $this->index()` instead of doing a redirect. Though @Gavin's anwser is probably better. – danneth Jun 14 '12 at 11:21

4 Answers4

24

I found the way to do it. Redirecting does not keep the data to be shown. I used the code below to solve the problem:

if($this->form_validation->run() == FALSE)
{
    $this->index();
}
Afshin
  • 2,427
  • 5
  • 36
  • 56
18

I know it's a bit late but this method works wonders for me.

If you are validating your form in a different function than the one the form is loaded in, you can send your validation_errors() to any page that you redirect() by passing the validation_errors() method to $this->session->set_flashdata() like so:

if ($this->form_validation->run() == FALSE) {

    $this->session->set_flashdata('error', validation_errors());

    redirect('/');
}

In your controller functions where you would like your errors or messages to be received you can then set them to the $data array like so:

if (!empty($this->session->flashdata('message'))) {

    $data['message'] = $this->session->flashdata('message');
} elseif (!empty($this->session->flashdata('error'))) {

    $data['error'] = $this->session->flashdata('error');
}

At the top of my views I usually include:

<?php if (isset($message)) {

    echo '<p class="alert alert-info">'.$message.'</p>';
} elseif (isset($error)) {

    echo '<p class="alert alert-danger"><strong>Error: </strong>'.$error.'</p>';
}?>

Using twitter bootstrap classes to format the messages helps to differentiate them.

I included the message flashdata so that you can see how whatever type of message or error you want to send, you are able to format them differently for all information, warning, success and error messages.

MunkyMead
  • 355
  • 3
  • 9
2

As per my comment:

function index()
{
    $this->load->library('form_validation');
    $data = array
    (
        'Param' => 'Value'
    );
    if($this->input->post('cellphone', true) !== false)
    {
        if($this->form_validation->run() != FALSE)
        {
            echo '<pre>' . print_r($_POST, true) . '</pre>';
        }
    }
    $this->load->view('index', $data);
}

First, you need to change your form so it points to the current page, i.e. current_url() or site_url('controller/index').

When you go to the index without posting, it will simply skip the validation. Upon submitting your form, it will run the validation.

You can then use the built in form_error or validation_errors methods to display the errors within your index view.

Gavin
  • 6,284
  • 5
  • 30
  • 38
  • I did know about this. But I just wanted to know if there's a way to do it using redirect – Afshin Jun 14 '12 at 11:26
  • Yes, however it's more complicated. You would have to store both the `$_POST` and `validation_errors` values in the FlashData and then display the error etc on return. This means you cannot use the built in functions and you are effectively rewriting code for no reason. – Gavin Jun 14 '12 at 11:30
1

finally i got a solution for the redirect with validation_errors

This is using to pass the validation_errors in the session data, i do it like this

if ($this->form_validation->run()) {
        $data = array(
            'email' => $this->input->post('email'),
            'is_login' => true
        );
        $this->session->set_userdata($data);
        redirect($this->input->post('redirect'));
    }
    else
    {
        $data = array (
            'errors' => validation_errors(),
            'is_login' => false
        );
        $this->session->set_userdata($data);
        redirect($this->input->post('redirect'));
    }

and in the page i used

        $this->session->set_flashdata('redirectToCurrent', current_url());

    if ($this->session->userdata('is_login'))
    {
        echo "You are using this as : </br>" . $this->session->userdata('email');
        echo "</br><a href='/logout'>Logout</a>";
    }
    else
    {
        echo form_open('login');
        echo "" . $this->session->userdata('errors');
        echo "email : " . form_input('email');
        echo "Password : " . form_password('password');
        echo form_submit('submit', 'Login');
        echo form_hidden('redirect',$this->uri->uri_string());
        echo form_close();
    }   

I wish you like this fast solution