Class: Decidim::FormBuilder

Inherits:
FoundationRailsHelper::FormBuilder
  • Object
show all
Includes:
ActionView::Context, TranslatableAttributes
Defined in:
lib/decidim/form_builder.rb

Overview

This custom FormBuilder adds fields needed to deal with translatable fields, following the conventions set on ‘Decidim::TranslatableAttributes`.

Direct Known Subclasses

AuthorizationFormBuilder, FilterFormBuilder

Instance Method Summary collapse

Instance Method Details

#areas_select(name, collection, options = {}) ⇒ Object

Public: Generates a select field for areas.

name - The name of the field (usually area_id) collection - A collection of areas or area_types.

If it's areas, we sort the selectable options alphabetically.

Returns a String.



229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/decidim/form_builder.rb', line 229

def areas_select(name, collection, options = {})
  selectables = if collection.first.is_a?(Decidim::Area)
                  assemblies = collection
                               .map { |a| [a.name[I18n.locale.to_s], a.id] }
                               .sort_by { |arr| arr[0] }

                  @template.options_for_select(
                    assemblies,
                    selected: options[:selected]
                  )
                else
                  @template.option_groups_from_collection_for_select(
                    collection,
                    :areas,
                    :translated_name,
                    :id,
                    :translated_name,
                    selected: options[:selected]
                  )
                end

  select(name, selectables, options)
end

#categories_select(name, collection, options = {}) ⇒ Object

Public: Generates a select field with the categories. Only leaf categories can be set as selected.

name - The name of the field (usually category_id) collection - A collection of categories. options - An optional Hash with options:

  • prompt - An optional String with the text to display as prompt.

  • disable_parents - A Boolean to disable parent categories. Defaults to ‘true`.

Returns a String.



204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/decidim/form_builder.rb', line 204

def categories_select(name, collection, options = {})
  options = {
    disable_parents: true
  }.merge(options)

  disable_parents = options[:disable_parents]

  selected = object.send(name)
  categories = categories_for_select(collection)
  disabled = if disable_parents
               disabled_categories_for(collection)
             else
               []
             end
  html_options = {}
  select(name, @template.options_for_select(categories, selected: selected, disabled: disabled), options, html_options)
end

#check_box(attribute, options = {}, checked_value = "1", unchecked_value = "0") ⇒ Object

Public: Override so checkboxes are rendered before the label.



318
319
320
321
322
323
324
# File 'lib/decidim/form_builder.rb', line 318

def check_box(attribute, options = {}, checked_value = "1", unchecked_value = "0")
  custom_label(attribute, options[:label], options[:label_options], true) do
    options.delete(:label)
    options.delete(:label_options)
    @template.check_box(@object_name, attribute, objectify_options(options), checked_value, unchecked_value)
  end + error_and_help_text(attribute, options)
end

#collection_check_boxes(attribute, collection, value_attribute, text_attribute, options = {}, html_options = {}) ⇒ Object

Public: generates a check boxes input from a collection and adds help text and errors.

attribute - the name of the field collection - the collection from which we will render the check boxes value_attribute - a Symbol or a Proc defining how to find the value

attribute

text_attribute - a Symbol or a Proc defining how to find the text

attribute

options - a Hash with options html_options - a Hash with options

Renders a collection of check boxes. rubocop:disable Metrics/ParameterLists



26
27
28
# File 'lib/decidim/form_builder.rb', line 26

def collection_check_boxes(attribute, collection, value_attribute, text_attribute, options = {}, html_options = {})
  super + error_and_help_text(attribute, options)
end

#collection_radio_buttons(attribute, collection, value_attribute, text_attribute, options = {}, html_options = {}) ⇒ Object

Public: generates a radio buttons input from a collection and adds help text and errors.

attribute - the name of the field collection - the collection from which we will render the check boxes value_attribute - a Symbol or a Proc defining how to find the value attribute text_attribute - a Symbol or a Proc defining how to find the text attribute options - a Hash with options html_options - a Hash with options

Renders a collection of radio buttons. rubocop:disable Metrics/ParameterLists



43
44
45
# File 'lib/decidim/form_builder.rb', line 43

def collection_radio_buttons(attribute, collection, value_attribute, text_attribute, options = {}, html_options = {})
  super + error_and_help_text(attribute, options)
end

#data_picker(attribute, options = {}, prompt_params = {}) ⇒ Object

