0

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?

  • It depends, to some extent, where your `GridField` is, and how the data is related. i.e. is this on a `ModelAdmin`? Or is this a `has_many` relation being displayed on a `GridField` of some parent `DataObject`? Please provide more information about your specific scenario. – Guy Sartorelli Oct 05 '22 at 02:51
  • @GuySartorelli it is a `has_many` realtion. I have a new tab in the SiteConfig to add new ThemeColor objects that extend DataObject. – TimSchulzRC Oct 28 '22 at 10:56

1 Answers1

0

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.

Guy Sartorelli
  • 313
  • 1
  • 8