Class: CCS::Components::GovUK::Field::Inputs::Checkboxes

Inherits:
CCS::Components::GovUK::Field::Inputs show all
Defined in:
lib/ccs/components/govuk/field/inputs/checkboxes.rb

Overview

GOV.UK Checkboxes

This is used for generating the checkboxes component from the GDS - Components - Checkboxes

Constant Summary collapse

DEFAULT_ATTRIBUTES =

The default attributes for the checkboxes

{ class: 'govuk-checkboxes', data: { module: 'govuk-checkboxes' } }.freeze

Instance Method Summary collapse

Methods inherited from CCS::Components::GovUK::Field::Inputs

#render

Methods inherited from CCS::Components::GovUK::Field

#render

Constructor Details

#initialize(attribute:, checkbox_items:, **options) ⇒ Checkboxes

Returns a new instance of Checkboxes.

Parameters:

  • checkbox_items (Array<Hash>)

    an array of options for the checkboxes. See Checkbox#initialize for details of the items in the array.

  • fieldset (Hash)

    attributes for the fieldset, see Fieldset#initialize for more details.

  • attribute (String, Symbol)

    the attribute of the field

  • hint (Hash)

    attributes for the hint, see Hint#initialize for more details. If no hint is given then no hint will be rendered

  • form_group (Hash)

    attributes for the form group, see FormGroup#initialize for more details.

  • options (Hash)

    options that will be used for the parts of the field

Options Hash (**options):

  • :error_message (String) — default: nil

    the error message to be displayed

  • :model (ActiveModel) — default: nil

    optional model that can be used to find an error message

  • :form (ActionView::Helpers::FormBuilder) — default: nil

    optional form builder used to create the field and find the error message

  • :classes (String)

    additional CSS classes for the field HTML

  • :attributes (Hash) — default: {}

    any additional attributes that will added as part of the HTML



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/ccs/components/govuk/field/inputs/checkboxes.rb', line 25

def initialize(attribute:, checkbox_items:, **options)
  super(attribute: attribute, **options)

  @options[:values] ||= []
  @options[:values] = (@options[:model] || @options[:form].object).send(attribute) || [] if @options[:model] || @options[:form]

  checkbox_items.each { |checkbox_item| checkbox_item[:checked] = @options[:values].include?(checkbox_item[:value]) } if @options[:values].any?
  checkbox_items.each { |checkbox_item| set_described_by(checkbox_item, @attribute, @error_message, @hint&.send(:options)) } unless @fieldset

  checkbox_item_class = @options[:form] ? Item::Checkbox::Form : Inputs::Item::Checkbox::Tag

  @input_items = checkbox_items.map { |checkbox_item| checkbox_item[:divider] ? Item::Divider.new(divider: checkbox_item[:divider], type: 'checkboxes') : checkbox_item_class.new(attribute: attribute, form: @options[:form], context: @context, **checkbox_item) }
end