Public: Generates a picker field for selection (either simple or multiselect).

attribute - The name of the object’s attribute. options - A Hash with options:

  • multiple: Multiple mode, to allow selection of multiple items.

  • label: Show label?

  • name: (optional) The name attribute of the input elements.

prompt_params - Hash with options:

  • url: The url where the ajax endpoint that will fill the content of the selector popup (the prompt).

  • text: Text in the button to open the Data Picker selector.

Also it should receive a block that returns a Hash with :url and :text for each selected scope

Returns an html String.



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/decidim/form_builder.rb', line 300

def data_picker(attribute, options = {}, prompt_params = {})
  picker_options = {
    id: "#{@object_name}_#{attribute}",
    class: "picker-#{options[:multiple] ? "multiple" : "single"}",
    name: options[:name] || "#{@object_name}[#{attribute}]"
  }
  picker_options[:class] += " is-invalid-input" if error?(attribute)

  items = object.send(attribute).collect { |item| [item, yield(item)] }

  template = ""
  template += label(attribute, label_for(attribute) + required_for_attribute(attribute)) unless options[:label] == false
  template += @template.render("decidim/widgets/data_picker", picker_options: picker_options, prompt_params: prompt_params, items: items)
  template += error_and_help_text(attribute, options)
  template.html_safe
end

#date_field(attribute, options = {}) ⇒ Object

Public: Override so the date fields are rendered using foundation datepicker library



328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/decidim/form_builder.rb', line 328

def date_field(attribute, options = {})
  value = object.send(attribute)
  data = { datepicker: "" }
  data[:startdate] = I18n.localize(value, format: :decidim_short) if value.present? && value.is_a?(Date)
  datepicker_format = ruby_format_to_datepicker(I18n.t("date.formats.decidim_short"))
  data[:"date-format"] = datepicker_format

  template = text_field(
    attribute,
    options.merge(data: data)
  )
  help_text = I18n.t("decidim.datepicker.help_text", datepicker_format: datepicker_format)
  template += error_and_help_text(attribute, options.merge(help_text: help_text))
  template.html_safe
end

#datetime_field(attribute, options = {}) ⇒ Object

Public: Generates a timepicker field using foundation datepicker library



346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'lib/decidim/form_builder.rb', line 346

def datetime_field(attribute, options = {})
  value = object.send(attribute)
  data = { datepicker: "", timepicker: "" }
  data[:startdate] = I18n.localize(value, format: :decidim_short) if value.present? && value.is_a?(ActiveSupport::TimeWithZone)
  datepicker_format = ruby_format_to_datepicker(I18n.t("time.formats.decidim_short"))
  data[:"date-format"] = datepicker_format

  template = text_field(
    attribute,
    options.merge(data: data)
  )
  help_text = I18n.t("decidim.datepicker.help_text", datepicker_format: datepicker_format)
  template += error_and_help_text(attribute, options.merge(help_text: help_text))
  template.html_safe
end

#editor(name, options = {}) ⇒ Object

Public: generates a hidden field and a container for WYSIWYG editor

name - The name of the field options - The set of options to send to the field

:label - The Boolean value to create or not the input label (optional) (default: true)
:toolbar - The String value to configure WYSIWYG toolbar. It should be 'basic' or
           or 'full' (optional) (default: 'basic')
:lines - The Integer to indicate how many lines should editor have (optional) (default: 10)
:disabled - Whether the editor should be disabled

Renders a container with both hidden field and editor container



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/decidim/form_builder.rb', line 177

def editor(name, options = {})
  options[:toolbar] ||= "basic"
  options[:lines] ||= 10
  options[:disabled] ||= false

  (:div, class: "editor #{"hashtags__container" if options[:hashtaggable]}") do
    template = ""
    template += label(name, options[:label].to_s || name) if options[:label] != false
    template += hidden_field(name, options)
    template += (:div, nil, class: "editor-container #{"js-hashtags" if options[:hashtaggable]}", data: {
                              toolbar: options[:toolbar],
                              disabled: options[:disabled]
                            }, style: "height: #{options[:lines]}rem")
    template += error_for(name, options) if error?(name)
    template.html_safe
  end
end

#form_field_for(attribute, options = {}) ⇒ Object



422
423
424
425
426
427
428
# File 'lib/decidim/form_builder.rb', line 422

