Created
May 17, 2019 15:39
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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