Ivan Ivan - 5 months ago 42
PHP Question

Silverstripe selected in DropdownField

How can I set a default selected value in

Silverstripe
using
DropdownField
. I have list of categories and I want to set a default selected item, but I don't know how to do it. Looking on SS API for DropdownField, there does not exist method for
selected
.

Here is my code:

DropdownField::create('CategoryID', 'Categories')->setSource(Category::get()->map('ID', 'Name'))->setEmptyString('Chose category'),

Answer

Use ->setValue with your value (e.g. $iSelectedCategoryID) like this...

DropdownField::create('CategoryID', 'Categories')
    ->setSource(Category::get()->map('ID', 'Name'))
    ->setEmptyString('Chose category')
    ->setValue($iSelectedCategoryID)
Comments