我在项目中设置了表单验证。我的所有表单验证都在工作,但是我无法显示文件输入验证错误消息。该文件已正确上传,当我上传无效文件时它没有显示任何错误。我尝试了很多方法,但是任何方法都不起作用。
我在这里仅提供文件上传相关的代码。
我的控制器
$config = [
'upload_path'=>'./uploads/image/',
'allowed_types'=>'jpg|png',
'max_size' => '400',
'overwrite' => FALSE
];
$this->load->library('upload', $config);
if(!($this->form_validation->run() && $this->upload->do_upload()))
{
$view = array('error' => $this->upload->display_errors());
$view['admin_view'] = "admin/add_books";
$this->load->view('layouts/admin_layout', $view);
}
我的模型
public function add_books()
{
$data = $this->upload->data();
$image_path = base_url("uploads/image/".$data['raw_name'].$data['file_ext']);
$data = array(
'book_name' => $this->input->post('book_name'),
'description' => $this->input->post('description'),
'author' => $this->input->post('author'),
'publisher' => $this->input->post('publisher'),
'price' => $this->input->post('price'),
'quantity' => $this->input->post('quantity'),
'categoryId' => $this->input->post('categoryId'),
'book_image' => $image_path,
'userId' => $this->session->userdata('id'),
'status' => $this->input->post('status')
);
$insert_book = $this->db->insert('books', $data);
return $insert_book;
}
我的观点
<div class="form-group row">
<label for="book_image" class="col-sm-2 col-form-label">Book image</label>
<div class="col-sm-6">
<?= form_upload(['name'=>'userfile', 'class'=>'form-control'])?>
<div class="text-secondary">* Upload PNG, JPG format. Image should not be more than 400KB</div>
</div>
<div class="col-sm-4">
<div class="text-danger form-error"><?= form_error('userfile')?></div>
</div>
</div>
如何解决?
答案 0 :(得分:1)
我认为您应该将$this->form_validation->run()
和$this->upload->do_upload()
分开
$view = array();
if($this->form_validation->run() == true){
if(!$this->upload->do_upload('userfile')){
$view['error'] = $this->upload->display_errors();
}
}else{
$view['error'] = validation_errors();
}
if(array_key_exists('error', $view)){
$view['admin_view'] = "admin/add_books";
$this->load->view('layouts/admin_layout', $view);
}else{
//Insert the record
}