如何向 Silverstripe DropDownField 添加空白值并要求选​​择非空白值?

How can I add a blank value to a Silverstripe DropDownField and require a non-blank value to be selected?

如何向 Silverstripe DropDownField 添加空白值并要求选​​择非空白值?

目前我的领域是:

$myField = new DropdownField(
  'MyField',
  "So what'll it be, yes or no?",
  array( "N"=>"No", "Y"=>"Yes")
);

我正在使用 SilverStripe 3.1

您要设置

$myField->setHasEmptyDefault(true);

然后在你的控制器中使用Form validation

类似于:

public function myForm() {
    $myField = new DropdownField(
        'MyField',
        "So what'll it be, yes or no?",
        array( "N"=>"No", "Y"=>"Yes")
    );
    $fields = new FieldList($myField);
    $validator = new RequiredFields('MyField');

    return new Form($this, 'myFormForm', $fields, $actions, $validator);
}