php yii framework populate CActiveform dropdownlist data by model directly?

wolvorinePk picture wolvorinePk · Jul 20, 2012 · Viewed 8.8k times · Source

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?

Answer

bool.dev picture bool.dev · Jul 20, 2012

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.