Populate defaults dynamically with SilverStripe

Posted in SilverStripe -

SilverStripe allows default values to be set for fields on data objects using the static $defaults property but this cannot be populated with dynamic values, such as using date() or rand(). Instead use the populateDefaults() function.

Setting defalts with static $defaults

The first example shows setting a field value with a default using the static $defaults property. The value set in static $defaults cannot be set by calling a function.

class Page extends SiteTree {

  public static $fields = array(
    'MyBooleanField' => 'Boolean',
    'MyDateField' => 'SS_DateTime'
  );

  public static $defaults = array(
    'MyBooleanField' => 1
  );

}

Trying to set the date in the following way, by calling a function, results in a PHP error:

  public static $defaults = array(
    'MyBooleanField' => 1,
    'MyDateField' => date('Y-m-d H:i:s');
  );

But the property can be set in the populateDefaults function instead like so:

  public function populateDefaults() {
    parent::populateDefaults();
    $this->MyDateField = date('Y-m-d H:i:s');
  }

This will set the MyDateField value to the current date and time whenever a new record is created.

Putting all the above code together looks like this:

class Page extends SiteTree {

  public static $fields = array(
    'MyBooleanField' => 'Boolean',
    'MyDateField' => 'SS_DateTime'
  );

  public static $defaults = array(
    'MyBooleanField' => 1
  );

  public function populateDefaults() {
    parent::populateDefaults();
    $this->MyDateField = date('Y-m-d H:i:s');
  }

}


Related posts:


Comments