Repeatable CMS field templates

Silverstripe Version: 4.1

Question:
Does this feature exist in SS4?

In another CMS I could define a set of fields that created a group of fields. When viewed in the CMS that group could be repeated as different copies, each copy could be reordered/added/edited/deleted and was saved as a JSON object in the schema for the page.

The use case is for a set of repeatable blocks on the front end of the site. Like a 2 x 3 grid of image, title, text. Has no use outside the template it’s used on.

From what I can find SS4 can’t do this and I have to use an external data object and link it with has_many on the pages model. Is that correct? I realise I could put each of the six in their own tab or in one tab and manually repeat the fields like Title_1, Image_1, Title_2, Image_2 but… ugh what a PITA.

Yeah a DataObject model is the way to go for this, and you manage the has_many relationship with a gridfield, which provides the editing functionality you’re describing. Should be much more reliable than storing JSON objects as text.

Okay, thought as much. Thanks I’ll look into that, does seem like a lot of overhead for something simple.

Not sure I follow that bit - it is just text at the end of the day. It’s been reliable for the 7-8 years.

If you use DataObjects to define your schema you have the ORM layer enforcing your model and types, so there’s less potential for bad values to be introduced. It also means you can change your model over time easily and you have all the advantages that DataObjects bring, like templating, automatic escaping, accessor methods etc. - so it’s a lot more powerful and I would say safer. In your example, storing the relation to the image in a DataObject vs a JSON object means you can easily manipulate the image to produce a thumbnail etc.

But yeah, there are several ways to skin a cat. In SilverStripe the easiest solution will probably be to use DataObjects.

Thanks @JonoM - I got this done yesterday. Your point of image manipulation is a good one.

It works well, maybe a bit clunky to add/edit with page hopping but it is what it is…

Is there a way of limiting how many records can be created?

Yeah you could use Model Permissions. For example, if you used the code below, once you have created 5 items of that type you will no longer see an ‘Add New’ button on your gridfield.

public function canCreate($member = null, $context = array())
{
    if (self::get()->count() >= 5) return false;
    return parent::canCreate($member, $context);
}
1 Like

Perfect, cheers! You’re kill’n it - your help is much appreciated.

1 Like