CakePHP re-populate list box

后端 未结 1 1683
借酒劲吻你
借酒劲吻你 2021-01-27 19:27

I have a question about cakePHP. I create two drop down lists in my view. When the user changes the value in one list, I want the second to change. Currently, I have this wor

相关标签:
1条回答
  • 2021-01-27 19:42
    • 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           
            }
        }
    ?>
    
    0 讨论(0)
提交回复
热议问题