tags:

views:

112

answers:

3

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[\'user_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

+1  A: 

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.

Blizz
As a sidenote: you should really look into CActiveRecord derived classes, what you are doing is a serious detour and can be handled a lot better in Yii.
Blizz
A: 

You can use

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

Hope that's usefull

chahedous
A: 

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
ZaQ