def form_field_for(attribute, options = {})
  if attribute == :body
    text_area(attribute, options.merge(rows: 10))
  else
    text_field(attribute, options)
  end
end

#hashtaggable_text_field(type, name, locale, options = {}) ⇒ Object

Public: Generates a field for hashtaggable type. type - The form field’s type, like ‘text_area` or `text_input` name - The name of the field handlers - The social handlers to be created options - The set of options to send to the field

Renders form fields for each locale.



114
115
116
117
118
119
120
121
122
# File 'lib/decidim/form_builder.rb', line 114

def hashtaggable_text_field(type, name, locale, options = {})
  (:div, class: "hashtags__container") do
    if options[:value]
      send(type, name_with_locale(name, locale), options.merge(label: options[:label], value: options[:value][locale]))
    else
      send(type, name_with_locale(name, locale), options.merge(label: options[:label]))
    end
  end
end

#label_for(attribute) ⇒ Object

Public: Returns the translated name for the given attribute.

attribute - The String name of the attribute to return the name.



414
415
416
417
418
419
420
# File 'lib/decidim/form_builder.rb', line 414

def label_for(attribute)
  if object.class.respond_to?(:human_attribute_name)
    object.class.human_attribute_name(attribute)
  else
    attribute.to_s.humanize
  end
end

#scopes_picker(attribute, options = {}) ⇒ Object

Public: Generates a picker field for scope selection.

attribute - The name of the field (usually scope_id) options - An optional Hash with options:

  • multiple - Multiple mode, to allow multiple scopes selection.

  • label - Show label?

  • checkboxes_on_top - Show checked picker values on top (default) or below the picker prompt

Also it should receive a block that returns a Hash with :url and :text for each selected scope (and for null scope for prompt)

Returns a String.



264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# File 'lib/decidim/form_builder.rb', line 264

def scopes_picker(attribute, options = {})
  picker_options = {
    id: "#{@object_name}_#{attribute}",
    class: "picker-#{options[:multiple] ? "multiple" : "single"}",
    name: "#{@object_name}[#{attribute}]"
  }

  picker_options[:class] += " is-invalid-input" if error?(attribute)

  prompt_params = yield(nil)
  scopes = selected_scopes(attribute).map { |scope| [scope, yield(scope)] }
  template = ""
  template += label(attribute, label_for(attribute) + required_for_attribute(attribute)) unless options[:label] == false
  template += @template.render("decidim/scopes/scopes_picker_input",
                               picker_options: picker_options,
                               prompt_params: prompt_params,
                               scopes: scopes,
                               checkboxes_on_top: options[:checkboxes_on_top])
  template += error_and_help_text(attribute, options)
  template.html_safe
end

#social_field(type, name, handlers, options = {}) ⇒ Object

Public: Generates an form field for each social.

type - The form field’s type, like ‘text_area` or `text_input` name - The name of the field handlers - The social handlers to be created options - The set of options to send to the field

Renders form fields for each locale.



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
# File 'lib/decidim/form_builder.rb', line 132

def social_field(type, name, handlers, options = {})
  tabs_id = sanitize_tabs_selector(options[:tabs_id] || "#{object_name}-#{name}-tabs")

  label_tabs = (:div, class: "label--tabs") do
    field_label = label_i18n(name, options[:label] || label_for(name))

    tabs_panels = "".html_safe
    if options[:label] != false
      tabs_panels = (:ul, class: "tabs tabs--lang", id: tabs_id, data: { tabs: true }) do
        handlers.each_with_index.inject("".html_safe) do |string, (handler, index)|
          string + (:li, class: tab_element_class_for("title", index)) do
            title = I18n.t(".#{handler}", scope: "activemodel.attributes.#{object_name}")
            tab_content_id = sanitize_tabs_selector "#{tabs_id}-#{name}-panel-#{index}"
            (:a, title, href: "##{tab_content_id}")
          end
        end
      end
    end

    safe_join [field_label, tabs_panels]
  end

  tabs_content = (:div, class: "tabs-content", data: { tabs_content: tabs_id }) do
    handlers.each_with_index.inject("".html_safe) do |string, (handler, index)|
      tab_content_id = sanitize_tabs_selector "#{tabs_id}-#{name}-panel-#{index}"
      string + (:div, class: tab_element_class_for("panel", index), id: tab_content_id) do
        send(type, "#{handler}_handler", options.merge(label: false))
      end
    end
  end

  safe_join [label_tabs, tabs_content]
