yii2 ActiveDataProvider与ActiveForm结合使用?

时间:2014-11-18 15:26:58

标签: php yii yii2 cactivedataprovider

我正在尝试使用ActiveDataProvider作为ActiveDataForm的源代码。 但是我无法访问这些信息。不在视图或控制器内。该疾病列表+ ListView是如何工作的。

我似乎无法弄清楚我哪里出错了。即使我得了这样的疾病:

$disease = new Disease();
$disease = Disease::find()->where(['id'=>1]);

我无法访问数据。只有当我在控制器中发起新疾病时,我才能使ActiveForm正常工作。

控制器:

public function actionIndex($id = 1)
{
    $disease = new ActiveDataProvider([
        'query' => Disease::find()
        ->where(['id'=>$id]),
            'pagination' =>  [
                'pageSize' => 1,
            ]
        ]);

    $diseaseList = new ActiveDataProvider([
        'query' => Disease::find()->orderBy('LOWER(name)'),
            'pagination' =>  [
                'pageSize' => 20,
            ]
        ]);
    return $this->render('index', ['disease' => $disease, 'diseaseList' => $diseaseList]);
}

在我看来:

<?php 
echo ListView::widget([
'dataProvider' => $diseaseList,
'itemView' => function($diseaseList, $key, $index, $widget)
{
    return 
        Html::a($diseaseList->name,
            Url::toRoute(['disease/index', 'id' => $diseaseList->primaryKey]));
}
]); 
?>

<?php
    $form = ActiveForm::begin([
    'id' => 'disease-form-vertical'
    ]);
    ?>
        <?= $form->field($disease, 'name') ?>
        <?= $form->field($disease, 'description') ?>
        <?= $form->field($disease, 'transmission') ?>
        <?= $form->field($disease, 'actions') ?>
        <?= $form->field($disease, 'report') ?>
        <?= $form->field($disease, 'exclusion') ?>
        <?= $form->field($disease, 'notes') ?>
    <div class="form-group">
        <?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
    </div>
    <?php ActiveForm::end(); ?>

这是我收到的错误。 Error

1 个答案:

答案 0 :(得分:1)

这里有问题,这是:

$disease = Disease::find()->where(['id'=>1]);

应该是:

$disease = Disease::find()->where(['id'=>1])->one();

要知道您收到此错误的原因:您将ActiveQuery传递给ActiveForm $disease = Disease::find()->where(['id'=>1]),这是错误的。 ActiveForm不接受ActiveQuery