Question

i am newbee in yii and i am learning at this moment ...

I am using in model this query to get assosiative array for my listbox

public function getAllCategories()
{


    $cats = $this->model()->findAll(array('select'=>'id,name'));
    $mainarr = array();

    foreach($cats as $obj)
        $mainarr["$obj->id"]=$obj->name;

    return $mainarr;
}

and on my form i am calling this function in my dropdownlist as this

<?php echo $form->dropDownList($model,'name',$model->getAllCategories());  ?>

I have so many drop down with many different queries and i dont find any faster way to do that and everytime i have to create above array to make it fulfill. Kindly advise me better and faster solution to populate if there is any using CActiveForm?

Était-ce utile?

La solution

Faster way, i'm not sure there is any other.

But you could reduce your code, using CHtml::listData(); function. Atleast you'll reduce having to define a function in the model class:

<?php 
    echo $form->dropDownList($model,
      'name',
      CHtml::listData(Modelname::model()->findAll(),'id','name')// $model->getAllCategories()
    );
?>

listData(); will get you that associative array with array('id'=>'name') format.

Edit:

To follow good mvc practices, you could use listData in the controller action, which displays this form, instead of the form view directly:

public function actionFormDisplayer(){
  // other code
  $list_for_name_dropdown = CHtml::listData(Modelname::model()->findAll(),'id','name');
  // other code
  // then in render pass this value also
  $this->render('viewname',
     array('dropdownoptions'=>$list_for_name_dropdown, // other data to pass
  ));
}

Then in your view you can use $dropdownoptions.

Autres conseils

If you want to display menu name in dropdown from menu mode then use this code $menu_model = Menu::model()->findAll();
$list = CHtml::listData($menu_model, 'menu_id', 'menu_name'); echo CHtml::dropDownList('categories', $category, $list, array('empty' => '(Select a category')); `

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top