How to build nested dropdown/checkbox

Hi all,

I need help with building nested dropdown/checkbox. This is my data structure:




  [3]=>

  array(2) {

    ["title"]=>

    string(36) "COMPUTER SCIENCE, TELECOMMUNICATIONS"

    ["subgroups"]=>

    array(2) {

      [301]=>

      array(1) {

        ["title"]=>

        string(29) "IT - Information Technologies"

      }

      [302]=>

      array(1) {

        ["title"]=>

        string(38) "Telecommunications and postal services"

      }

    }

  }

  [4]=>

  array(2) {

    ["title"]=>

    string(12) "CONSTRUCTION"

    ["subgroups"]=>

    array(10) {

      [401]=>

      array(1) {

        ["title"]=>

        string(13) "City planning"

      }

      [402]=>

      array(1) {

        ["title"]=>

        string(17) "Building material"

      }

      [403]=>

      array(1) {

        ["title"]=>

        string(17) "Civil engineering"

      }

    }

  }



I am expecting output like this:


COMPUTER SCIENCE, TELECOMMUNICATIONS

    - IT - Information Technologies

    - Telecommunications and postal services

CONSTRUCTION

    - City planning

    - Building material

    - and so on...

User can chose first level item ( for example "COMPUTER SCIENCE, TELECOMMUNICATIONS", or he can go deeper ). I am allowing only one item to be selected. I have tried outputting my array with checkBoxList + ArrayHelper::map(), but I only get errors. I am assuming that my data structure is not suitable.

Does anyone know how to create nested checkbox list, and can help me out here ? Do I need to change structure of my data, how it should look like ? I prefer not using external code. Thanks in advance.

You may try the following for testing purpose.




$items = [

    'COMPUTER SCIENCE, TELECOMMUNICATIONS' => [

        301 => 'IT - Information Technologies',

        302 => 'Telecommunications and postal services',

    ],

    'CONSTRUCTION' => [

        401 => 'City planning',

        402 => 'Building material',

        403 => 'Civil engineering',

    ],

];


$selection = 302;


echo Html::dropDownList('input_name', $selection, $items);




It should generate a dropDownList with the following items:




COMPUTER SCIENCE, TELECOMMUNICATIONS

    IT - Information Technologies

    Telecommunications and postal services

CONSTRUCTION

    City planning

    Building material

    Civil engineering



The first-level items are treated as the labels of the groups and are not selectable - only the 2nd-level items can be selected.

Please check the API for Html::dropDownList() here and read carefully the description of the 3rd parameter ‘$items’.

In order to use ArrayHelper::map() to construct this kind of nested item array, you have to pass the 4th parameter ‘$group’ appropriately. Check the API for ArrayHelper::map().