CakePHP re-populate list box

江枫思渺然 提交于 2019-12-02 13:33:06
manzapanza
  • The js event is change fired on the select tag and NOT click
  • You can use the Form Helper to build your form.
  • Pay attention Naming things following the cakephp way.

Because your code is a bit confused i will make other simple example:

Country hasMany City
User belongsTo Country
User belongsTo City

ModelName/TableName (fields)
Country/countries (id, name, ....) 
City/cities (id, country_id, name, ....)
User/users (id, country_id, city_id, name, ....)

View/Users/add.ctp

<?php
    echo $this->Form->create('User');
    echo $this->Form->input('country_id');
    echo $this->Form->input('city_id');
    echo $this->Form->input('name');
    echo $this->Form->end('Submit');

    $this->Js->get('#UserCountryId')->event('change',
        $this->Js->request(
            array('controller' => 'countries', 'action' => 'get_cities'),
                array(
                    'update' => '#UserCityId',
                    'async' => true,
                    'type' => 'json',
                    'dataExpression' => true,
                    'evalScripts' => true,
                    'data' => $this->Js->serializeForm(array('isForm' => false, 'inline' => true)),
            )
        )
    );
    echo $this->Js->writeBuffer();

?>

UsersController.php / add:

public function add(){
    ...
    ...
    // populate selects with options
    $this->set('countries', $this->User->Country->find('list'));
    $this->set('cities', $this->User->City->find('list'));
}

CountriesController.php / get_cities:

public function get_cities(){
    Configure::write('debug', 0);
    $cities = array();
    if(isset($this->request->query['data']['User']['country_id'])){
        $cities = $this->Country->City->find('list', array(
                  'conditions' => array('City.country_id' => $this->request->query['data']['User']['country_id'])
        ));
    }
    $this->set('cities', $cities);
}

View/Cities/get_cities.ctp :

<?php 
    if(!empty($cities)){
        foreach ($cities as $id => $name) {
?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php           
        }
    }
?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!