我有一个可以提交图片的表单,这不是我原来的代码,我继承它并且我试图弄明白并解决问题。
从此表单编辑数据时,输入文件为空,而不是其他输入。因此保存实际上将当前文件替换为" array"在数据库中。
如果不变,我希望能保留当前的那个吗?
表单编辑:
<h1>Edit</h1>
<?php
echo $this->Form->create($template,['enctype' => 'multipart/form-data']);
echo $this->Form->input('title');
echo $this->Form->input('works_id');
echo $this->Form->input('photo',['type' => 'file']);
echo $this->Form->input('text', ['rows' => '4']);
echo $this->Form->input('url');
echo $this->Form->button(__('Save'));
echo $this->Form->end();
?>
从控制器编辑功能:
public function edit($id = null){
$template = $this->Templates->get($id);
if ($this->request->is(['post', 'put'])) {
$template = $this->Templates->patchEntity($template, $this->request->data,['associated' => ['Works']]);
if ($this->Templates->save($template)) {
$this->Flash->success(__('Your template has been updated.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('Unable to update your template.'));
}
$this->set('template', $template);
$works = $this->Templates->Works->find('list');
$this->set(compact('works'));
}
在我的数据库中,它保存在两个colomns上: file_dir和filename,所以它让我更加困惑如何在编辑表单中获取文件。
编辑:添加TemplatesTable:
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\Validator;
class TemplatesTable extends Table
{
protected function _initializeSchema(\Cake\Database\Schema\Table $table){
$table->columnType('photo', 'proffer.file');
return $table;
}
public function initialize(array $config){
$this->addBehavior('Timestamp');
$this->addBehavior('Proffer.Proffer', [
'photo' => [
'root' => WWW_ROOT.'files',
'dir' => 'photo_dir',
'thumbnailSizes' => [
'square' => ['w' => 200, 'h' => 200],
'portrait' => ['w' => 100, 'h' => 300, 'crop' => true],
],
'thumbnailMethod' => 'gd' // Options are Imagick, Gd or Gmagick
]
]);
$this->belongsTo(
'Works',
[
'foreignKey' => 'work_id',
]
);
}
public function validationDefault(Validator $validator){
$validator
->notEmpty('work_id')
->notEmpty('title');
return $validator;
}
}
答案 0 :(得分:1)
根据文档,Proffer
行为可以处理开箱即用的空上传,您只需相应地配置字段的验证规则,以便在更新时为空:
如果您希望用户在创建记录时提交文件,但是 不是在更新时,您可以使用基本的Cake配置它 规则。
$validator ->requirePresence('image', 'create') ->allowEmpty('image', 'update');
现在,您的用户每次更新时都不需要上传文件 记录。
所以在你的情况下会是:
->requirePresence('photo', 'create')
->allowEmpty('photo', 'update')