Pages and widgets can have attributes for associating them with specific data, e.g. an author name, a background image, a color, etc. Sometimes it is helpful to be able to have a default value assigned to an attribute in the very moment a CMS object or widget is created. This way, editors are given the option to alter a predefined property instead of forcing them to set this property's value for each and every new page or widget.
For this, Obj.create
and Widget.new
– the methods used for creating a CMS object or widget, respectively – accept an attributes
hash as an argument.
For specifying simple defaults, the Obj.attribute
and Widget.attribute
methods have a corresponding parameter (default
, see below for an example).
For specifying more advanced default values, Obj.default_for(attribute_name, &block)
and Widget.default_for(attribute_name, &block)
are available. The block is called with two arguments:
- The first argument is an
ActiveSupport::HashWithIndifferentAccess
containing the attributes passed toObj.create_with_defaults
orWidget.new_with_defaults
, respectively. - The second argument represents the context as a
Hash
. If thedefault_for
callback is triggered by a UI user creating a CMS object or a Widget, Scrivito places thecurrent_user
and thecurrent_page
(originating from the UI calling the creation method) into this hash. However,current_page
won't be present in the context hash if the user creates the object or widget while viewing a page which isn't a CMS object. Also, the context hash is empty if the object or widget is not created using the UI but, for example, via the console.
Please refer to the documentation on users and permissions, in particular on the Scrivito::Configuration.editing_auth
callback, for details about specifying the current user.