Kiril Kirilov
Kiril Kirilov

Reputation: 11257

Rails: Form with conditional required field

I'm relatively new to RoR. I got the following source in haml

= form.text_field :country, 'Country'
= form.text_field :state, 'State', :placeholder => 'optional'

but the :state filed is not exactly optional, it is optional only if the user is non-US user, If his/her country=='USA', the field must become required.

Upvotes: 4

Views: 1891

Answers (1)

Learner
Learner

Reputation: 4636

Why not trying,

In your case,

HAML is indentation based , and the parser can be tricky.You don't need to use "- end" in Haml. Use indentation instead.In Haml,a block begins whenever the indentation is increased after a Ruby evaluation command. It ends when the indentation decreases.Sample if else block as follows.

- if country != 'USA' # change country variable to your country value variable
  = form.text_field :state, 'State', :placeholder => 'optional'
- else
  = form.text_field :state, 'State', :placeholder => 'Mandatory'

If you want to use just IF condition,

- if country != 'USA' # change country variable to your country value variable
  = form.text_field :state, 'State', :placeholder => 'optional'

In a normal ruby form code,

<% if @country == 'USA' %> # change @country variable to your country value variable
  <%= form.text_field :state, 'State', :placeholder => 'Mandatory' %>
<% else %>
  <%= form.text_field :state, 'State', :placeholder => 'optional' %>
<% end %>

Above is just an example to get the idea.. because I didn't know about the country value stored in which variable.

Upvotes: 2

Related Questions