Creating and Modifying Widgets with Ruby

Creating and Modifying Widgets with Ruby

Creating a CMS object with widgets

Suppose that you need to provide a couple of pre-built pages to your editors because you want to ensure that the pages have a particular structure. Here’s how this can be done using the Scrivito SDK:

This code assumes that the page object class, “DescriptionPage”, as well as the widget object classes, “TwoColumnWidget”, “TextWidget”, and “ImageWidget”, exist. If they don’t, create the object classes first.

The “main_content” attribute of the “DescriptionPage” class is a widgetlist attribute to which a two-column widget is added. Both its columns are filled with further widgets.

The “image” attribute of the “ImageWidget” needs to be of the reference type.

Accessing and modifying widgets

The contents of a widgetlist attribute of a given CMS object can be retrieved like so:

The result is always an array of widgets, or an empty array if the widget attribute doesn’t contain any widgets. Thus, you can iterate over the widgets and process them as desired.

A widget is contained either in a widgetlist attribute at the top level, or in another widget. You can use the container method to determine the origin of a widget, and the container_field_name method to retrieve the name of the attribute containing the widget:

After modifying a widget, make sure to update it in the CMS unless you are going to update the CMS object that contains the widget:

That’s it. Happy coding!