views:

183

answers:

2

Hi.

I am using button_to and link_to form helpers in Rails. I need to set an html attribute based on a condition in code. More precisely, I need to disable a button_to component only if a certain condition is true.

How can I achieve that? code snippet below.

<%= button_to "Submit", "#", :id=> "submit", :class => "button_white_big", :disabled => true%>

In above statement I may need :disabled=>true or I may not need it. Is there a clean way, apart from duplicating the code line?

Cheers -Priyank

+1  A: 

What is the condition that is true or false?

If it's triggered in the controller, you can set the disabledbutton value, or write a helper, which would take the condition as a variable, and print out the result.

<%= button_to "Submit", "#", :id=> "submit", :class => "button_white_big", @disabled %>

is_disabled? ? @disabled = {:disabled => 'disabled'} : @disabled = false
CodeJoust
I tried disabled => true and false but that doesn't work. What rails generates is always :disabled => disabledSo I am not sure if true and false is an option as a value for disabled.
Priyank
the :disabled option takes true or false, but the HTML either generates 'disabled="disabled"' or nothing as per the source of convert_boolean_attributes! http://apidock.com/rails/ActionView/Helpers/UrlHelper/convert_boolean_attributes!
Martin Gordon
+3  A: 

You can replace the "true" in the disabled with the condition (really any expression that returns a boolean) to get the functionality you need. Like this:

<%= button_to "Submit", "#", :id=> "submit", :class => "button_white_big", :disabled => obj.disabled? %>

or

<%= button_to "Submit", "#", :id=> "submit", :class => "button_white_big", :disabled => x == y %>

etc.

Martin Gordon