Providing Custom Buttons in Place

Providing Custom Buttons in Place

Scrivito includes a collection of pre-built JavaScript editors combined in the Scrivito Editors gem. You can even make use of Scrivito’s API for in-place editing to write your own editor. But you can also use the API to customize in-place editing as a whole.

In this technical overview, we will show you entry points to do that. Example code in this document is meant to give an idea of what is possible with the API. However, since Scrivito already comes with everything you need, you might, eventually, come to the conclusion that there's nothing to customize at all.

Getting notified when editing is activated

All editing features on the website utilize the Javascript API of the Scrivito SDK. The SDK triggers an event after the page and the UI have been loaded. If editing is activated, i.e. if you clicked the Edit button on the Scrivito panel at the top of the page, the SDK signals this.

In all other cases, if you haven't activated editing or don't have sufficient permission, or aren't even logged in, this event is not triggered.

So, we subscribe to this event and render a button right into the DOM of our sidebar if editing is active. Clicking the button will have no effect yet, but we will attach a click handler in a moment.

Append the following content to the app/assets/javascripts/application.js file:

Creating a CMS object with the click of a button

Let's define the behavior of the button now. When someone clicks this button, an empty page should be created in the Scrivito database, and the browser should be redirected to this new page. There you can fill in all the details of the page, in place.

Append the following click handler to the function above:

Let's take a short look at this code:

The outermost function is a standard jQuery click handler. In it, the button is disabled to make sure it is not clicked twice. A CMS object is created using scrivito.create_obj to which a hash of attributes is passed.

scrivito.create_obj returns a promise. It is resolved on success, so we can then redirect the browser to the newly created page.

This short overview should give you an idea about the code needed to provide custom in-place editing functionality to your editors.