当我调用CreateController时出现此错误:“get_class()期望参数1为对象,给定数组为”
Controll / actionCreate()如下:
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'));
?>
_form.php的字段如下:
<div class="row">
<?php echo $form->labelEx($model2,'aciklama'); ?>
<?php echo $form->textField($model2,'aciklama'); ?>
<?php echo $form->error($model2,'aciklama'); ?>
</div><!-- row -->
答案 0 :(得分:2)
$this->renderPartial('_form', array(
'model' => array(
'model'=>$model,
'model2'=>$model2
),
'buttons' => 'create'
));
上面的代码意味着文件_form.php
可以访问两个变量:
$ model - 两个元素的数组,以及$ buttons - string。
因此,要访问第一个模型,您必须编写$model['model']
,第二个 - $model['model2']
。
但在此代码中
<?php echo $form->labelEx($model2,'aciklama'); ?>
<?php echo $form->textField($model2,'aciklama'); ?>
<?php echo $form->error($model2,'aciklama'); ?>
您正在尝试访问未定义的变量$model2
。这应该会引起各自的错误。
错误没有得到的东西让我在列出代码之前的某个地方以类似的方式访问变量$model
,如下所示:
echo $form->labelEx($model,'test');
在上面的代码中$model
是数组(因为你传递了数组)。这就是您收到预期对象的错误的原因。
因此,您应该传递模型或以适当的方式访问它们。
我希望这会有所帮助。
答案 1 :(得分:0)
我解决了另一个问题。也许有人可能需要......
(CDbCommand无法执行SQL语句:SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键)
if ($model->save(false) && $model2->save(false)) {
if (Yii::app()->getRequest()->getIsAjaxRequest())
Yii::app()->end();
else
$this->redirect(array('view', 'id' => $model->ogrenci_id));
}
到
$a=$model2->save(false);
$model->adresler_id=$model2->adresler_id;
if ($a && $model->save(false)) {
if (Yii::app()->getRequest()->getIsAjaxRequest())
Yii::app()->end();
else
$this->redirect(array('view', 'id' => $model->ogrenci_id));
}