unchanged
Title
Update two model with one view
Suppose to have two models: Users and Emails. You do not want to store email in
a Users model. And User can have 0 or many emails. This is the form generated to
create a new user (just username).
~~~
[php]
<?php $form = $this->beginWidget(‘CActiveForm’, array(
‘id’ =>
‘anagrafiche-form’,‘users-form’,
‘enableAjaxValidation’ => false )); ?>
<?php echo $form->labelEx($model, ‘username’); ?>
<?php echo $form->textField($model, ‘username’,
array(‘size’ => 60, ‘maxlength’ => 250)); ?>
<?php echo $form->error($model, ‘username’); ?>
<?php echo CHtml::submitButton($model->isNewRecord ? ‘Create’
: ‘Save’); ?>
<?php $this->endWidget(); ?>
~~~
First, ... we can add email field to _form.php template passing Emails::model()
as model.
~~~
[php]
<?php $form = $this->beginWidget(‘CActiveForm’, array(
‘id’ =>
‘anagrafiche-form’,‘users-form’,
‘enableAjaxValidation’ => false )); ?>
<?php echo $form->labelEx($model, ‘username’); ?>
<?php echo $form->textField($model, ‘username’,
array(‘size’ => 60, ‘maxlength’ => 250)); ?>
<?php echo $form->error($model, ‘username’); ?>
<?php echo $form->labelEx(Emails::model(), ‘email’); ?>
<?php echo $form->textField(Emails::model(), ‘email’,
array(‘size’ => 60, ‘maxlength’ => 250)); ?>
<?php echo $form->error(Emails::model(), ‘email’); ?>
<?php echo CHtml::submitButton($model->isNewRecord ? ‘Create’
: ‘Save’); ?>
<?php $this->endWidget(); ?>
~~~
Second ... we could update actionCreate of UsersController by adding the code
like below:
~~~
[php]
$modelEmail = new Emails;
$modelEmail->attributes = $_POST['Emails'];
$modelEmail->iduser = $model->id;
if ($modelEmail->save())
$this->redirect(array('view', 'id' => $model->id));
~~~
Maybe Users::actionCreate(); will appear like this:
~~~
[php]
public function actionCreate() {
$model = new Users;
if (isset($_POST['Users'])) {
$model->attributes = $_POST['Users'];
if ($model->save()) {
$modelEmail = new Emails;
$modelEmail->attributes = $_POST['Emails'];
$modelEmail->iduser = $model->id;
if ($modelEmail->save())
$this->redirect(array('view', 'id' => $model->id));
}
}
$this->render('create', array(
'model' => $model,
));
}
~~~