CodeIgniter Form Validation with existing $_POST data
I have a form that I need to validate but I can't figure out how to code the controller so that it works correctly the first time the page is displayed. Here is my code (simplified):
function index()
$data['somedata'] = $this->input->post('somedata');
$this->form_validation->set_rules('event', 'Event', 'trim|required|alpha_numeric');
... more set_rules ...
if($this->form_validation->run() == FALSE)
{
// Hasn't been run or there are validation errors
$this->load->view('eventview', $data);
}
else
{
// Process the event
}
}
The problem is that form_validation->run() is never FALSE because the $_POST array contains data from a previous form that is used by this second form. At the very beginning of the form_validation->run() function is the following code:
// Do we even have any data to process? Mm?
if (count($_POST) == 0)
{
return FALSE;
}
Since $_POST data exists the count is al开发者_如何学运维ways greater than zero which results in the validation to be processed on initial page load. Any suggestions as to how I might work around this?
I would suggest that you save the data from your first form in sessions, then make a redirect to your second form instead of going directly to the next one, with your post data.
This would also be more flexible if you need to reuse any of the submitted data.
In the first form set a hidden input
<input type="hidden" name="form1" value="form1" />
Then in your controller check if the field is set, if so store the current post array, and then unset it.
if(isset($_POST['form1'])){
$old_post = $_POST;
unset($_POST);
}
as I assume you are accessing the $_POST array in your view, instead pass `$old_post` through and use that,
e.g. (isset($old_post) ? $old_post['field_name'] : set_value('field_name))
Good luck.
精彩评论