Method: Scrivito::BasicObj.create

Defined in:
app/cms/scrivito/basic_obj.rb

.create(attributes = {}, context = {}) ⇒ Obj

Create a new Obj in the CMS.

This allows you to set the different attributes of an Obj by providing a hash containing the attribute names as keys and the corresponding values you want to set. The defaults set via Obj.default_for are taken into account.

Examples:

Provide reference lists as an Array of Obj.

Obj.create(:reference_list => [other_obj])

Passing an Obj allows you to set a reference.

Obj.create(:reference => other_obj)

You can upload files by passing a Ruby File object.

Obj.create(:blob => File.new("image.png"))

A link list can be set as an Array of Links.

Obj.create(:link_list => [
  # external link
  Link.new(:url => "http://www.example.com", :title => "Example"),
  # internal link
  Link.new(:obj => other_obj, :title => "Other Obj")
])

Passing a Link allows you to set a link.

Obj.create(
  external_link: Link.new(url: 'http://www.example.com', title: 'Example'),
  internal_link: Link.new(obj: other_obj, title: 'Other Obj')
)

Date attributes accept Time, Date and their subclasses (DateTime, for example).

Obj.create(:date => Time.new)
Obj.create(:date => Date.now)

String, html and enum attributes can be set by passing a String value.

Obj.create(:title => "My Title")

Multienum attributes can be set using an Array of Strings.

Obj.create(:tags => ["ruby", "rails"])

Simply pass an Array of Widgets to populate a widget field. See Widget#copy on how to copy a widget.

# Add new widgets
Obj.create(:widgets => [Widget.new(_obj_class: 'TitleWidget', title: 'My Title')])

# Add a copy of a widget
Obj.create(:widgets => [another_obj.widgets.first.copy])

# Change a widget field
obj.update(:widgets => [obj.widgets.first])

# Clear a widget field
obj.update(:widgets => [])

Parameters:

  • attributes (Hash) (defaults to: {})

    of the new obj

  • context (Hash) (defaults to: {})

    in which the object is created

Options Hash (context):

Returns:

  • (Obj)

    the newly created Obj

Raises:

  • (ArgumentError)

    if called on Obj without _obj_class attribute.

See Also:



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'app/cms/scrivito/basic_obj.rb', line 139

def self.create(attributes = {}, context = {})
  attributes = with_default_id_attribute(attributes)
  if obj_class = extract_obj_class_from_attributes(attributes)
    obj_class.create(attributes, context)
  else
    attributes = build_attributes_with_defaults(attributes, context)
    attributes = prepare_attributes_for_instantiation(attributes)
    extraction, api_attributes = prepare_attributes_for_rest_api(attributes)

    workspace = Workspace.current
    obj_data = workspace.create_obj(obj: api_attributes)
    obj = BasicObj.instantiate(obj_data)
    obj.revision = workspace.revision

    extraction.notify_persisted(obj)
    obj
  end
end