Sherlock_Stalker
Sherlock_Stalker

Reputation: 37

Rails: Two values for label_method (simple_form_for)

I want to create a new pm_workload. I have the following code-snippet

<%= f.input :project_id, :collection => PmProject.order('name'), :label_method => :name, :value_method => :id, :label => "Project", :include_blank => false %>

Is there an option to use two values for :label_method? e.g.
:label_method => :name << (PmProject.project_number)

Upvotes: 2

Views: 1711

Answers (2)

RobL
RobL

Reputation: 57

I've been looking at this problem this week. But a variation of it, in my case I wanted the label text to be wrapped in a <span>. I thought I was looking for was related to simple_form but actually it's still part of Rails ActionView tags helpers.

Yes, you could add another method on your model, but if you like to keep your models clean or you want to use something not in the model in the label. :label_method can also be a proc.

<% label_method = proc { |p| "#{p.name} #{p.project_number}" } %>
<%= f.input :project_id, collection: PmProject.order('name'), label_method: label_method, value_method :id, label: 'Project', include_blank: false %>

or in my case

<% label_method = proc { |p| "<span>#{p.name}</span>".html_safe } %>
<%= f.input :project_id, collection: PmProject.order('name'), label_method: label_method, value_method :id, label: 'Project', include_blank: false %>

Upvotes: 0

Bharat soni
Bharat soni

Reputation: 2786

It's not possible to have to attributes or field name inside the label method. But I have an alternate soluction for you resolve this problem.

You are taking PmProject collections, So now create a instance level method insdie the PmProject model like as below.

def name_of_method
  "#{name} #{project_number}"
end

Now to use the same on the view input of the simple form for use like that as below...

<%= f.input :project_id, :collection => PmProject.order('name'), :label_method => :name_of_method, :value_method => :id, :label => "Project", :include_blank => false %>

Upvotes: 2

Related Questions