Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Customising the CMS /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

How to do multiple nested dropdown lists in Admin are??


Go to End


2 Posts   1563 Views

Avatar
Nadz

Community Member, 8 Posts

5 April 2012 at 3:38pm

Hello, For example i have a 'country' and 'city' table in db. CountryID is referenced in city table.
How can i generate a dropdown list so that i have something like this:

Australia
- Sydney
- Melbourne
New Zealand
- Auckland
- Wellington

My code is something as below

City.php Model

function getActiveCities(){
$countries = Dataobject::get('Country', 'Active=1');
$allcities = new DataObjectSet();
foreach($countries as $country){
$cities = DataObject::get('DealCity', 'Active=1 AND CountryID='.$country->ID)->map('ID', 'Title');
$allcities->push($cities);
}
return $allcities;
}

Page Controller in CMS
...
$cities = City::getActiveCities();
$fields->addFieldToTab('Root.Content.Main', new DropdownField('City','Select city', $cities));
....

This does give the output of cities in the dropdown but not the expected output that i desire as above!

Can someone please eleborate on this or is there a better way of doing nested dropdowns in SS??

cheers
Nadz

Avatar
Nadz

Community Member, 8 Posts

5 April 2012 at 4:26pm

Dang, I managed to find the solution myself and it took me half an hour to figure out how to do this.

Here is the code below that shall do the magic.

function getActiveCities(){
$countries = Dataobject::get('Country', 'Active=1');
$cityarray = array();
foreach($countries as $country){
$cityarray[$country->Title] = array();
$cities = DataObject::get('City', 'Active=1 AND CountryID='.$country->ID);
foreach($cities as $city){
$cityarray[$country->Title][$city->ID]=$city->Title;
}
}
return $cityarray;
}

And the controller code:

$fields->addFieldToTab('Root.Content.Main', new GroupedDropdownField('City','Select city', City::getActiveCities()));

Hope this helps someone...

cheers
Nadz