Welcome Guest, Not a member yet? Register   Sign In
Form Validation with existing $_POST data
#1

[eluser]chuckl[/eluser]
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):
Code:
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:
Code:
// Do we even have any data to process? Mm?
  if (count($_POST) == 0)
  {
    return FALSE;
  }
Since $_POST data exists the count is always 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?
#2

[eluser]misplacedme[/eluser]
A quick fix would be to add a variable to the previous form that won't be used in the next form.
If $this->input->post('step1') returns a non-false value, then you know that the form was previously submitted, so don't run validation.
#3

[eluser]chuckl[/eluser]
I guess I wasn't sufficiently clear in my description of the problem. The problem is that the $_POST array has existing elements when the controller is invoked.

In CodeIgniter's system/libraries/Form_validation.php file, the function run() has a check at the very beginning that checks to see if there are any entries in the $_POST array and if it is empty (count = 0) then it returns false.
Code:
// No validation rules?  We're done...
if (count($this->_config_rules) == 0)
{
  return FALSE;
}
Every example/tutorial I have seen uses the code I posted previously as the way to determine if this is the first time the page has been loaded. Obviously, since the $_POST array is not empty at this point, the run() function does not return but processes the form before its time.

I thought about clearing the $_POST array but I'm not sure how to go about doing that nor am I sure what the ramifications might be in doing so.




Theme © iAndrew 2016 - Forum software by © MyBB