I want to have a GridField for creating a list of theme colors. I also want some colors to always be in that list (maybe not even being removable) e.g. black and white.
How can I add default Objects to a GridField in SilverStripe?
I want to have a GridField for creating a list of theme colors. I also want some colors to always be in that list (maybe not even being removable) e.g. black and white.
How can I add default Objects to a GridField in SilverStripe?
One way to do this would be by implementing requireDefaultRecords
in an Extension
which you apply to SiteConfig
- this would create the records when running dev/build
.
e.g.
use SilverStripe\Core\Extension;
class MySiteConfigExtension extends Extension
{
public function requireDefaultRecords()
{
// Implement creating the default SiteConfig so we can add records to its relations
$config = DataObject::get_one(SiteConfig::class);
if (!$config) {
self::make_site_config();
DB::alteration_message("Added default site config", "created");
}
// Add records
$list = $config->ThemeColors();
if ($list->count() === 0) {
$color = ThemeColor::create();
$color->write();
$list->add($color);
DB::alteration_message("Added default theme colours to site config", "created");
}
}
}
Be aware that the ThemeColor
database table may-or-may-not be ready.
You could also implement requireDefaultRecords()
on your ThemeColor
class but be aware that in that case SiteConfig
may-or-may-not be ready in the db.
Note: I've obviously made assumptions about your relation and class names. Substitute these as appropriate.