Creating a Products Widget

Creating a Products Widget

Wouldn't it be nice to be able to place one or more Solidus products onto a page managed by Scrivito? Let's create a widget for this!

The basics

Run rails g scrivito:widget SolidusProductsWidget to create the widget model and its views. Then open the model file and add a stringlist attribute named product_ids. Also, provide it with a products method that returns Spree::Product instances of the products stored in product_ids. This is what the model file should finally contain:

For letting editors specify the IDs of the products the widget should render, extend the details view of the SolidusProductsWidget so that the product_ids attribute becomes editable. The view should finally contain the following:

To have a SolidusProductsWidget instance render the products, set the contents of its show view to the following:

As you can see, we simply utilize the spree/shared/products partial, which is provided by Solidus/Spree.


We would like to be able to auto-complete Solidus products on the details page of a SolidusProductsWidget instance. For this, we provide a custom inplace editor. This editor uses the API provided by Solidus/Spree.

First, add the following gems to your Gemfile (if they are not present yet):

gem 'underscore-rails'
gem 'coffee-rails', '~> 4.2'

Run bundle install. Then extend the widget's details view so that it renders the spree_api_key of the current user:

The details view should finally look like this (we also changed the dialog size from medium to large):

The Spree API can be configured to not require an API key for read-only access: Just set config.requires_authentication to false during Spree::Api::Config.configure. In this case it is, of course, not necessary to render the user's API key as shown above.

Next, create app/assets/javascripts/ and set its contents to:

Then, add the following to app/assets/javascripts/cms.js:

It is important that the JavaScript of the products_editor is inserted after //= require scrivito.

If you restart your server now, you should be able to auto-complete products in the properties dialog of any SolidusProductsWidget instance. Just start typing, e.g. Spa”. You can also reorder the products in the list.

Note: The instructions do not include error handling in the case of an invalid product being added. This was consciously done in an effort to keep the tutorial simple.