Merge pull request #6005 from open-sausages/pulls/4.0/defaut-string-value

API Enable default value to be specified for dbstring types at the db level
This commit is contained in:
Ingo Schommer 2016-09-22 16:09:19 +12:00 committed by GitHub
commit 301436f669
4 changed files with 45 additions and 3 deletions

View File

@ -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'

View File

@ -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;
}

View File

@ -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
<?php
@ -82,7 +88,8 @@ going forward. You do this be passing an argument for the default value in your
private static $db = array(
'Wheels' => 'Int(4)',
'Condition' => 'Enum(array("New","Fair","Junk"), "New")'
'Condition' => 'Enum(array("New","Fair","Junk"), "New")',
'Make' => 'Varchar(["default" => "Honda"]),
);
}

View File

@ -1,7 +1,7 @@
<?php
use SilverStripe\Core\Object;
use SilverStripe\ORM\FieldType\DBField;
use SilverStripe\ORM\FieldType\DBString;
use SilverStripe\Dev\SapphireTest;
@ -26,6 +26,18 @@ class DBStringTest extends SapphireTest {
);
}
public function testDefault() {
/** @var DBString $dbField */
$dbField = Object::create_from_string(
"StringFieldTest_MyStringField(['default' => 'Here is my default text'])",
'Myfield'
);
$this->assertEquals(
"Here is my default text",
$dbField->getDefaultValue()
);
}
/**
* @covers SilverStripe\Model\FieldType\DBString::LowerCase()
*/