Welcome Guest, Not a member yet? Register   Sign In
Form Validation -> callback function with no args when POST['field'] is inexistent
#1

[eluser]skiff_pt[/eluser]
Hi all,

I was trying to integrate file upload validation with form validation.
As i have form with a variable number of File fields i tried to dynamically add form_validation rules based on the entries on the $_FILES:

In controller:
Code:
//FIRST I ADD THE RULES FOR ALL THE TEXT, AND CHECKBOXES FIELDS OF THE FORM
//THEN I START TO WORK ON THE FILES:

$this->file_config['allowed_types']= 'gif|jpg|png';
$this->file_config['max_size']     = MAX_UPLOAD_SIZE;
$this->file_config['upload_path']  = WEB_ROOT_FROM_ADMIN.$this->dir_imagens;
$this->file_config['overwrite']    = TRUE;
                
foreach($_FILES as $key => $value){
  $form_config[]= array(
                        'field' => $key,
                        'label' => ucfirst($key),
                        'rules' => 'callback__upload_file['.$key.']'
                       );
}

$this->form_validation->set_rules($form_config);
$this->form_validation->run();

_upload_file callback function:
Code:
function _upload_file($str,  $file_name){

  $this->load->library('upload');

  file_config['file_name'] = "temp_{$file_name}".$this->_include_ext($_FILES[$file_name]['name']);

  $this->upload->initialize($this->file_config);

  if ( ! $this->upload->do_upload($file_name)){
    $this->form_validation->set_message('_upload_file',$this->upload->display_errors('<p class="error">','</p>'));
    return FALSE;
  }else{
    return TRUE;
  }
}

What happens is that the Form_validation code is first looking into $_POST super global to check if $_POST['field'] exists, if it does not exist it only grabs the name of the call back function but with no arguments.
In the case above, if i don't have the file name in the $_FILES superglobal my call back version will allways output no file entered error!

Question:
Is there any reason why in such case the no arguments are passed into the callback function?


Work arround:
In the meantime i came up with a possible work arround.
I extended Form_validation library to My_Form_validation.
I only changed _execute method.
And in that method i only changed line number: 487

Code:
// Before we bail out, does the rule contain a callback?

/*Original Statement
if (preg_match("/(callback_\w+)/", implode(' ', $rules), $match))*/
//New Statement
if (preg_match("/(callback_\w+(\[\w*\])*)/", implode(' ', $rules), $match))
{
  $callback = TRUE;
  $rules = (array('1' => $match[1]));
}

This way when there is no $_POST['field'] the argument of callback function is still passed.

Take Care.




Theme © iAndrew 2016 - Forum software by © MyBB