Multiple select storing and viewing from one controller with two or more models

Hi,

I have tables cities(id, name), companies(id, name, created_at), companies_cities(id, company_id, city_id, created_at)

I have given the relation as HAS_MANY for ‘CompaniesCities’ model that is ‘city’ => array(self::HAS_MANY, ‘Cities’, ‘city_id’),

I am calling the CompaniesCities model in the companies controller under actionCreate and calling calling from the form to select multiple cities

<?php echo $form->dropDownList($model1,‘city_id[]’,CHtml::listData(Cities::model()->findAll(), ‘id’, ‘city_name’), array(‘prompt’=> ‘Please Select’, ‘multiple’ => ‘multiple’)); ?>

Under CompaniesCities controller->actionCreate i am trying to store the selected cities

$model1->attributes=$_POST[‘CompaniesCities’];

$model1->company_id=$model->id;

$model1->save();

This scenario is working if i select one value. If i select multiple cities then it is not storing any values. And i also want to display the stored values. If i declare the HAS_MANY relation i am not able to display the city_name through the _view file from companies_cities (CRUD)

<? echo CHtml::encode($data->city->city_name); ?>

Please tell me on how to do it.

Thanks in advance.

Could anyone can help me out.

What I would suggest is this:




$CompaniesCities = $_POST['form-name']['city_id'];


foreach ($CompaniesCities as $city){

     $modelg=new Companies_City;

				

     $modelg->codigoal=$_POST['form-name']['company_id'];

     $modelg->codigom=$city;


     if ($modelg->save()) {

	    $allGood=true;

     }else{

	    $allGood=false;

     }

				

}



A couple of things, if I understand your code correctly, you are putting this code from companies cities controller but if you want to save the info each time a company is created then you have to call it after you save the company, meaning it has to run in the actionCreate of the Company controller. The other thing is you dont have to declare the city_id as an array, you just have to give it a simple name and the form automatically will create an array.

For the other question, you can try $data.city.city_name, Im not sure about that but i think that is the way $data displays the relations.

Hope it helps.

By the way I use the $allGood var just to make sure every record was saved correctly.

IMHO, the easier way is use some of exists extension to make such work. For example esaverelatedbehavior or advancedrelationsbehavior. Both of them will help you to save company’s cities with 2 lines of code.

Hi Thanks for the help,

I have already came across to write with foreach. I thought there would be some easier way in YII.

Could please tell me on how to display with has_many relation. When i call it gives me unknown column and in the stack trace it shows the query with t0_c0 column. Any idea on how to call.