Class: Hanami::Helpers::FormHelper::Form

Inherits:
Object
  • Object
show all
Defined in:
gems/gems/hanami-helpers-1.3.0/lib/hanami/helpers/form_helper.rb

Overview

Form object

Since:

  • 0.2.0

Instance Method Summary collapse

Constructor Details

#initialize(name, url, values = {}, attributes = {}) ⇒ Form

Initialize a form

It accepts a set of values that are used in combination with request params to autofill value attributes for fields.

The keys of this Hash, MUST correspond to the structure of the (nested) fields of the form.

For a given input where the name is book[title], Hanami will look for :book key in values.

If the current params have the same key, it will be PREFERRED over the given values.

For instance, if params.get('book.title') equals to "TDD" while values[:book].title returns "No test", the first will win.

Examples:

Pass A Value

# Given the following view

module Web::Views::Deliveries
  class Edit
    include Web::View

    def form
      Form.new(:delivery, routes.delivery_path(id: delivery.id),
      {delivery: delivery, customer: customer},
      {method: :patch})
    end
  end
end

# And the corresponding template:

<%=
  form_for form do
    date_field :delivered_on

    fields_for :customer do
      text_field :name

      fields_for :address do
        # ...
        text_field :city
      end
    end

    submit 'Update'
  end
%>

<!-- output -->

<form action="/deliveries/1" method="POST" accept-charset="utf-8">
  <input type="hidden" name="_method" value="PATCH">
  <input type="hidden" name="_csrf_token" value="920cd5bfaecc6e58368950e790f2f7b4e5561eeeab230aa1b7de1b1f40ea7d5d">

  # Value taken from delivery.delivered_on
  <input type="date" name="delivery[delivered_on]" id="delivery-delivered-on" value="2015-05-27">

  # Value taken from customer.name
  <input type="text" name="delivery[customer][name]" id="delivery-customer-name" value="Luca">

  # Value taken from customer.address.city
  <input type="text" name="delivery[customer][address][city]" id="delivery-customer-address-city" value="Rome">

  <button type="submit">Update</button>
</form>

Parameters:

  • name (Symbol)

    the name of the form

  • url (String)

    the action of the form

  • values (Hash, NilClass) (defaults to: {})

    a Hash of values to be used to autofill value attributes for fields

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

    a Hash of attributes to pass to the form tag

Since:

  • 0.2.0

def initialize(name, url, values = {}, attributes = {})
  @name       = name
  @url        = url
  @values     = values
  @attributes = attributes || {}
end