Dropdown list with dyanmic optgroup

Hi cakephp experts! I am looking for help in the dyanmic dropdown with the dyanamic optgroup. Suppose I have two tables:

 countries:  id, country_name,

 counties:  id, county_name, country_id

Now I want to display a dropdown using optgroups populated by frm countries and a list of 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!

+3
source share
3 answers

Cake FormHelper :: the input method will display the select tag with optgroups if the parameters are correct, for example

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

if there is a variable available in a view called $ counties that 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;
}
+19

tableB A tableA, do

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

find("all")

$this->tableA->recursive->2

+1

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


$counties = Hash::combine($countries,'{n}.County.id','{n}.County.name','{n}.Country.name'); 

0
source

Source: https://habr.com/ru/post/1725159/


All Articles