Update two models with one view

Suppose I have two model name User and UserDetail. In UserDetail I put the ID of User when create new User (Foreign key). UserDetail contains the details of user like email, address, ….etc…
How can we update two models with only one view ?

In your yii controller applicaton, create whatever action you want. In here I create ActionCreate()

public function actionCreate()
{
    $model = new User;
    $modelDetail = new UserDetail;
    if(isset($_POST['User'], $_POST['UserDetail']))
    {
        $model->attributes=$_POST['User'];
        $modelDetail->attributes=$_POST['UserDetail'];

        $valid=$model->validate();
        $valid=$modelDetail->validate() && $valid;

        if($model->save())
        {
            $modelDetail->user_id = $model->ID;
            $modelDetail->save();
            // ...redirect to another page
        }
    }
    $this->renderPartial('index',array('model'=>$model, 'modelDetail' => $modelDetail));
}

In view page

<?php echo CHtml::beginForm(); ?>

    <?php echo CHtml::errorSummary(array($a,$b)); ?>

    <div class="row">
        <?php echo $form->labelEx($model,'username'); ?>
        <?php echo $form->textField($model,'username'); ?>
        <?php echo $form->error($model,'username'); ?>
    </div>

    <div class="row">
        <?php echo $form->labelEx($modelDetail,'email'); ?>
        <?php echo $form->textField($modelDetail,'email'); ?>
        <?php echo $form->error($modelDetail,'email'); ?>
    </div>

<?php echo CHtml::endForm(); ?
Share with your friendsShare on Google+Share on LinkedInPin on PinterestTweet about this on TwitterShare on Facebook
  • http://fb.com/rohisuthar Rohit Suthar

    Nice code,

    But can you tell how to update or edit my existing records???

    how can i do through actionUpdate function… my actionUpdate function working fine but record doesn’t updated.

    my code –

    public function actionUpdate($id){

    $model=$this->loadModel($id);
    $user = Channeluser::model()->findByAttributes(array(‘branch_id’=>$model->Id));

    if(isset($_POST['Branchmaster'], $_POST['Usermaster'])){

    $model->attributes=$_POST['Branchmaster'];
    $user->attributes=$_POST['Usermaster'];

    $valid=$model->validate();
    $valid=$user->validate() && $valid;

    if($valid){
    $model->save();
    $user->save();

    $this->redirect(array(‘view’,’id’=>$model->Id));
    }
    }

    $this->render(‘update’,array(
    ‘model’=>$model,
    ‘user’=>$user,
    ));
    }