• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
The Electric Toolbox Blog

The Electric Toolbox Blog

Linux, Apache, Nginx, MySQL, Javascript and PHP articles

  • Applications
  • FCKEditor
  • Apache
  • Windows
  • Contact Us
Home / Populate defaults dynamically with SilverStripe

Populate defaults dynamically with 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');
  }

}

Check Out These Related posts:

  1. Get public properties that aren’t static with PHP Reflection
  2. Process Forking with PHP
  3. RFC 1321 – MD5 Message-Digest Algorithm
  4. Get unique array values with PHP

Filed Under: SilverStripe

Primary Sidebar

Categories

  • Apache
  • Applications
  • Article
  • Case Studies
  • Email Servers
  • FCKEditor
  • HTML And CSS
  • Javascript
  • Linux/Unix/BSD
  • Microsoft SQL Server
  • Miscellaneous Postings
  • MySql
  • Networking
  • Nginx Web Server
  • Offsite Articles
  • OSX
  • PHP
  • Quick Tips
  • RFC – Request for Comments
  • SilverStripe
  • VMWare
  • VPN
  • Windows
  • WordPress

Recent Posts

  • Vim Show Line Numbers
  • Add User To Group Linux
  • Chmod 777 Tutorial
  • How to Copy Directory Linux
  • Linux create user

Copyright © 2021. ElectricToolBox. All Rights Reserved.

  • Contact Us
  • Copyright Info
  • Privacy Policy
  • Sitemap