mirror of
https://github.com/silverstripe/silverstripe-framework
synced 2024-09-01 15:28:02 +02:00
git-svn-id: svn://svn.silverstripe.com/silverstripe/open/modules/sapphire/trunk@39001 467b73ca-7a2a-4603-9d3b-597d59a354a9
65 lines
1.9 KiB
PHP
Executable File
65 lines
1.9 KiB
PHP
Executable File
<?php
|
|
|
|
class Enum extends DBField {
|
|
|
|
protected $enum, $default;
|
|
|
|
/**
|
|
* Create a new Enum field.
|
|
* You should create an enum field like this:
|
|
* "MyField" => "Enum('Val1, Val2, Val3', 'Val1')"
|
|
* or: "MyField" => "Enum(Array('Val1', 'Val2', 'Val3'), 'Val1')"
|
|
* but NOT: "MyField" => "Enum('Val1', 'Val2', 'Val3', 'Val1')"
|
|
* @param enum: A string containing a comma separated list of options or an array of Vals.
|
|
* @param default The default option, which is either NULL or one of the items in the enumeration.
|
|
*/
|
|
function __construct($name, $enum = NULL, $default = NULL) {
|
|
if($enum) {
|
|
if(!is_array($enum)){
|
|
$enum = split(" *, *", trim($enum));
|
|
}
|
|
|
|
$this->enum = $enum;
|
|
|
|
// If there's a default, then
|
|
if($default) {
|
|
if(in_array($default, $enum)) {
|
|
$this->default = $default;
|
|
} else {
|
|
user_error("Enum::__construct() The default value does not match any item in the enumeration", E_USER_ERROR);
|
|
}
|
|
|
|
// By default, set the default value to the first item
|
|
} else {
|
|
$this->default = reset($enum);
|
|
}
|
|
}
|
|
parent::__construct($name);
|
|
}
|
|
|
|
function requireField(){
|
|
DB::requireField($this->tableName, $this->name, "enum('" . implode("','", $this->enum) . "') character set utf8 collate utf8_general_ci default '{$this->default}'");
|
|
}
|
|
|
|
|
|
/**
|
|
* Return a dropdown field suitable for editing this field
|
|
*/
|
|
function formField($title = null, $name = null, $hasEmpty = false, $value = "", $form = null) {
|
|
if(!$title) $title = $this->name;
|
|
if(!$name) $name = $this->name;
|
|
|
|
$field = new DropdownField($name, $title, $this->enumValues($hasEmpty), $value, $form);
|
|
|
|
return $field;
|
|
}
|
|
|
|
/**
|
|
* Return the values of this enum, suitable for insertion into a dropdown field.
|
|
*/
|
|
function enumValues($hasEmpty = false) {
|
|
return ($hasEmpty) ? array_merge(array('' => ''), ArrayLib::valuekey($this->enum)) : ArrayLib::valuekey($this->enum);
|
|
}
|
|
}
|
|
|
|
?>
|