我正在创建一个插件FileManager
,其中所有上传都存储在一个表中。这个插件有一个AttachmentBehavior
,它附加了一个hasMany
关联。
我使用模板Articles/add.php和Articles/edit.php中的多个文件输入来上传将链接到一篇文章的文件:
// Example in Articles/edit.php
echo $this->Form->create($article, ['type' => 'file']);
echo $this->Form->control('title', /*[...]*/);
echo $this->Form->control('body', /*[...]*/);
echo $this->Form->control('pieces_jointes', ['type' => 'file', 'multiple' => true, 'name' => 'pieces_jointes[]']);
我可以添加带有文件的新文章,没有问题。
我可以编辑一篇没有文件可添加文件的文章,没有问题。
但是,当我编辑一篇已经有文件要添加更多文件的文章时,我有一个错误“不能使用Laminas\Diactoros\UploadedFile作为数组的对象”--当实体Article
被修补时出现了这个错误。这是我的控制器:
// in ArticlesController.php
public function edit($id)
{
$article = $this->Articles->findById($id)->firstOrFail();
if ($this->request->is(['post', 'put'])) {
debug($article); // $article->pieces_jointes is an array of entities of my files table.
debug($this->request->getData()); // $this->request->getData()->pieces_jointes is an array of UplaodedFile objects
$article = $this->Articles->patchEntity($article, $this->request->getData()); // The error occurs here
if ($this->Articles->save($article)) {
return $this->redirect(/*[...]*/);
}
}
$this->set(compact('item'));
}
我不太清楚到底发生了什么。有人能解释我并帮助我解决这个问题吗?
发布于 2021-11-16 19:58:28
您不应该对upload字段和关联属性使用相同的名称,这是在框架的不同位置等待发生的冲突。
重命名表单中的字段等等,这样它使用的名称既不匹配任何关联属性,也不匹配任何列名,然后让您的行为和填充使用“外部”名称处理输入,并在将输入转换为保存数据所需的结构后将其转换为“内部”名称。
发布于 2021-11-16 17:19:59
删除AttachmentBehavior::beforeMarshal
中的关联文件模型似乎修复了错误:
// in AttachmentBehavior
public function beforeMarshal(Event $event, ArrayObject $data, ArrayObject $options)
{
foreach ($this->_fields as $field => $value) {
// Remove associated file Model (PiecesJointes, ...) in $options['associated']
$options['associated'] = collection($options['associated'])
->reject(function ($modelAssociated, $key) use ($value) {
return $modelAssociated == $value['alias'];
})
->toArray();
// [...]
}
}
但我需要确认我是对的(?)
https://stackoverflow.com/questions/69991547
复制相似问题