diff --git a/ORM/FieldType/DBField.php b/ORM/FieldType/DBField.php index bdcce554e..4a2dc62bc 100644 --- a/ORM/FieldType/DBField.php +++ b/ORM/FieldType/DBField.php @@ -195,6 +195,26 @@ abstract class DBField extends ViewableData { $this->value = $value; } + /** + * Get default value assigned at the DB level + * + * @return mixed + */ + public function getDefaultValue() { + return $this->defaultVal; + } + + /** + * Set default value to use at the DB level + * + * @param mixed $defaultValue + * @return $this + */ + public function setDefaultValue($defaultValue) { + $this->defaultVal = $defaultValue; + return $this; + } + /** * Determines if the field has a value which is not considered to be 'null' diff --git a/ORM/FieldType/DBString.php b/ORM/FieldType/DBString.php index 58258d297..5222950b2 100644 --- a/ORM/FieldType/DBString.php +++ b/ORM/FieldType/DBString.php @@ -58,6 +58,9 @@ abstract class DBString extends DBField { if(array_key_exists("nullifyEmpty", $options)) { $this->nullifyEmpty = $options["nullifyEmpty"] ? true : false; } + if(array_key_exists("default", $options)) { + $this->setDefaultValue($options["default"]); + } return $this; } diff --git a/docs/en/02_Developer_Guides/00_Model/04_Data_Types_and_Casting.md b/docs/en/02_Developer_Guides/00_Model/04_Data_Types_and_Casting.md index 9896a5f83..f1bfc7359 100644 --- a/docs/en/02_Developer_Guides/00_Model/04_Data_Types_and_Casting.md +++ b/docs/en/02_Developer_Guides/00_Model/04_Data_Types_and_Casting.md @@ -73,7 +73,13 @@ When adding a new `$db` field to a DataObject you can specify a default value to be applied to all existing records when the column is added in the database for the first time. This will also be applied to any newly created objects going forward. You do this be passing an argument for the default value in your -`$db` items. For example: +`$db` items. + +For integer values, the default is the first parameter in the field specification. +For string values, you will need to declare this default using the options array. +For enum values, it's the second parameter. + +For example: :::php 'Int(4)', - 'Condition' => 'Enum(array("New","Fair","Junk"), "New")' + 'Condition' => 'Enum(array("New","Fair","Junk"), "New")', + 'Make' => 'Varchar(["default" => "Honda"]), ); } diff --git a/tests/model/DBStringTest.php b/tests/model/DBStringTest.php index 7d798e6fb..b204c627f 100644 --- a/tests/model/DBStringTest.php +++ b/tests/model/DBStringTest.php @@ -1,7 +1,7 @@ 'Here is my default text'])", + 'Myfield' + ); + $this->assertEquals( + "Here is my default text", + $dbField->getDefaultValue() + ); + } + /** * @covers SilverStripe\Model\FieldType\DBString::LowerCase() */