Wednesday 28 August 2013

Dynamic state city dropdown selection in Yii Framework

Here is the tutorial to select city from state id dynamically by using ajax in Yii Framework in 3 easy steps

1) Fetch all state name and state id from "State" table and show it in dropdown field

<?php 
$stateList = CHtml::listData(State::model()->findAll(array('order' => 'name')), 'state_id', 'name');
        echo $form->dropDownList($model, 'state_id', $stateList, array(
            'ajax' => array(
                'type' => 'POST', //request type
                'url' => CController::createUrl('ajax/getCities'), //url to call.                
                'update' => '#Address_city_id', //selector to update   
                'data' => array('state_id' => 'js:this.value'),
        )));
?>

Here I have added the 'ajax' array in dropdownlist field where:

- type is type of request i.e. POST/GET

- url is controller and action url to call (Here I have called the AjaxController's getCities() method)

- update is the selector to update i.e. city dropdownlist id

- data is state_id to send request to particular controller/action

This will generate the following HTML output:

<select id="Address_state_id" name="Address[state_id]">
<option value="1">Andaman & Nicobar</option>
<option value="2">Andhra Pradesh</option>
<option value="3">Arunachal Pradesh</option>
.
.
</select>

Here "value" field contains the state id and option name as state names

2) Create city dropdown field

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

This will generate the following HTML output:

<select id="Address_city_id" name="Address[city_id]">
<option value="1">Kolhapur</option>
<option value="2">Ahmednagar</option>
.
.
</select>

3) In controller i.e AjaxController -> actionGetCities() method

<?php
class AjaxController extends Controller {

    public function actionGetCities() {        
    //Fetch all city name and id from state_id
        $data = City::model()->findAll('state_id=:id', array(':id' => (int) $_POST['state_id']));        
    //Passing city id and city name to list data which generates the data suitable for list-based HTML elements
        $data = CHtml::listData($data, 'city_id', 'name');
    //CHtml::tag which generates an HTML element
        foreach ($data as $value => $name) {            
            echo CHtml::tag('option', array('value' => $value), CHtml::encode($name), true);
        }
    }
}
?>

Thats it! Hope this will help you.

1 comment:

  1. The King Casino
    The king casino in Oklahoma offers a communitykhabar wide variety deccasino of games. The worrione casino offers several slots, poker, poormansguidetocasinogambling.com blackjack, and 출장샵 live games to choose from. We will also

    ReplyDelete