Dropdown list with dyanmic optgroup

前端 未结 3 1035
抹茶落季
抹茶落季 2021-01-03 10:32

Hi there cakephp experts! I am looking for you help on a dyanmic dropdown list with dyanamic optgroup. Suppose I have two tables:

 countries:  id, country_na         


        
相关标签:
3条回答
  • 2021-01-03 11:00

    bind tableB to tableA in tableA model, do

    $hasMany = array("tableB"=>array("className"=>"tableB","foreignKey"=>"aId"));
    

    then use

    find("all")
    

    might need

    $this->tableA->recursive->2
    

    right before find

    0 讨论(0)
  • 2021-01-03 11:20

    You can also use the Hash::combine function instead of a nested loop as suggested by @neilcrookes

    
    $counties = Hash::combine($countries,'{n}.County.id','{n}.County.name','{n}.Country.name'); 
    
    
    0 讨论(0)
  • 2021-01-03 11:23

    Cake's FormHelper::input method will render a select tag with optgroups if the options are correct, e.g.

    echo  $form->input('county');
    

    provided there is a variable available in the view called $counties which contains data in the following format:

    $counties = array(
      'Country Name 1' => array(
        'county_1_id' => 'County 1 Name',
        'county_2_id' => 'County 2 Name',
        'county_3_id' => 'County 3 Name',
      ),
      'Country Name 2' => array(
        'county_4_id' => 'County 4 Name',
        'county_5_id' => 'County 5 Name',
        'county_6_id' => 'County 6 Name',
      ),
    );
    

    So, in your controller, do something like:

    $this->set('counties', ClassRegistry::init('Country')->getCountiesByCountry());
    

    and in your Country Model, do something like:

    function getCountiesByCountry() {
      $countries = $this->find('all', array('contain' => array('County')));
      $return = array();
      foreach ($countries as $country) {
        foreach ($country['County'] as $county) {
          $return[$country['Country']['name']][$county['id']] = $county['name'];
        }
      }
      return $return;
    }
    
    0 讨论(0)
提交回复
热议问题