Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using conditions in Form Helpers of Rails

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

like image 880
Priyank Avatar asked Dec 18 '25 22:12

Priyank


2 Answers

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.

like image 123
Martin Gordon Avatar answered Dec 20 '25 17:12

Martin Gordon


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 
like image 35
CodeJoust Avatar answered Dec 20 '25 16:12

CodeJoust



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!