2011-02-07 07:48:44 +01:00
# Dynamic Default Values
2017-07-03 03:22:12 +02:00
The [DataObject::$defaults ](api:SilverStripe\ORM\DataObject::$defaults ) array allows you to specify simple static values to be the default values when a
2015-03-11 04:27:56 +01:00
record is created, but in many situations default values need to be dynamically calculated. In order to do this, the
2017-07-03 03:22:12 +02:00
[DataObject::populateDefaults() ](api:SilverStripe\ORM\DataObject::populateDefaults( )) method will need to be overloaded.
2011-02-07 07:48:44 +01:00
This method is called whenever a new record is instantiated, and you must be sure to call the method on the parent
object!
A simple example is to set a field to the current date and time:
2017-08-03 00:46:55 +02:00
```php
2011-02-07 07:48:44 +01:00
/**
* Sets the Date field to the current date.
*/
2017-08-03 00:46:55 +02:00
public function populateDefaults()
{
2011-02-07 07:48:44 +01:00
$this->Date = date('Y-m-d');
parent::populateDefaults();
}
2017-08-03 00:46:55 +02:00
```
2011-02-07 07:48:44 +01:00
It's also possible to get the data from any other source, or another object, just by using the usual data retrieval
methods. For example:
2017-08-03 00:46:55 +02:00
```php
2011-02-07 07:48:44 +01:00
/**
* This method combines the Title of the parent object with the Title of this
* object in the FullTitle field.
*/
2017-08-03 00:46:55 +02:00
public function populateDefaults()
{
2011-02-07 07:48:44 +01:00
if($parent = $this->Parent()) {
$this->FullTitle = $parent->Title . ': ' . $this->Title;
} else {
$this->FullTitle = $this->Title;
}
parent::populateDefaults();
2015-03-11 04:27:56 +01:00
}
2017-08-03 00:46:55 +02:00
```