سؤال

I am trying to create custom form builder in rails to convert this code

    <div class="row collapse">
      <div class="large-4 columns">
        <%= builder.label :vacancy_title, "Title of the Vacancy", class: "right inline" %>
      </div>
      <div class="large-8 columns">
        <%= builder.text_field :vacancy_title, class: "tiny" %>
      </div>
    </div>

to simple

<%= builder.t_field :vacancies, "Label title" %>

I am trying this code with no luck, it just displays label.

#form_builders/custom_form_builder.rb
class CustomFormBuilder < ActionView::Helpers::FormBuilder
def t_field(name, title, *args)
   @template.content_tag :div, class: "row collapse" do
     @template.content_tag :div, class: "large-8 columns" do
   text_field_tag(name, *args)
     end

   @template.content_tag :div, class: "large-4 columns" do
     @template.content_tag :h5 do
       label(title, options[:label], class: "right inline")
     end
   end

 end
end

Something is obviously wrong with text_field_tag(name, *args), but I have no idea how to declare input. I couldn't found any docs on rubyapi Helpers::FormBuilder

SOLVED

Thanks to Levi Stanley i solved this with the following code. I need to change text_field_tag(name, *args) with text_field_tag("#{object_name}[#{name}]") and label(title, options[:label], class: "right inline") with label(name, title, *args, class: "right") in order the form works properly with nested attributes.

class LabeledFormBuilder < ActionView::Helpers::FormBuilder
  def t_field(name, title, *args)
    @template.content_tag :div, class: "row collapse" do
      (@template.content_tag :div, class: "large-4 columns" do
        @template.content_tag :h5 do
          label(name, title, *args, class: "right")
        end
      end) +
      (@template.content_tag :div, class: "large-8 columns" do
        @template.text_field_tag("#{object_name}[#{name}]")
      end)
    end
  end
end
هل كانت مفيدة؟

المحلول

You need to concat the content_tags for the inner divs together. The content_tag method uses the return value of the block to determine its contents. You are running the code for the div containing the text_field_tag but not actually including it in the outer "row collapse" div since it isn't included in the return value of the block.

#form_builders/custom_form_builder.rb
class CustomFormBuilder < ActionView::Helpers::FormBuilder
  def t_field(name, title, *args)

    @template.content_tag :div, class: "row collapse" do
      (@template.content_tag :div, class: "large-8 columns" do
        text_field_tag(name, *args)
      end) +

      (@template.content_tag :div, class: "large-4 columns" do
        @template.content_tag :h5 do
          label(title, options[:label], class: "right inline")
        end
      end)
    end
  end
end
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top