5ome
5ome

Reputation: 147

Get selected value from CHtml::dropDownList

I have a question about Yii framework.

Let's say I have dropdown list like the code listed below.

I need to print selected value and I try to do it with $_POST['countries'] but nothing happened.

I just need the selected value to store in a variable so I can manipulate it.

<?php 
      echo CHtml::dropDownList('countries', $select = array(),
      CHtml::listData($countries, 'code', 'name'));
?>

Upvotes: 1

Views: 9720

Answers (2)

ineersa
ineersa

Reputation: 3435

You can also use an Ajax request. Its even better if you want to make some dependent dropdown lists. For example:

echo $form->dropDownList($profile, $field->varname,CHtml::listData(Countries::model()->findAll(),'short','title'), array(
    'class'=>"chzn-select",
    'empty'=>"Select country",  
    'ajax' => array(
                    'type' => 'POST',
                    'url'=>$this->createUrl('registration/state'),   
                    'update' => '#Profile_state',                        
                    'data'=>array('country'=>'js:this.value',), 
                    'success'=> 'function(data) {
                                    $("#Profile_state").empty();
                                    $("#Profile_state").append(data);
                                    $("#Profile_state").trigger("liszt:updated");

                                            } ',

    )));

Then in your controller you can use POST Example:

    public function actionState()
{

 $data=Regions::model()->findAll('country_code=:country_code', 
                  array(':country_code'=> $_POST['country']));                
 echo "<option value=''>Select state</option>";
    $data=CHtml::listData($data,'region_code','region_title');
            foreach($data as $value=>$state)  {
                        echo CHtml::tag
                                ('option', array('value'=>$value),CHtml::encode($state),true);
                    }   

}

Upvotes: 2

darkheir
darkheir

Reputation: 8950

The $_POST var is corresponding to some data sent using HTTP protocol, so to use this var the client (the browser) need to send data to the server.

Since you want to display something just after the user selected a value in the dropdown list, you'll need to use javascript which is executed on the client side.

Here's an example that will get the selected value using jquery. You should then update the div where you want the value to appear, but since it's not in your question I can't help!

$('#dropDownId').change(function(){ 
    var value = $('#dropDownId :selected').text();
    //Here update the div where you need to see the selected value
});

Where dropDownId is the id that you need to give to your dropDownList (in the CHtml::dropDownList html options)

Upvotes: 3

Related Questions