Grouping results in Select2
Asked Answered
U

2

17

Is it possible somehow to group results in a Select2 component when it's not using <select> tag, but <input type="hidden">, and results are provided as "data" option in configuration object?

var select2Options = {
  data: {
    results: myArrayOfResults
  }
};
Unclassical answered 12/7, 2013 at 9:0 Comment(0)
U
36

Yes, the results objects support a children attribute...

so for example:

var select2Options = {
  data: {
    results: [
      {text: "My shiny group", children: [
          {id: 1, text: "My shiny item"}, 
          {id: 2, text: "My shiny item2"}
      ]}
    ]
  }
};
Unclassical answered 12/7, 2013 at 17:52 Comment(5)
Well it's quite long time I used it lastly... I don't know if is it working with the current version of Select2.Unclassical
worked for me now, but title must be changed by text. thanks anyway, after few hours rounding around, I get this stuff working. I'm sure your post here helped me yet!Circumambulate
to keep it up-to-date, maybe you can edit the answer just adding the possibility of text instead TITLE :)Circumambulate
I see, you are right, I've simplified it, thank you.Unclassical
FYI: Children can be stacked so you can build a tree-like hierarchy.Fluvial
S
0

For ajax data loading with group and data work for me using,

$arrFinal = array(array("name"=>"My shiny group 1",
"children"=>array(array("id"=>1,"name"=>"My shiny item 11"),array("id"=>2,"name"=>"My shiny item 12"))
),array("name"=>"My shiny group 2",
"children"=>array(array("id"=>1,"name"=>"My shiny item 21"),array("id"=>2,"name"=>"My shiny item 22"))
)
);
die(json_encode(array("result" => $arrFinal)));

if formatResult: ratioFormatResult then,
function ratioFormatResult(row) {
// Here, you will get both group ("My shiny group 1") as well as data("My shiny item11") as row .
}

To make group selectable use id field along with name in group.

Ser answered 26/7, 2013 at 9:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.