Search code examples
phptemplatesyiiyii-cmodel

Yii Collect Data For Two Or More Models ( Get_Class() Expects Parameter 1 To Be Object, Array Given )


I get this error when I call CreateController : "get_class() expects parameter 1 to be object, array given "

Controll/actionCreate() is as follows:

public function actionCreate() {
    $model = new Ogrenci;
    $model2 =new Adresler;
    $this->performAjaxValidation($model, 'ogrenci-form');
    $this->performAjaxValidation($model2, 'ogrenci-form');
    if (isset($_POST['Ogrenci'],$_POST['Adresler'])) {
        $model->setAttributes($_POST['Ogrenci']);
        $model2->setAttributes($_POST['Adresler']);
        if ($model->save(false) && $model2->save(false)) {
            if (Yii::app()->getRequest()->getIsAjaxRequest())
                Yii::app()->end();
        else
            $this->redirect(array('view', 'id' => $model->ogrenci_id));
        }
    }
    $this->render('create', array( 'model' => $model,'model2' => $model2));
}

create.php:

<?php  $this->renderPartial('_form', array(
    'model' => array('model'=>$model,'model2'=>$model2),
    'buttons' => 'create'));
?>

And _form.php's fields is as follows:

<div class="row">
    <?php echo $form->labelEx($model2,'aciklama'); ?>
    <?php echo $form->textField($model2,'aciklama'); ?>
    <?php echo $form->error($model2,'aciklama'); ?>
</div><!-- row -->

Solution

  • $this->renderPartial('_form', array(
        'model' => array(
            'model'=>$model,
            'model2'=>$model2
        ),
        'buttons' => 'create'
    ));
    

    code above means that file _form.php will have access to two variables: $model - array of two elements, and $buttons - string.

    So, to get access to first model you have to write $model['model'], second - $model['model2'].

    but in this code

    <?php echo $form->labelEx($model2,'aciklama'); ?>
    <?php echo $form->textField($model2,'aciklama'); ?>
    <?php echo $form->error($model2,'aciklama'); ?>
    

    You are trying to access undefined variable $model2. And this should raise respective error.

    The thing that error is not got makes me thinking that somewhere before listed code you access variable $model in the similar way, something like this:

    echo $form->labelEx($model,'test');
    

    In the above code $model is array(because you passed array). That is why you receive error that object is expected.

    So, you should either pass models or access them in a proper way.

    I hope this helps.