将变量从控制器传递到模型 (beforeSave) (Upload Field) CakePHP

Pass variable from controller to model (beforeSave) (Upload Field) CakePHP

我真的需要知道这个问题才能完成我的工作。

这里我举一个模型和控制器的例子。 我想将 $final_name 从控制器传递到我的模型

的 beforeSave()
public function admin_add() {
    if($this->request->is('post')) {
        if($this->data['Client']['file']['tmp_name'] != '') {
                // Upload block
                $tmp_file = $this->data['Client']['file']['tmp_name'];
                $file = new File($tmp_file);
                if($file->mime() == "image/jpeg" or "image/png") {
                    $ext = explode('.', $this->data['Client']['file']['name']);
                    $name = md5($this->data['Client']['file']['name']);
                    $file->copy(IMG_DIR . 'portfolio\' . $name . '.' . end($ext));
                    $final_name = $name . "." . end($ext); // File name with extension
                }
                // If save
            if($this->Client->save($this->request->data)) {
                $this->Session->setFlash('Client cadastrado com sucesso!', 'admin_flash');
            }
        }
    }
}

在我的客户端模型中

public function beforeSave($options = array()) {
    if($this->data['Client']['file']['name'] != null) {
        $this->data['Client']['file'] = $final_name;
    }
    return parent::beforeSave($options);
}

在控制器中

$this->request->data['Client']['final_name'] = $name . "." . end($ext);

模型中

public function beforeSave($options = array()) {
if($this->data['Client']['file']['name'] != null) {
    $this->data['Client']['file'] = $this->data['Client']['final_name'];
}
return parent::beforeSave($options);
}

CakePHP3 更新

将变量从控制器传递到 table beforeSave, afterSave ?

// Examples
// In Controller
$this->Article->save($data, ['passVariable' => 'passedData']);

// in Table

public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options)
    {
        if (isset($options['passVariable'])) {
            // implement your code
        }
    }

阅读更多: https://api.cakephp.org/3.8/class-Cake.ORM.Table.html#_save

但是在保存之前修改数据的好地方是:

https://book.cakephp.org/3.0/en/orm/saving-data.html#before-marshalhttps://book.cakephp.org/3.0/en/orm/entities.html#accessors-mutators