Last active
February 2, 2023 21:44
-
-
Save tinabel/e127541571e0186ed97ed8bcf72b1b6d to your computer and use it in GitHub Desktop.
associate label with checkbox
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# frozen_string_literal: true | |
module Form | |
module Checkbox | |
class Component < ApplicationComponent | |
def initialize(name: nil, label: nil, form: nil, attribute: nil, reversed: false, checked: false, value: "1", unchecked_value: "0", error: false, **input_options) | |
@name = name | |
@label = label | |
@form = form | |
@attribute = attribute | |
@reversed = reversed | |
@checked = checked | |
@value = value | |
@unchecked_value = unchecked_value | |
@error = error | |
@input_options = input_options | |
end | |
private | |
def before_render | |
validate! | |
end | |
def validate! | |
raise ArgumentError, "#{self.class.name} requires a `:name` when not part of a form" if @name.nil? && !for_form? | |
end | |
def input_options | |
@input_options[:class] = class_names("vc--checkbox__input", @input_options[:class], { "for-error" => @error }) | |
@input_options[:id] = @input_options[:id].presence || "checkbox-input--#{SecureRandom.hex(10)}" if @label.present? | |
@input_options | |
end | |
def for_form? | |
@form.present? && @attribute.present? | |
end | |
def checkbox | |
for_form? ? @form.check_box(@attribute, input_options, @value, @unchecked_value) : check_box_tag(@name, @value, @checked, input_options) | |
end | |
def translate_user_generated_content? | |
return unless input_options[:data].present? | |
input_options[:data][:translation_target].presence == "userGeneratedContent" | |
end | |
def label | |
render( | |
Form::Label::Component.new( | |
name: @name, | |
text: @label, | |
form: @form, | |
attribute: @attribute, | |
for: input_options[:id], | |
required: input_options[:required], | |
class: class_names("vc--checkbox__label", { "for-disabled" => input_options[:disabled], "for-reversed" => @reversed }) ) | |
) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment