本文介绍了带有动态 optgroup 的下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,cakephp 专家!我正在寻找有关 dyanamic optgroup 的动态下拉列表的帮助.假设我有两个表:

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_name,

 counties:  id, county_name, country_id

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

Now, I want to display a dropdown list with optgroups populated frm countries table and list items populated from counties.

country_name1

        county_name1

        county_name2

country_name2

        county_name3

        county_name4

country_name3

         county_name4

        county_name5

.......

提前致谢并感谢您的帮助!

Thanks in advance and appreciate any help!!

推荐答案

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

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

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

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

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;
}

这篇关于带有动态 optgroup 的下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 14:32