dropDownList

Disable a DropDownList (It defaults to false)

'htmlOptions'=>array('disabled'=>'true');


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,
              $model->genderOptions,
              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,
              $list,
              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',
                          $country,
                          array('multiple'=>'multiple',
                                            'name'=>'values',
                                            'class'=>'multiselect',
                                            'title'=>"страны",
                                            '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;
        else
            $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(){
    $arr=self::model()->findAll();
    return CHtml::listData($arr, 'id', 'name', 'typeName' );
}

//this will construct:
$arr=array(
    'Cars'=>array(
        'Ford'=>'Ford',
        'BMW'=>'BMW',
    ),
    'Phones'=>array(
        'HTC'=>'HTC',
        'Nokia'=>'Nokia',
    ),
);

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');
               ...
	       $this->render('create',array(
		    'model'=>$model,
                    'categories'=>$categories,
	       ));
        }
}

// in views/product/create.php
 echo $this->renderPartial('_form', array(
     'model'=>$model,
     'categories'=>$categories,
 ));

// in views/product/_form.php
$form=$this->beginWidget('CActiveForm', array(
	'id'=>'product-form',
	'enableAjaxValidation'=>false,
));
...
echo $form->dropDownList(
        //reference the model of current form (e.g. Product::model())
        $model,
        //name of the referenced fiel in the model 
        'category', 
        //array of the key=>value pairs to display
        $categories, 
        //other options
        array (
            "disabled"=>"disabled"
            //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.
                    'value3'=>array('unselectValue'=>true),
),
        ));
...
$this->endWidget();
CHtml::listData($posts,'id',function($model) {
	return CHtml::encode($model->title);
});

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

CHtml::dropDownList('country', '', Moto::model()->dropDown2('',0), array(
       'empty'=>Yii::t('default', 'Выберите марку'),
       'class'=>"select-panel__select",
       'ajax'=>array(
               'type'=>'GET',
               'url'=>CController::createUrl('site/scatmoto'), 
               'update'=>'#models',
               'success' => 'function(html,script,script1){
                             jQuery("#models").html(html);
                             eval(script1);
                       }',
                'data'=>array(
                       'id'=>'js:this.value',
                       'to'=>'models'
                 ),
         ),
));
?>
<span   id="models"></span>
<span   id="volume"></span>


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

echo  CHtml::dropDownList('volume_', '', Moto::model()->dropDown2('',$_GET[id]), array(
                    'empty'=>Yii::t('default', 'Выберите модель'),
                    'class'=>"select-panel__select",
                    'ajax'=>array(
                        'type'=>'GET',
                        'url'=>CController::createUrl('site/scatmoto'), 
                        'update'=>'#volume',
                        'data'=>array(
                            'id'=>'js:this.value',
                            'to'=>'volume',
                            ),
                        'success' => 'function(html){
                                           alert(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();
    //Если подкатегорий больше нет
    if(!$data){
        echo CHtml::activeHiddenField($product_model, 'cat_id', array('value'=>$_POST['uplevel_id']));
    } else {
        echo CHtml::activeDropDownList($product_model,
            'cat_last',
            $data,
            array('prompt'=>'Выберите',
                'onchange'=> CHtml::ajax(array('type'=>'POST',
                    'url'=>CController::createUrl('dynamiccat'),
                    '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
Archives
Categories
%d bloggers like this: