首页 > 解决方案 > beforeSave 方法在 cakephp3 中不起作用

问题描述

我有数据要先修改,然后再将其保存到我的数据库中,因此我研究了 beforeSave 方法。

我有一个用户的图片输入,我想在成功验证后将其路径保存在我的数据库中,这是我当前的代码:

    src/model/table/UsersTable.php

    use Cake\ORM\Entity;
    use Cake\Event\Event;
    use ArrayObject;
    use Cake\Validation\Validator;

    public function validationDefault(Validator $validator)
    {            
       $validator
            ->allowEmptyFile('image_location')
            ->add('image_location', 
            [
                'mimeType' => [
                    'rule' => array('mimeType', array( 'image/png', 'image/jpg', 'image/jpeg')),
                    'message' =>  'Please upload images only (png, jpg).'
                ],
                'fileSize' => [
                    'rule' => array('fileSize', '<=', '10MB'),
                    'message' => 'Image must be less than 10MB.'
                ],
            ]);
                        
        return $validator;
    }

    public function beforeSave($event, $entity, $options)
    {
        if ($entity->image_location['name']) {
            $tmp = $entity->image_location['tmp_name'];
            $hash = rand();
            $date = data("Ymd");
            $image = $dage.$hash;
            $target = WWW_ROOT.'img'.DS.'uploads'.DS;
            $target = $target.basename($image);
            $image_location = "uploads/".$image;
            $entity->image_location = $image_location;
            move_uploaded_file($tmp, $target);
        }
    }

唯一有效的部分是验证部分,但是在成功验证图像文件后, beforeSave 方法不起作用。

我当前的代码有什么错误,或者如何在 cakephp3 中使用 beforeSave 方法。

非常感谢!

编辑

我什至试过这条线:

public function beforeSave($event, $entity, $options)
{
    debug($entity);
    if ($entity->image_location['name']) {
        $tmp = $entity->image_location['tmp_name'];
        $hash = rand();
        $date = data("Ymd");
        $image = $dage.$hash;
        $target = WWW_ROOT.'img'.DS.'uploads'.DS;
        $target = $target.basename($image);
        $image_location = "uploads/".$image;
        $entity->image_location = $image_location;
        move_uploaded_file($tmp, $target);
    }
}

检查 beforeSave 方法正在接收的实体,但它不输出任何内容。

标签: cakephpcakephp-3.xbefore-save

解决方案


推荐阅读