yii2下拉列表中的空值

时间:2016-04-20 08:52:11

标签: php object yii2 yii2-basic-app yii2-validation

我有一个活动表格的下拉列表我正确显示数据但是当我想插入下拉列表中所选值的值时,该值为空。

在我的控制器中:

        $model = new AjoutRessourceForm();

        if ($model->load(Yii::$app->request->post()) && $model->validate())
        {
            if ($ressource = $model->addRessource())
            {
                return $this->redirect(['form/ressource']);
            }
        }
        $sql = "select idEtatRessource, nomEtatRessource from etat_ressource";
        $command = $connection->createCommand($sql);
        $data = $command->queryAll();
        $etats = ArrayHelper::map($data, 'idEtatRessource', 'nomEtatRessource');

        return $this->render('/form/newRessource', ['model' => $model, 'etats' => $etats, 'types' => $types]);

在我看来:

<?= $form->field($model, 'idEtatRessource')->dropDownList($etats) ?>

在模型中:

    $histEtatRessource                  = new HistoriqueEtatRessource();
    $histEtatRessource->idRessource     = $this->idRessource;
    $histEtatRessource->idEtatRessource = $this->idEtatRessource;

    if ($ressource->save() && $histEtatRessource->save())
    {
        return $ressource;
    }

我有一个IntegrityException,因为$this->idEtatRessource的值为null(我的数据库中的主键)

谢谢!

--- --- EDIT

当我通过$_POST['idEtatRessource']代替$this->idEtatRessource时,它工作,我不知道为什么!请帮忙;)

1 个答案:

答案 0 :(得分:0)

我发现问题所在:

我没有对这些字段进行规则验证,因此当我将这两个字段的模型值加载为null时。

来源:model->attributes in Yii2 always has NULL value