I am trying to use form validation for my form after user submits it. My view page has a variable that was passed by my controller. The view page works fine until I submit the form to validate. It gave me errors saying the variables passed by controller were undefined. I am not sure how to solve this. Any thoughts?
// Controller - status.php
public function load_view ()
{
$this->load->model('project_query');
$JNresults=$this->project_query->get_jobnumber();
$data['JNresults']=$JNresults->result(); //pass to view
$data['view']='form_view';
$this->load->view('include/template',$data);
}
public function validate ()
{
//validate form
$data['error']='There are errors in your form.';
$data['view']='form_view';
$this->load->view('include/template',$data);
}
// View page - form_view.php
foreach ($JNresults as $row): //work fine when first loaded.
echo $row->job_number;
endforeach;
echo form_open('status/validate');
echo validation_errors();
// input fields...
echo form_submit($submit);
echo form_close();
I get undefined variable $JNresults after I submit the form. I understand the view page don’t recognize it because it was passed from the controller. I just want to know if anyone can help me to solve this.
In your
validate()method, you aren’t using$data['JNresults']=$JNresults->result();so the variable$JNresultsnever gets populated in your view.The solution:
Validate the form in
load_view(), and get rid the ofvalidate()method:Then change
form_open('status/validate')toform_open()orform_open('status/load_view').It looks like you aren’t using the
$data['error'], which is fine because you don’t need it.validation_error()returns an empty string if there are no errors, so if you want to add an extra message you can just check if it’s empty: