Version 4 supported
This version of Silverstripe CMS is still supported though will not receive any additional features. Go to documentation for the most recent stable version.

Data types and casting

Each model in a Silverstripe CMS DataObject will handle data at some point. This includes database columns such as the ones defined in a $db array or simply a method that returns data for the template.

A Data Type is represented in Silverstripe CMS by a DBField subclass. The class is responsible for telling the ORM about how to store its data in the database and how to format the information coming out of the database, i.e. on a template.

In the Player example, we have four database columns each with a different data type (Int, Varchar).

// app/src/Player.php
namespace App\Model;

use SilverStripe\ORM\DataObject;

class Player extends DataObject
{
    private static $db = [
        'PlayerNumber' => 'Int',
        'FirstName' => 'Varchar(255)',
        'LastName' => 'Text',
        'Birthday' => 'Date',
    ];
}

Available types

  • 'Boolean': A boolean field (see: DBBoolean).
  • 'Currency': A number with 2 decimal points of precision, designed to store currency values (see: DBCurrency).
  • 'Date': A date field (see: DBDate).
  • 'Decimal': A decimal number (see: DBDecimal).
  • 'Enum': An enumeration of a set of strings (see: DBEnum).
  • 'HTMLText': A variable-length string of up to 2MB, designed to store HTML (see: DBHTMLText).
  • 'HTMLVarchar': A variable-length string of up to 255 characters, designed to store HTML (see: DBHTMLVarchar).
  • 'Int': An integer field (see: DBInt).
  • 'Percentage': A decimal number between 0 and 1 that represents a percentage (see: DBPercentage).
  • 'Datetime': A date / time field (see: DBDatetime).
  • 'Text': A variable-length string of up to 2MB, designed to store raw text (see: DBText).
  • 'Time': A time field (see: DBTime).
  • 'Varchar': A variable-length string of up to 255 characters, designed to store raw text (see: DBVarchar).

See the API documentation for a full list of available Data Types. You can define your own DBField instances if required as well.

Default values

Default values for new objects

For complex default values for newly instantiated objects see Dynamic Default Values. For simple values you can make use of the $defaults array. For example:

namespace App\Model;

use SilverStripe\ORM\DataObject;

class Car extends DataObject
{
    private static $db = [
        'Wheels' => 'Int',
        'Condition' => 'Enum(["New","Fair","Junk"])',
    ];

    private static $defaults = [
        'Wheels' => 4,
        'Condition' => 'New',
    ];
}

Default values for new database columns

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 by passing an argument for the default value in your $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:

namespace App\Model;

use SilverStripe\ORM\DataObject;

class Car extends DataObject
{
    private static $db = [
        'Wheels' => 'Int(4)',
        'Condition' => 'Enum(["New","Fair","Junk"], "New")',
        'Make' => 'Varchar(["default" => "Honda"])',
    ];
}

Formatting output

The Data Type does more than setup the correct database schema. They can also define methods and formatting helpers for output. You can manually create instances of a Data Type and pass it through to the template.

In this case, we'll create a new method for our Player that returns the full name. By wrapping this in a DBVarchar object we can control the formatting and it allows us to call methods defined from Varchar as LimitCharacters.

// app/src/Model/Player.php
namespace App\Model;

use SilverStripe\ORM\DataObject;
use SilverStripe\ORM\FieldType\DBField;

class Player extends DataObject
{
    public function getName()
    {
        return DBField::create_field('Varchar', $this->FirstName . ' ' . $this->LastName);
    }
}

Then we can refer to a new Name column on our Player instances. In templates we don't need to use the get prefix.

use App\Model\Player;

$player = Player::get()->byId(1);

echo $player->Name;
// returns "Sam Minnée"

echo $player->getName();
// returns "Sam Minnée";

echo $player->getName()->LimitCharacters(2);
// returns "Sa…"

Casting

Rather than manually returning objects from your custom functions. You can use the $casting property.

namespace App\Model;

use SilverStripe\ORM\DataObject;

class Player extends DataObject
{
    private static $casting = [
        'Name' => 'Varchar',
    ];

    public function getName()
    {
        return $this->FirstName . ' ' . $this->LastName;
    }
}

The properties on any Silverstripe CMS object can be type casted automatically, by transforming its scalar value into an instance of the DBField class, providing additional helpers. For example, a string can be cast as a DBText type, which has a FirstSentence() method to retrieve the first sentence in a longer piece of text.

On the most basic level, the class can be used as simple conversion class from one value to another, e.g. to round a number.

use SilverStripe\ORM\FieldType\DBField;
// results in 1.23
DBField::create_field('Double', 1.23456)->Round(2);

Of course that's much more verbose than the equivalent PHP call. The power of DBField comes with its more sophisticated helpers, like showing the time difference to the current date:

use SilverStripe\ORM\FieldType\DBField;
// shows "30 years ago"
DBField::create_field('Date', '1982-01-01')->TimeDiff();

Casting ViewableData

Most objects in Silverstripe CMS extend from ViewableData, which means they know how to present themselves in a view context. Through a $casting array, arbitrary properties and getters can be casted:

namespace App\Model;

use SilverStripe\View\ViewableData;

class MyObject extends ViewableData
{
    private static $casting = [
        'MyDate' => 'Date',
    ];

    public function getMyDate()
    {
        return '1982-01-01';
    }
}
use App\Model\MyObject;

$obj = MyObject::create();
// returns string
$obj->getMyDate();
// returns string
$obj->MyDate;
// returns object
$obj->obj('MyDate');
// returns boolean
$obj->obj('MyDate')->InPast();

Casting HTML text

The database field types DBHTMLVarchar/DBHTMLText and DBVarchar/DBText are exactly the same in the database. However, the template engine knows to escape fields without the HTML prefix automatically in templates, to prevent them from rendering HTML interpreted by browsers. This escaping prevents attacks like CSRF or XSS (see "security"), which is important if these fields store user-provided data.

See the Template casting section for controlling casting in your templates.

Overloading

"Getters" and "Setters" are functions that help save fields to our DataObject instances. By default, the methods getField() and setField() are used to set column data. They save to the protected array, $obj->record. We can overload the default behavior by making a function called "get<fieldname>" or "set<fieldname>".

The following example will use the result of getStatus instead of the 'Status' database column. We can refer to the database column using getField().

namespace App\Model;

use SilverStripe\ORM\DataObject;

/**
 * @property Float $Cost
 */
class Product extends DataObject
{
    private static $db = [
        'Title' => 'Varchar(255)',
        //cost in pennies/cents
        'Cost' => 'Int',
    ];

    public function getCost()
    {
        return $this->getField('Cost') / 100;
    }

    public function setCost($value)
    {
        return $this->setField('Cost', $value * 100);
    }
}

API documentation