Search code examples
ruby-on-railssimple-form

Rails simple_form default input value not showing


I have a custom text input that I'm trying to display a default value in. The value gets set in the HTML, but is not displayed in the actual input.

My custom input:

class DateTimePickerInput < SimpleForm::Inputs::Base
  def input(wrapper_options)
    template.content_tag(:div, class: "input-group", style: "width: 100%;") do
      template.concat @builder.text_field(attribute_name, input_html_options)
      template.concat span_icon
    end
  end

  def input_html_options
    super.merge({ class: 'text datetimepicker form-control', "data-date-input": "", value: default_value })
  end

  def span_icon
    template.content_tag(:span, class: "input-group-addon") do
      template.content_tag(:i, class: "material-icons") do
        "date_range"
      end
    end
  end

  def default_value
    object.send(attribute_name).to_time.strftime("%F %I:%M %p") if object.send(attribute_name).present?
  end
end

The way I'm calling the input:

<%= f.input :expired_at, as: :date_time_picker %>

I have also tried with no luck:

<%= f.input :expired_at, as: :date_time_picker, input_html: { value: evaluation.expired_at } %>

I have also tried to replace the default_value method with a simple string "hello" to test that it renders. It does not.


Solution

  • This question was solved. The problem was that I was not telling the input what format to put the data in.

    The solution was achieved by adding the following to the input_html_options method:

    data: { date_format: "YYYY-MM-DD hh:mm A" }

    So that the line now looks like:

    super.merge({ value: default_value, class: "text datetimepicker form-control", data: { date_format: "YYYY-MM-DD hh:mm A" } })