Search code examples
arrayscheckboxmany-to-manysilverstripe

Silverstripe many-many relationship for CheckboxSetField


I have a CheckboxSetField with numbers 1 - 10. I also have a many-many relationship set up that gets updated with the numbers.

While I can select numbers no problem, I am having trouble calling those selected numbers again once it has been submitted.

CheckboxSetField::create("Numbers","Numbers")
            ->setSource(array("1" => "1",
                             "2" => "2",
                             "3" => "3",
                             "4" => "4",
                             "5" => "5",
                             "6" => "6",
                             "7" => "7",
                             "8" => "8",
                             "9" => "9",
                             "10" => "10",))
            ->setInline(true)
            ->addExtraClass("inline-checkbox")
            ->setDefaultItems($numberlist)

I set up a query that returns all the numbers to setDefaultItems. It returns the numbers as a string which I then convert to an array but the array returns

Array ( [0] => 1 ) Array ( [0] => 2 ) Array ( [0] => 3 )

If the array is:

(array("1" => "1", "2" => "2", "3" => "3"))

It seems to work.

Am I missing something?


Solution

  • Your $numberlist seems to only contain the numbers as values, but you need keys and values.

    You can achieve that using array_combine, example:

    ->setDefaultItems(array_combine($numberlist, $numberlist))
    

    Hint: to create numeric ranges, you can use the range function, so you could shorten your setSource code to:

    ->setSource(array_combine(range(1,10), range(1,10)))