Jump to:

5542 Posts in 1739 Topics by 1225 members

Customising the CMS

SilverStripe Forums » Customising the CMS » How to do multiple nested dropdown lists in Admin are??

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

Page: 1
Go to End
Author Topic: 629 Views
  • Nadz
    Avatar
    Community Member
    8 Posts

    How to do multiple nested dropdown lists in Admin are?? Link to this post

    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

  • Nadz
    Avatar
    Community Member
    8 Posts

    Re: How to do multiple nested dropdown lists in Admin are?? Link to this post

    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

    629 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.