Disable a DropDownList (It defaults to false)


echo CHtml::dropDownList('listname', $select,
              array('M' => 'Male', 'F' => 'Female'));

В модели:
public function getGenderOptions(){
    return array('M' => 'Male', 'F' => 'Female');
В представлении:
<?php echo CHtml::dropDownList('listname', $select,
              array('empty' => '(Select a gender'));

// retrieve the models from db
$models = categories::model()->findAll(
                 array('order' => 'category_name'));

// format models as $key=>$value with listData
$list = CHtml::listData($models,
                'category_id', 'category_name');
echo CHtml::dropDownList('categories', $category,
              array('empty' => '(Select a category'));

Для множественного выбора делаю так:

echo CHtml::form('','POST',array ('enctype' =>'multipart/form-data'));
echo CHtml::errorSummary($model);
echo CHtml::activeLabel($model, 'values');

$country = array('RUS' => 'Россия',
                      'UKR' =>'Украина', 
                      'BLR' => 'Белоруссия', 
                      'ITL' => 'Италия');
$selectedValues = array('BLR'=> Array ( 'selected' => 'selected' ),
                    'ITL' => Array ( 'selected' => 'selected' )); 

echo CHtml::activeDropDownList($model,'values',
                                            'options' => $selectedValues,
echo CHtml::endForm($model);

echo CHtml::activeListBox($model, 'provider_id', $ddl, array(
                'empty' => 'Выберите поставщика',
                'htmlOptions' => array('multiple'=>'multiple'))

$selectedValues = array($provider_id => Array('selected' => 'selected'));
            echo CHtml::activeDropDownList($model, 'provider_id[]', $ddl, array(
                'empty' => 'Выберите поставщика',
                'options' => $selectedValues,)

Manipulation with a list

//in the model
class Product extends CActiveRecord
    public function getReadableName()
        if ($this->parent == 0)
            $newName = str_repeat('&nbsp;', 3).$this->name;
            $newName = '<b>'.$this->name.'</b>';

        return $newName;

//in code
$model = ProductCategory::model()->queryAll();
$products = CHtml::listData($model,'id', 'readableName');

Use list in groups

//in model
static public function listOf(){
    return CHtml::listData($arr, 'id', 'name', 'typeName' );

//this will construct:

echo CHtml::dropDownList("list", '', $arr);

Use list in forms

class ProductController extends Controller
	public function actionCreate()
               $model=new Product;
               $category_ar = Category::model()->queryAll();
               $categories = CHtml::listData($category_ar,'id', 'name');

// in views/product/create.php
 echo $this->renderPartial('_form', array(

// in views/product/_form.php
$form=$this->beginWidget('CActiveForm', array(
echo $form->dropDownList(
        //reference the model of current form (e.g. Product::model())
        //name of the referenced fiel in the model 
        //array of the key=>value pairs to display
        //other options
        array (
            //empty: string, specifies the text corresponding to empty selection. 
            //Its value is empty.
            //This option can also be an array of value-label pairs.
            'empty' => '--- choose category ---',
            //encode: boolean, specifies whether to encode the values. Defaults to true.
            'encode'=> false,
            //prompt: string, specifies the prompt text shown as the first list option. 
            //Its value is empty. Note, the prompt text will NOT be HTML-encoded.
            'prompt' => '--- choose category ---',
            //options: array, specifies additional attributes for each OPTION tag.
            'options' => array(
                    'value1'=>array('disabled'=>true, 'label'=>'value 1'),
                    'value2'=>array('label'=>'value 2'),
                    //set the value that will be returned when no option is selected in multiple mode
                    //If 'unselectValue' is not set or set to NULL, the hidden field will not be rendered.
CHtml::listData($posts,'id',function($model) {
	return CHtml::encode($model->title);

onChange, метод контроллера

CHtml::dropDownList('country', '', Moto::model()->dropDown2('',0), array(
       'empty'=>Yii::t('default', 'Выберите марку'),
               'success' => 'function(html,script,script1){
<span   id="models"></span>
<span   id="volume"></span>

код контроллера который возвращает код в #models

echo  CHtml::dropDownList('volume_', '', Moto::model()->dropDown2('',$_GET[id]), array(
                    'empty'=>Yii::t('default', 'Выберите модель'),
                        'success' => 'function(html){

public function actionDynamiccat()
    $model = Categories::model()->findByPk($_POST['uplevel_id']);
    $data = Categories::model()
        ->findAll(array('condition' =>
        'lft>=:lft and rgt<=:rgt and level=:level',
        'params' => array(':lft' => $model->lft,
            ':rgt' => $model->rgt,
            ':level' => $model->level + 1
        'order' => 'lft ASC'
    $data = CHtml::listData($data, 'id', 'name');
    $product_model = new Products();
    //Если подкатегорий больше нет
        echo CHtml::activeHiddenField($product_model, 'cat_id', array('value'=>$_POST['uplevel_id']));
    } else {
        echo CHtml::activeDropDownList($product_model,
                'onchange'=> CHtml::ajax(array('type'=>'POST',
                    'data' => array('uplevel_id' => 'js:$(this).val()'),
                    'update'=> '#subcat_'.$model->level
        echo '<div id="subcat_'.$model->level.'"></div>';

Ну и чтобы добавить пустое поле в начале используем сложение массивов
Не надо ничего складывать, если опция empty

echo $form->dropDownList($model, 'category_id',
     array(""=>"") + CHtml::listData(
         Category::model()->findAll(), 'id', 'name')

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Recent Posts
Recent Comments
%d bloggers like this: