Update two model with one view

You are viewing revision #3 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#2)next (#4) »

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 $form = $this->beginWidget(‘CActiveForm’, array(
        ‘id’ => ‘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 $form = $this->beginWidget(‘CActiveForm’, array(
        ‘id’ => ‘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:

$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:

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