Skip to content

Commit

Permalink
Docs: Update Dynamic_Default_Fields.md (silverstripe#8941)
Browse files Browse the repository at this point in the history
  • Loading branch information
adrhumphreys authored and chillu committed Apr 29, 2019
1 parent 5c4367f commit e648fd3
Showing 1 changed file with 44 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,27 @@
# Dynamic Default Values
# Default Values and Records

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, but in many situations default values need to be dynamically calculated. In order to do this, the
## 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.

A simple example is if you have a dog and by default it's bark is "Woof":
```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
[DataObject::populateDefaults()](api:SilverStripe\ORM\DataObject::populateDefaults()) method will need to be overloaded.

This method is called whenever a new record is instantiated, and you must be sure to call the method on the parent
Expand Down Expand Up @@ -38,3 +58,24 @@ public function populateDefaults()
parent::populateDefaults();
}
```

## 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'],
];
}
```

0 comments on commit e648fd3

Please sign in to comment.