Yii2在保存模型之前获取值

时间:2016-12-07 17:22:47

标签: yii2 before-save

我想在我的模型中创建特殊验证,我需要获取transaction_id,但它返回null。它的normlan因为模型不能保存,但是有一些技巧可以让我在保存之前得到这个transaction_id吗?

我读到了Blameable Behavior,但它在验证后节省了价值

型号:

<?php

class CommentForm extends ActiveRecord
{
    public $type;
    public $content;

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['type'], 'required'],
            [['content'], 'string', 'length' => [1, 140]],
            [['content'], 'required',],
            [['type'], 'in', 'range' => Message::getCommentTypes()],
            [['transaction_id'], 'canSendComment', 'skipOnEmpty' => false, 'skipOnError' => false],
        ];
    }

    public function canSendComment($attribute)
    {
        $message = Message::find()
            ->where([
                'transaction_id' => $this->transaction_id,
                'sender_id' => $this->sender_id,
                'type' => Message::getCommentTypes(),
            ])
            ->one();
    }
}

控制器行动

public function actionShow($id)
    {

$transaction = Transaction::find()        
            ->where(['id' => $id])
            ->one();        


$comment = new CommentForm();

        if ($comment->load(Yii::$app->request->post()) && $comment->validate()) {

            $comment->transaction_id = $id;
            $comment->sender_id = Yii::$app->user->identity->id;
            $comment->save();

            Yii::$app->getSession()
                ->addFlash('success', '<strong>success</strong> OK!!.');

            return $this->redirect(['transaction/show', 'id' => $id]);
        }


        return $this->render($view, [  
    'transaction' => $transaction,
            'comment' => $comment,
        ]);
    }

0 个答案:

没有答案