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.

Form Questions /

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

Setting the default value for OptionsetField derived from a list of DataObjects


Go to End


3 Posts   883 Views

Avatar
benald

Community Member, 10 Posts

6 January 2017 at 6:59pm

Edited: 07/01/2017 5:47pm

Hey all,

I have a front end form which requires the selection of a lottery feed using OptionsetField. I need to check the first item by default but I can't get it to work.
Before i go completely bonkers, Is there anyone out there able to set me right please?

Initially this was my field code .

 OptionsetField::create('LotteryFeedID', 'LotteryFeed')
	->setSource(LotteryFeed::get()->map('ID','Title'))

I attempted defining the source as a variable ($map) outside the FieldList and then calling it as follows; using the api example for OptionsetField:

        $map = LotteryFeed::get()->map('ID','Title');
        $fields = new FieldList(
            OptionsetField::create('LotteryFeedID', 'LotteryFeed', $map, $map[0])
        );

No error on build this time, but it fails to actually check the first item in the list on the template.

I then attempted to set the default value in the class itself

        private static $defaults = array (
            'LotteryFeed' => '[0]' // not sure of the syntax here
        );

Banging my head against the wall isn't helping, it's no doubt super easy but I cannot find reference to the correct answer.

Thanks in advance

Ben

Avatar
Kirk

Community Member, 67 Posts

10 January 2017 at 11:29am

The reason it is not working is because the source you are using from LotteryFeed is going to be an array with the ID of the dataobject as the element key.
So try something like this

        $map = LotteryFeed::get()->map('ID','Title');
        $fields = new FieldList(
            OptionsetField::create('LotteryFeedID', 'LotteryFeed', $map, LotteryFeed::get()->first()->ID)
        );

Avatar
benald

Community Member, 10 Posts

11 January 2017 at 6:26pm

Thank you Kirk, exactly what I was after :)