开发者

Passing models in array format to views in YII

How can I pass the model in array format. I want to pass models in this format from controller to view:-

Users[user_contact]=Contact Users[user_contact][contat_city]=City Users[user_contact][contact_state]=state

This is what I am doing

public function actionCreate() {
    $user = new Users;
    $presContact = new Contacts;
    $presCity = new Cities;
    $presState = new States;
    $contactArr = array();
    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);
    if (isset($_POST['Users'])) {
        $transaction = CActiveRecord::getDBConnection()->beginTransaction();
        $contactArr = CommonFunctions::saveContact($_POST['Users']['user_pres_contact'],'user_pres_contact',$errorArr);
        $presContact = $contactArr['contact'];
        $presCity = $contactArr['city'];
        $presState = $contactArr['state'];
        $user->attributes = $_POST['Users'];
        $user->user_pres_contact_id = $presContact->contact_id;
        if($user->save()){
            $transaction->commit();
            $this->redirect(array('view', 'id' => $user->user_id));
        } else {
            $transaction->rollback();

        }
    }

    $this->render('createUser', array(
        'Users' => $user,
        'Users[\'user_pres_contact\']'=>$presContact,
        'Users[\'u开发者_开发问答ser_pres_contact\'][\'contact_city\']'=>$presCity,
        'Users[\'user_pres_contact\'][\'contact_state\']'=>$presState,
    ));
}

I am able to access only $users but I m not able to access $Users['user_pres_contact'] in the view


That's because you are assigning them as strings... The correct way of doing things would be (btw, what you are asking for can't done literally, it is impossible to assign 2 values to one key):

$user = array(
'user_press_contact' => array(
  'contact' => $presContact,
  'city' => $presCity,
  'state' => $presState,
 ),
);


$this->render('createUser', array(
        'Users' => $user,
    ));

It will give you $Users['user_press_contact']['contact'] for the name in the view, etc.


You can use

$user->getAttributes() //it returns an array of data.

Hope that's usefull


It is possible to solve this using model relations? You can define a relation from the User model to the City model (e.g. naming it relation_to_city), then you can just assign the user model in the controller

$this->render('view', 'user'=>$user);

and access the city (from the view)

$user->relation_to_city
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