Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在CakePHP3中使用beforeSave$事件、$entity和$options必须始终填写?_Cakephp_Cakephp 3.0 - Fatal编程技术网

如何在CakePHP3中使用beforeSave$事件、$entity和$options必须始终填写?

如何在CakePHP3中使用beforeSave$事件、$entity和$options必须始终填写?,cakephp,cakephp-3.0,Cakephp,Cakephp 3.0,我在“PostsTable.php”中,我试图获取表单数据来处理图像文件 在CakePHP 2中,我曾经做过: public function beforeSave($options = array()) { if(!empty($this->data['Post']['picture']['name'])... 有人可以在蛋糕3中解释这一点: beforeSave Cake\ORM\Table::beforeSave(Event $event, Entity $entity, Arra

我在“PostsTable.php”中,我试图获取表单数据来处理图像文件

在CakePHP 2中,我曾经做过:

public function beforeSave($options = array())
{
if(!empty($this->data['Post']['picture']['name'])...
有人可以在蛋糕3中解释这一点:

beforeSave
Cake\ORM\Table::beforeSave(Event $event, Entity $entity, ArrayObject $options)
?

已添加

我尝试这段代码,以查看是否能够将此字段作为测试保存在数据库中,但似乎之前保存被忽略:

public function beforeSave($options)
{ 
if(!empty($entity->pic1['name'])) 
{ 
$entity->pic1 = 'jus a test';
}
谢谢

让我为你:

Model.beforeSave事件在保存每个实体之前触发。停止此事件将中止保存操作。当事件停止时,将返回事件的结果

此外:

Model.beforeSave:将在计算要持久化的字段列表之前触发。它接收实体和选项作为参数。选项数组作为ArrayObject传递,因此它中的任何更改都将反映在每个侦听器中,并在事件结束时记住,以便可以用于其余的保存操作。在任何侦听器中返回false都将中止保存过程。如果使用事件API停止事件,则将返回事件对象的result属性。当您在侦听器中实现自己的保存策略时,这可能很有用

要执行之前在Cake2中所做的任何操作,只需修改
$entity
,因为实体已经替换了
模型::$data
属性

if(!empty($entity->picture['name'])

如果你不知道事件是如何运作的。也是必读的。它列出了所有已更改的内容。

从函数定义开始

Cake\ORM\Table::beforeSave(Event $event, EntityInterface $entity, ArrayObject $options)
由于CakePHP是自动调用函数的,因此调用函数的方式是这样的,因此按照函数定义构建函数:

// In PostsTable.php
public function beforeSave($event, $entity, $options) {

}
如果不确定发送的是什么数据,请使用CakePHP的
debug()
函数:

    debug($event); debug($entity); debug($options);
$entity
中找到数据后,使用它对数据执行您想要执行的操作:

    if (!empty($entity->picture['name'])) { ...

下面是我使用的一个示例:

use Cake\Event\Event;
public function beforeSave(Event $event)
{
    $entity = $event->getData('entity');
    if(!empty($entity->picture['name']){
       // your action here
    }
}

我已经更改了它,但beforeSave似乎被忽略了。我尝试了这个我添加到问题中作为测试,但是名称没有设置。@burzump这里发生的事情是:我得到了我想要做的,但是我使用了BeforeMarshall,而不是beforeSave。有什么问题吗?我只想将路径保存在数据库中,将文件保存在文件夹中。但在似乎忽略保存之前…请阅读手册;)<代码>您可以使用Model.beforemashall事件在请求数据转换为实体之前修改请求数据。我不知道为什么它不适合您。