Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlewis-everley/689f20619bbc6e6b846ad552fa793b74 to your computer and use it in GitHub Desktop.
Save mlewis-everley/689f20619bbc6e6b846ad552fa793b74 to your computer and use it in GitHub Desktop.
Custom dropdown field that pretends to submit an array (but only allows selection of one item)
<?php
namespace App\Forms;
use SilverStripe\Forms\DropdownField;
class SingleSelectListBoxDropdownField extends DropdownField
{
/**
* Force this field to appear as if it saves an array
*
* @return array
*/
public function getAttributes()
{
return array_merge(
parent::getAttributes(),
array(
'size' => 1,
'name' => $this->getName() . '[]'
)
);
}
/**
* Validate this field
*
* @param Validator $validator
* @return bool
*/
public function validate($validator)
{
// Check if valid value is given
$selected = $this->Value()[0];
if (strlen($selected)) {
// Use selection rules to check which are valid
foreach ($this->getValidValues() as $formValue) {
if ($this->isSelectedValue($formValue, $selected)) {
return true;
}
}
} else {
if ($this->getHasEmptyDefault()) {
// Check empty value
return true;
}
$selected = '(none)';
}
// Fail
$validator->validationError(
$this->name,
_t(
'SilverStripe\\Forms\\DropdownField.SOURCE_VALIDATION',
"Please select a value within the list provided. {value} is not a valid option",
array('value' => $selected)
),
"validation"
);
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment