How to show validation errors using redirect in codeigniter?

后端 未结 4 1810
迷失自我
迷失自我 2020-12-31 04:50

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 :

         


        
4条回答
  •  一向
    一向 (楼主)
    2020-12-31 05:33

    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:

    '.$message.'

    '; } elseif (isset($error)) { echo '

    Error: '.$error.'

    '; }?>

    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.

提交回复
热议问题