Update two models 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 $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,
        ));
    }
9 2
13 followers
Viewed: 46 682 times
Version: 1.1
Category: Tips
Written by: sensorario
Last updated by: SebK
Created on: Dec 19, 2011
Last updated: 7 years ago
Update Article

Revisions

View all history

Related Articles