简体   繁体   中英

Do Partial Views Need Separate Controllers if they Use Different Models?

I've created a series of partial views for a page in our Yii Framework site. Each partial view has it's own model because they call subsections of the main model class. Since each partial view has it's own model, do I need separate controller classes for each?

My loadModel portion of the User controller is as follows:

public function loadModel($id,$model_name='Users')
{
    $model=Users::model()->findByPk($id);
    if($model===null)
        throw new CHttpException(404,'The requested page does not exist.');
    return $model;
}

It is being called from this section of the User Controller:

 public function actionProfile($id=''){        

        $user = Users::model()->find('username=:id', array
                (':id' => Yii::app()->user->id));           
        if(!$id){
            $id = $user->id;
            if(!$id)
            $this->redirect('login');
        }
        if( getUserSess('user_type') == 'Sitter') {
            $this->render('profile_detail', array('user_id' => $id ));
        } else {
            $this->render('petowner_profile_detail',array(
        'model'=>$this->loadModel($id),
    ));
        }
    }

I think I understand what you are trying to do. My answer would be no, you don't need separate controller actions for each partial view. I would create a view that then calls all the partial views. If you use gii to create your CRUD functionality you will see both the create and edit views call a partial view of the form. You would do this same thing only call multiple partial views in your view file. If you need different models just make sure your controller passes them to your main view file first so that it can then pass them on to the partial views. Hopefully that helps you out.

Here is the code if there is no relationship:

$partialUser = new PartialUser::model->findByAttributes(array('uid'=>$id)); //IF NOT UID PUT WHATEVER YOU HAVE THE COLUMN NAME

            $this->render('petowner_profile_detail',array(
                'model'=>$this->loadModel($id),
                'partialUser' => $partialUser,
            ));

If you did have a relationship setup you could easily just do this:

$current_user = $this->loadModel($id);
            $this->render('petowner_profile_detail',array(
                'model'=> $current_user,
                'partialUser' => $current_user->partialUser, //whatever you set the name of the relationship as in the model
            ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM