Skip to content

Instantly share code, notes, and snippets.

@kinglozzer
Created January 10, 2020 10:31
Show Gist options
  • Save kinglozzer/9f9cbf6500bf12c41bcf2e1eaebfd497 to your computer and use it in GitHub Desktop.
Save kinglozzer/9f9cbf6500bf12c41bcf2e1eaebfd497 to your computer and use it in GitHub Desktop.
SilverStripe\Core\Injector\Injector:
NullableBoolean:
class: App\ORM\FieldType\DBNullableBoolean
<?php
namespace App\ORM\FieldType;
use SilverStripe\Forms\DropdownField;
use SilverStripe\Forms\OptionsetField;
use SilverStripe\ORM\DB;
use SilverStripe\ORM\FieldType\DBBoolean;
class DBNullableBoolean extends DBBoolean
{
public function __construct($name = null, $defaultVal = null)
{
parent::__construct($name);
$this->defaultVal = null;
if ($defaultVal !== null) {
$this->defaultVal = ($defaultVal) ? 1 : 0;
}
}
public function requireField()
{
$spec = 'tinyint(1) unsigned';
if (isset($this->defaultVal)) {
$spec .= ' default ' . DB::get_conn()->quoteString($this->defaultVal);
}
DB::require_field($this->tableName, $this->name, $spec);
}
public function Nice()
{
if ($this->value === null) {
return 'Not set';
}
return ($this->value)
? _t('SilverStripe\\ORM\\FieldType\\DBBoolean.YESANSWER', 'Yes')
: _t('SilverStripe\\ORM\\FieldType\\DBBoolean.NOANSWER', 'No');
}
public function NiceAsBoolean()
{
if ($this->value === null) {
return 'null';
}
return ($this->value) ? 'true' : 'false';
}
public function saveInto($dataObject)
{
$fieldName = $this->name;
if ($fieldName) {
if ($this->value === null) {
$dataObject->$fieldName = null;
} else {
$dataObject->$fieldName = ($this->value) ? 1 : 0;
}
} else {
$class = static::class;
user_error("DBField::saveInto() Called on a nameless '$class' object", E_USER_ERROR);
}
}
public function scaffoldFormField($title = null, $params = null)
{
return new OptionsetField($this->name, $title, [
1 => _t('SilverStripe\\ORM\\FieldType\\DBBoolean.YESANSWER', 'Yes'),
0 => _t('SilverStripe\\ORM\\FieldType\\DBBoolean.NOANSWER', 'No')
]);
}
public function scaffoldSearchField($title = null)
{
$anyText = _t('SilverStripe\\ORM\\FieldType\\DBBoolean.ANY', 'Any');
$source = [
1 => _t('SilverStripe\\ORM\\FieldType\\DBBoolean.YESANSWER', 'Yes'),
0 => _t('SilverStripe\\ORM\\FieldType\\DBBoolean.NOANSWER', 'No')
];
$field = new DropdownField($this->name, $title, $source);
$field->setEmptyString("($anyText)");
return $field;
}
public function nullValue()
{
return null;
}
public function writeToManipulation(&$manipulation)
{
$manipulation['fields'][$this->name] = $this->prepValueForDB($this->value);
}
public function prepValueForDB($value)
{
if (is_bool($value)) {
return $value ? 1 : 0;
} elseif (is_string($value)) {
switch (strtolower($value)) {
case 'false':
case 'f':
return 0;
case 'true':
case 't':
return 1;
case 'null':
return null;
}
}
if ($value === null) {
return null;
}
return $value ? 1 : 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment