2019-11-18 05:58:33 +01:00
---
title: Dynamic Default Fields
summary: Learn how to add default values to your models
---
2019-04-29 00:21:13 +02:00
# Default Values and Records
2011-02-07 07:48:44 +01:00
2019-04-29 00:21:13 +02:00
## Static Default Values
The [DataObject::$defaults ](api:SilverStripe\ORM\DataObject::$defaults ) array allows you to specify simple static values to be the default values when a record is created.
2021-05-14 15:29:11 +02:00
A simple example is if you have a dog and by default its bark is "Woof":
2019-04-29 00:21:13 +02:00
```php
use SilverStripe\ORM\DataObject;
class Dog extends DataObject
{
private static $db = [
'Bark' => 'Varchar(10)',
];
private static $defaults = [
'Bark' => 'Woof',
];
}
```
## Dynamic Default Values
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
2017-10-27 04:38:27 +02:00
/**
* Sets the Date field to the current date.
*/
public function populateDefaults()
{
$this->Date = date('Y-m-d');
parent::populateDefaults();
}
2017-08-03 00:46:55 +02:00
```
2017-10-27 04:38:27 +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
2017-10-27 04:38:27 +02:00
/**
* This method combines the Title of the parent object with the Title of this
* object in the FullTitle field.
*/
public function populateDefaults()
{
if($parent = $this->Parent()) {
$this->FullTitle = $parent->Title . ': ' . $this->Title;
} else {
$this->FullTitle = $this->Title;
2017-08-07 05:11:17 +02:00
}
2017-10-27 04:38:27 +02:00
parent::populateDefaults();
}
```
2019-04-29 00:21:13 +02:00
## Static Default Records
The [DataObject::$default_records ](api:SilverStripe\ORM\DataObject::$default_records ) array allows you to specify default records created on dev/build.
A simple example of this is having a region model and wanting a list of regions created when the site is built:
```php
use SilverStripe\ORM\DataObject;
class Region extends DataObject
{
private static $db = [
'Title' => 'Varchar(45)',
];
private static $default_records = [
['Title' => 'Auckland'],
['Title' => 'Coromandel'],
['Title' => 'Waikato'],
];
}
```