Sha256: 6ac0ee98ef0f412a7834984a80c6ab8e0e9eac35005fb91cba6f1d754303b023

Contents?: true

Size: 1.41 KB

Versions: 4

Compression:

Stored size: 1.41 KB

Contents

require "formalist/element"

module Formalist
  class Elements
    class Field < Element
      attribute :label
      attribute :hint
      attribute :placeholder
      attribute :inline
      attribute :validation

      def fill(input: {}, errors: {})
        super(
          input: input[name],
          errors: errors[name].to_a,
        )
      end

      # Converts the field into an abstract syntax tree.
      #
      # It takes the following format:
      #
      # ```
      # [:field, [params]]
      # ```
      #
      # With the following parameters:
      #
      # 1. Field name
      # 2. Custom form element type (or `:field` otherwise)
      # 3. Associated form input data
      # 4. Error messages
      # 5. Form element attributes
      #
      # @see Formalist::Element::Attributes#to_ast "Form element attributes" structure
      #
      # @example "email" field
      #   field.to_ast
      #   # => [:field, [
      #     :email,
      #     :field,
      #     "jane@doe.org",
      #     [],
      #     [:object, []],
      #   ]]
      #
      # @return [Array] the field as an abstract syntax tree.
      def to_ast
        # errors looks like this
        # {:field_name => [["pages is missing", "another error message"], nil]}

        [:field, [
          name,
          type,
          input,
          errors,
          Element::Attributes.new(attributes).to_ast,
        ]]
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
formalist-0.9.0 lib/formalist/elements/field.rb
formalist-0.8.0 lib/formalist/elements/field.rb
formalist-0.7.0 lib/formalist/elements/field.rb
formalist-0.6.0 lib/formalist/elements/field.rb