1
votes

I am loading my form on index action of my Add controller and posting that form to submit_post action of the same controller. All I want is that if the post data doesn't fulfill the validation then it should redirect to the index action back rendering my form only and keeping the form fields filled with the values that were posted and also I would be able to get the each field error individually here are my controller actions

class Add extends CI_Controller {
    private $view = "";

    public function __construct()
    {
        parent::__construct();
        $this->view = "add";
    }

    public function index()
    {
      $this->load->view("frontend/default", array("view" => $this->view));
    }

    public function submit_post()
    {
         $this->form_validation->set_rules('description', 'Description', 'required');
         $this->form_validation->set_rules('name', 'Name', 'required');
         if ($this->form_validation->run() == FALSE)
         {
              redirect('/add');
         }
         else
         {
             echo "Validated";
         }
    }
}

I have read many blogs and stackoverflow questions and found that this could be achieved via set_flashdata. Well, I did that and were able to print the all errors altogether.

2

2 Answers

2
votes

The problem is because of the line redirect('/add'); With a redirect the validation class will be reloaded and all the information gathered during form_validation->run() is lost.

Here's my suggested code

     if ($this->form_validation->run() == FALSE)
     {
          $this->index();
     }
     else
     {
         echo "Validated";
     }
0
votes

You should lоаd form_validation in your config file $autoload['libraries'] = array('form_validation'). And then if you want to display the errors individualy, you should put this in your html right under every input field :

    <?php echo form_error('your fieldname');?>