带有dyanmic optgroup的下拉列表

leo*_*leo 3 cakephp

你好,蛋糕专家!我正在寻找有关dyanamic optgroup的dyanmic下拉列表的帮助.假设我有两个表:

 countries:  id, country_name,

 counties:  id, county_name, country_id
Run Code Online (Sandbox Code Playgroud)

现在,我想显示一个下拉列表,其中包含填充了分组的frm国家/地区表和列出的县列表项.

country_name1

        county_name1

        county_name2

country_name2

        county_name3

        county_name4

country_name3

         county_name4

        county_name5

.......
Run Code Online (Sandbox Code Playgroud)

在此先感谢,并感谢任何帮助!

nei*_*kes 20

如果选项正确,Cake的FormHelper :: input方法将呈现带有optgroups的select标签,例如

echo  $form->input('county');
Run Code Online (Sandbox Code Playgroud)

如果视图中有一个名为$ counties的变量,它包含以下格式的数据:

$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',
  ),
);
Run Code Online (Sandbox Code Playgroud)

因此,在您的控制器中,执行以下操作:

$this->set('counties', ClassRegistry::init('Country')->getCountiesByCountry());
Run Code Online (Sandbox Code Playgroud)

在您的国家/地区模型中,执行以下操作:

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;
}
Run Code Online (Sandbox Code Playgroud)