Yii2 ActiveForm dropDownList值在表单中设置但在beforeSave中为空

时间:2016-09-28 11:23:04

标签: yii2 yii2-advanced-app

我一直在寻找这个,但无法找到答案。

我正在使用Gii CRUD生成器,我为字段进行了自定义更新。与验证规则无关,因为我没有收到任何错误。

以下是方案:我想要一个dropDownList,用户从中选择一个列表项,并在模型中更新该项。

问题:当我在_form.php中记录值时,它们会被正确检索并显示在表单上。但是,当我单击更新按钮并在beforeSave中记录模型值时,我发现目标字段为空。我没有错误,模型用空字段保存。

以下是我的代码。

_form.php这个

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.orm import relationship

from .base import Base as BaseModel


class BannedUser(BaseModel, declarative_base()):
     __tablename__ = 'banned_users'

     id = Column(Integer, primary_key=True)
     user_id = Column(Integer, ForeignKey('users.id'))
     user = relationship('User', back_populates='banned_users')
     reason = Column(String)
     time_end = Column(DateTime)

型号:

<?php $form = ActiveForm::begin(); ?>

    ....

    <?php $list = ArrayHelper::map($this->context->getListItems($model->id), 'id', 'item'); ?>
    <?= $form->field($model, 'item')->dropDownList($list, ['prompt'=>'Select...']) ?>

    ....

<?php ActiveForm::end(); ?>

上述结果:

<?php

    ....

    public function beforeSave($insert)
    {
        echo '<pre>';
        print_r($this);
        echo '</pre>';
        exit();

        return parent::beforeSave($insert);
    }

    ....

?>

请注意是如何为空。

任何提示?

1 个答案:

答案 0 :(得分:0)

我无法说出真正的问题,但在我的情况下,我有2个模型,孩子有自己的规则,父母有自己的规则。我试图合并这两个规则(来自父模型和子模型)并且它不起作用。所以我在父模型中移动了所有规则。