我有一个带有字段(名称、摘要)的视图(_form.php)提交按钮。如果我点击提交按钮,它应该会更新一个模型的名称字段和另一个型号的摘要字段。这两个模型都属于不同的数据库。有人能帮上忙吗。我为此尝试了以下操作
在_form.php(测试)中
<?php echo $form->labelEx($model, ‘name’); ?>
<?php echo $form->textField($model, ‘name’, array(‘size’ => 60, ‘maxlength’ => 250)); ?>
<?php echo $form->error($model, ‘name’); ?>
<?php echo $form->labelEx(Test1::model(), ‘summary’); ?>
<?php echo $form->textField(Test1::model(), ‘summary’, array(‘size’ => 60, ‘maxlength’ => 250)); ?>
<?php echo $form->error(Test1::model(), ‘summary’); ?>
<?php echo CHtml::submitButton($model->isNewRecord ? ‘Create’ : ‘Save’); ?>
在TestController.php中
public function actionCreate() {
$model = new Test;
if (isset($_POST['Test'])) {
$model->attributes = $_POST['Test'];
if ($model->save()) {
$modeltest1 = new Test1;
$modeltest1->attributes = $_POST['Test1'];
$modeltest1->Id = $model->Id;
if ($modeltest1->save())
$this->redirect(array('view', 'Id' => $model->Id));
}
}
$this->render('create', array(
'model' => $model,
));
}
此代码不起作用。如何使它适用于不同的数据库。我关注了下面的链接。
http://www.yiiframework.com/wiki/291/update-two-models-with-one-view/
这段代码实际上应该可以工作,但它很糟糕。
我想你根本不了解什么是模型,它在Yii中做什么,以及如何渲染和创建表单。
我会尽力解释它应该是怎样的。
首先,不要在视图中使用Test::model()
,除非你想从中调用一些函数(但尽量避免)。它可以通过从控制器传递来完成:
public function actionCreate() {
$model_name = new Name;
$model_summary=new Summary;
//something here
$this->render('create', array(
'name' => $model_name,
'summary'=>$model_summary,
));
}
进行渲染时,将变量传递到视图(name_in_view=>$variable)
第二。在您的视图中,您可以使用您的变量。
<?php echo $form->labelEx($name, ‘name’);
echo $form->textField($name, ‘name’, array(‘size’ => 60, ‘maxlength’ => 250));
echo $form->error($name, ‘name’);
echo $form->labelEx($summary, ‘summary’);
echo $form->textField($summary, ‘summary’, array(‘size’ => 60, ‘maxlength’ => 250)); ?>
echo $form->error($summary, ‘summary’); ?>
echo CHtml::submitButton($model->isNewRecord ? ‘Create’ : ‘Save’); ?>
第三。你需要了解什么是模型。在这种情况下,它是扩展CActiveRecord的类。控制器中的代码应该像这样:
public function actionCreate() {
$model_name = new Name;
$model_summary=new Summary;
if (isset($_POST['Name']))
$model_name->attributes=$_POST['Name'];
if (isset($_POST['Summary']))
$model_name->attributes=$_POST['Summary'];
if ($model_name->save()&&$model_summary->save())
$this->redirect(array('view', 'Id' => $model->Id));
$this->render('create', array(
'name' => $model_name,
'summary'=>$model_summary,
));
}
这里的$model->attributes=$_POST[]
是属性的大量赋值,所以它们在规则中必须是安全的。您总是可以用手(1乘1)指定属性,或者形成一个数组并从数组中推送它。