首先是一些背景信息:
用户可以填写一些输入文本框并上传多张图片(在一个上传字段中)。提交表单后,文本字段中的文本以$this->XXX->save()
. 此外,数据(特别是来自文件上传的图像)在回调函数中进行处理afterSave()
。到现在为止还挺好。
现在解决问题:
似乎多次调用回调函数(每个上传的图像1次)。所以问题是,第一次一切正常,但之后$this->data
数组基本上是空的(所有文本字段都是= ''
)所以回调函数会抛出一些异常,因为没有数据。我只是通过检查isset()
等等来解决问题,但我认为这并不能解决问题。
所以我的问题是,为什么多次调用回调函数,我该如何防止呢?
编辑: 遵循一些相关的代码片段:
控制器:
if ($this->request->is('post') || $this->request->is('put')) {
if($aid==null) $this->Article->create();
if ($this->Article->save($this->data)) {
$this->Session->setFlash(__('The article has been saved'), 'flash_custom');
return $this->redirect(array('controller' => 'articles', 'action' => 'view', $this->id));
} ...
模型:
我认为其中大部分与这里无关。一般来说,我将数据发送到其他模型,这些数据保存在其他数据库表中,例如图片
if ($this->data['Article']['picture']) {
foreach ($this->data['Article']['picture'] as $picture) {
if (is_uploaded_file($picture['tmp_name']) && (substr($picture['type'], 0, 5) == "image") && $numberOfPictures < $pictures_allowed) {
$this->Picture->addPicture($picture, $this->id);
}
$numberOfPictures++;
}
错误转储:
我认为$this->data
数组的转储在这里很有趣(下面的解释)
array(
'Article' => array(
'pictures' => '0',
'title' => 'Error Test',
'abstract' => 'Test abstract',
'body' => 'Testtext',
'picture' => array(
(int) 0 => array(
[maximum depth reached]
),
(int) 1 => array(
[maximum depth reached]
),
(int) 2 => array(
[maximum depth reached]
)
),
'modified' => '2015-04-13 22:00:09',
'created' => '2015-04-13 22:00:09',
'id' => '294'
))
Notice (8): Undefined index: title [APP/Model/Article.php, line 723]
Notice (8): Undefined index: body [APP/Model/Article.php, line 724]
Notice (8): Undefined index: abstract [APP/Model/Article.php, line 725]
array(
'Article' => array(
'id' => '294',
'pictures' => (int) 1,
'modified' => '2015-04-13 22:00:09',
'title' => '',
'body' => '',
'abstract' => '',
)
)
Notice (8): Undefined index: picture [APP/Model/Article.php, line 777]
Notice (8): Undefined index: title [APP/Model/Article.php, line 723]
Notice (8): Undefined index: body [APP/Model/Article.php, line 724]
Notice (8): Undefined index: abstract [APP/Model/Article.php, line 725]
array(
'Article' => array(
'id' => '294',
'pictures' => (int) 2,
'modified' => '2015-04-13 22:00:10',
'title' => '',
'body' => '',
'abstract' => '',
)
)
Notice (8): Undefined index: picture [APP/Model/Article.php, line 777]
Notice (8): Undefined index: title [APP/Model/Article.php, line 723]
Notice (8): Undefined index: body [APP/Model/Article.php, line 724]
Notice (8): Undefined index: abstract [APP/Model/Article.php, line 725]
array(
'Article' => array(
'id' => '294',
'pictures' => (int) 3,
'modified' => '2015-04-13 22:00:10',
'title' => '',
'body' => '',
'abstract' => '',
)
)
Notice (8): Undefined index: picture [APP/Model/Article.php, line 777]
解释:
我只是转储了$this->data
一次,但就像你看到的那样,我上传了 3 张图片,我收到了 3 个 afterSave 电话,所以 3 个$this->data
转储。第一次一切都很好,但之后由于数组不再填充而引发了一些警告。
我希望这些额外的信息可以帮助你