2017-02-03 50 views
1

在笨文档here如何从CodeIgniter中的表单验证回调方法返回数据?

在该节状态的底注:

您也可以处理传递给你的回调表单数据并将其返回。如果您的回调函数返回布尔值TRUE/FALSE以外的任何值,则假定该数据是您新处理的表单数据。

我有一个回调函数,验证图像上传和不上传,是这样的:

public function upload() { 
    $this->form_validation->set_rules('imageFile', 'Image', 'callback_validate_image'); 
    // ... 
} 

然后回调函数:

public function validate_image() { 

     if (empty($_FILES['imageFile'])) { 
      $this->form_validation->set_message('validate_image', 'Please select a file'); 
      return false; 
     } 

     $config = array (
      'upload_path' => './uploads/', 
      'allowed_types' => 'jpg|jpeg|png|gif', 
      'max_size' => '5048576' 
     ); 

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

     if (!$this->upload->do_upload('imageFile')) { 
      $this->form_validation->set_message('validate_image', $this->upload->display_errors()); 
      return false; 
     } else { 
      $data = array('upload_data' => $this->upload->data()); 
      return $data; 
     } 

} 

我怎样才能返回$dataupload函数,以便我可以在一个查询中插入所有数据到数据库中?

+0

如果我使用了验证我只用于验证不会上传 –

+0

您无法直接将数据返回给该回调,但是您可以使用全局变量或类变量来访问该数据。顺便说一下,不建议在表单验证中上传图像。 – puncoz

+0

那么如何在没有'do_upload()'函数的情况下检查文件是否有效? –

回答

1

如果我做了你的代码的一部分,我会做这样的

function upload() 
{ 

    // 'required' doesn't work on file inputs so use empty() 
    if (empty($_FILES['imageFile'])) { 
     // show error message 
    } 

    if ($this->form_validation->run() == FALSE) 
    { 
      echo "Please select a file"; 
      //$this->load->view('myform'); 
    } 
    else 
    { 
     $config = array (
      'upload_path' => './uploads/', 
      'allowed_types' => 'jpg|jpeg|png|gif', 
      'max_size' => '5048576' 
     ); 

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

     if (!$this->upload->do_upload('imageFile')) 
     { 
      $this->form_validation->set_message('validate_image', $this->upload->display_errors()); 
      return false; 
     } 
     else { 
      $data['upload_data'] = $this->upload->data(); 
      $data['form_data'] = $this->input->post(NULL, TRUE); 
      var_dump($data); 
     } 
    } 
} 

没有通过上传部去了。在运行之前对其进行测试

+0

啊更好的方法!谢谢。另外,我没有使用这一行:'$ this-> form_validation-> set_rules('imageFile','Image','required')',因为所需的文件输入不起作用。相反,我只是在'form_validation-> run()'之前放了一个'empty()'检查。更新我的问题,让人们可以看到未来。 –

+0

对我的答案做更新。所以它会更好地解释你所说的。 –

+0

已批准..高兴地帮助:) –