end

#translated(type, name, options = {}) ⇒ Object

Public: Generates an form field for each locale.

type - The form field’s type, like ‘text_area` or `text_input` name - The name of the field options - The set of options to send to the field

Renders form fields for each locale.



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/decidim/form_builder.rb', line 55

def translated(type, name, options = {})
  return translated_one_locale(type, name, locales.first, options.merge(label: (options[:label] || label_for(name)))) if locales.count == 1

  tabs_id = sanitize_tabs_selector(options[:tabs_id] || "#{object_name}-#{name}-tabs")

  label_tabs = (:div, class: "label--tabs") do
    field_label = label_i18n(name, options[:label] || label_for(name))

    tabs_panels = "".html_safe
    if options[:label] != false
      tabs_panels = (:ul, class: "tabs tabs--lang", id: tabs_id, data: { tabs: true }) do
        locales.each_with_index.inject("".html_safe) do |string, (locale, index)|
          string + (:li, class: tab_element_class_for("title", index)) do
            title = I18n.with_locale(locale) { I18n.t("name", scope: "locale") }
            element_class = nil
            element_class = "is-tab-error" if error?(name_with_locale(name, locale))
            tab_content_id = sanitize_tabs_selector "#{tabs_id}-#{name}-panel-#{index}"
            (:a, title, href: "##{tab_content_id}", class: element_class)
          end
        end
      end
    end

    safe_join [field_label, tabs_panels]
  end

  tabs_content = (:div, class: "tabs-content", data: { tabs_content: tabs_id }) do
    locales.each_with_index.inject("".html_safe) do |string, (locale, index)|
      tab_content_id = "#{tabs_id}-#{name}-panel-#{index}"
      string + (:div, class: tab_element_class_for("panel", index), id: tab_content_id) do
        if options[:hashtaggable]
          hashtaggable_text_field(type, name, locale, options.merge(label: false))
        else
          send(type, name_with_locale(name, locale), options.merge(label: false))
        end
      end
    end
  end

  safe_join [label_tabs, tabs_content]
end

#translated_one_locale(type, name, locale, options = {}) ⇒ Object



97
98
99
100
101
102
103
104
105
# File 'lib/decidim/form_builder.rb', line 97

def translated_one_locale(type, name, locale, options = {})
  return hashtaggable_text_field(type, name, locale, options.merge(value: options[:value])) if options[:hashtaggable]

  send(
    type,
    "#{name}_#{locale.to_s.gsub("-", "__")}",
    options.merge(label: options[:label] || label_for(name))
  )
end

#upload(attribute, options = {}) ⇒ Object

Public: Generates a file upload field and sets the form as multipart. If the file is an image it displays the default image if present or the current one. By default it also generates a checkbox to delete the file. This checkbox can be hidden if ‘options` is passed as `false`.

attribute - The String name of the attribute to buidl the field. options - A Hash with options to build the field.

* optional: Whether the file can be optional or not.


370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
# File 'lib/decidim/form_builder.rb', line 370

def upload(attribute, options = {})
  self.multipart = true
  options[:optional] = options[:optional].nil? ? true : options[:optional]

  file = object.send attribute
  template = ""
  template += label(attribute, label_for(attribute) + required_for_attribute(attribute))
  template += @template.file_field @object_name, attribute

  if file_is_image?(file)
    template += if file.present?
                  @template. :label, I18n.t("current_image", scope: "decidim.forms")
                else
                  @template. :label, I18n.t("default_image", scope: "decidim.forms")
                end
    template += @template.link_to @template.image_tag(file.url), file.url, target: "_blank", rel: "noopener"
  elsif file_is_present?(file)
    template += @template.label_tag I18n.t("current_file", scope: "decidim.forms")
    template += @template.link_to file.file.filename, file.url, target: "_blank", rel: "noopener"
  end

  if file_is_present?(file)
    if options[:optional]
      template +=  :div, class: "field" do
        safe_join([
                    @template.check_box(@object_name, "remove_#{attribute}"),
                    label("remove_#{attribute}", I18n.t("remove_this_file", scope: "decidim.forms"))
                  ])
      end
    end
  end

  if object.errors[attribute].any?
    template +=  :p, class: "is-invalid-label" do
      safe_join object.errors[attribute], "<br/>".html_safe
    end
  end

  template.html_safe
end