Skip to content

Custom inputs examples

Ian Vaughan edited this page Apr 30, 2014 · 10 revisions

Custom inputs examples

Week Day Input

In order to get an input with localized week days:

# app/inputs/wday_input.rb
class WdayInput < SimpleForm::Inputs::Base
  def input
    @builder.select(attribute_name, I18n.t(:"date.day_names").each_with_index.to_a)
  end
end

Then, use it in your form:

<%= timetable.input :wday, :as => :wday %>

Date Time Picker for Twitter Bootstrap 3 using the DateTimePicker JS Library

## app/inputs/date_time_picker_input.rb
class DateTimePickerInput < SimpleForm::Inputs::Base
  def input
    template.content_tag(:div, class: 'input-group date form_datetime') do
      template.concat @builder.text_field(attribute_name, input_html_options)
      template.concat span_remove
      template.concat span_table
    end
  end

  def input_html_options
    {class: 'form-control', readonly: true}
  end

  def span_remove
    template.content_tag(:span, class: 'input-group-addon') do
      template.concat icon_remove
    end
  end

  def span_table
    template.content_tag(:span, class: 'input-group-addon') do
      template.concat icon_table
    end
  end

  def icon_remove
    "<i class='glyphicon glyphicon-remove'></i>".html_safe
  end

  def icon_table
    "<i class='glyphicon glyphicon-th'></i>".html_safe
  end

end

To use add this to an appropriate coffee script file

$(document).ready ->
  $('.form_datetime').datetimepicker({
    autoclose: true,
    todayBtn: true,
    pickerPosition: "bottom-left",
    format: 'mm-dd-yyyy hh:ii'
  });

call on simple form input with

f.input :my_date, as: :date_time_picker