yii2 ActiveDataProvider in combination with ActiveForm?

893 views Asked by At

I'm trying to use an ActiveDataProvider as the source for my ActiveDataForm. However I am unable to access the information. Not from within the view or the controller. How ever the diseaseList + ListView is working.

I can't seem to figure out where I went wrong. Even when I get a disease like so:

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

I cannot access the data. Only when I initiate a NEW disease in the controller I can get the ActiveForm to work properly.

Controller:

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]);
}

In my view:

<?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(); ?>

Here is the error I'm receiving. Error

1

There are 1 answers

2
Ali MasudianPour On BEST ANSWER

There is something wrong here, which is:

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

That should be:

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

To know why you get this error: You are passing ActiveQuery to your ActiveForm by $disease = Disease::find()->where(['id'=>1]) which is wrong. ActiveForm does not accept ActiveQuery.