text_field disabled in Ruby on Rails - ruby-on-rails

I have the following code to disable a text_field when a user is not an admin and it is working fine:
<div class="form-group">
<%= f.label :nome, "Genero" %>
<%= f.text_field :nome, class: "form-control", disabled: true if not is_admin? %>
</div>
But when a user is an admin the text_field just disappears. Does anyone know why this is happening and what I have to do?

Assuming that is_admin? returns true or false, you can simply do
<%= f.text_field :nome, class: "form-control", disabled: !is_admin? %>
Currently, the if condition i.e., if not is_admin? is applied on the entire text field, which results in text field disappearance when is_admin? returns true and when the condition returns false text field is displayed.

The specific reason that your code wasn't working as expected is an operator precedence issue - the if test is being applied to the whole text field, not just the disabled parameter.
The most direct solution to this (though not necessarily the best) is to wrap true if not is_admin? in parentheses:
<%= f.text_field :nome, class: "form-control", disabled: (true if not is_admin?) %>
Otherwise, the whole text field has the if applied to it, like this:
<%= (f.text_field :nome, class: "form-control", disabled: true) if not is_admin? %>
So it will be rendered only for non-admin users - i.e. when is_admin? is false.
Also, when it's rendered, it will always be disabled. (Which on the plus side, will make it harder for non-admins to abuse.)

Related

Rails require radio button from a collection

I need a way for my form to not be sent if the user didn't bother to select any radio buttons.
I'd like to to that within the view and the controller, not in the model (the data shouldn't even be sent)
<%= form_tag("/bookings/new", method: "get") do %>
<% #flights.each do |flight| %>
<%= radio_button_tag :flight_id, flight.id %>
<% end %>
<%= submit_tag "book now" %>
<% end %>
edit, to clarify
normally I'd do
<%= f.text_field :name, required: true %>
but, as I have many radio buttons and I only need one for the form to work, I don't know how to implement it
You can set validation in the model to see the presence of checkbox if javascript is disabled. This is a more robust method.
validates :flight_id, :acceptance => true
Docs here - http://guides.rubyonrails.org/active_record_validations.html#acceptance
Edit
function validateCheckBox() {
var x = document.getElementById("flight_id").checked;
if(!x) {alert("Not checked")}
}
<%= submit_tag "book now" , :onclick => "validateCheckBox();" %>
<%= f.text_field :name, required: true %>
This still works perfectly for radio buttons, and it's okay if it ends up on all radio items. The form will still only require one input.
I just tested it on my Rails 6 app.

Changing dropdown content in spree form (Rails)

I am working on a project that is built on spree and am trying to concatenate state abbreviations to the state's name in the dropdown when selecting shipping address.
Example: "New York - NY" instead of "New York"
The shipping address form can be found here with the code making the state selection dropdown below:
<% if Spree::Config[:address_requires_state] %>
<p class="form-group" id=<%="#{address_id}state" %>>
<% have_states = !address.country.states.empty? %>
<%= form.label :state do %>
<%= Spree.t(:state) %><abbr class='required' title="required" id=<%="#{address_id}state-required"%>>*</abbr>
<% end %>
<%== state_elements = [
form.collection_select(:state_id, address.country.states,
:id, :name,
{include_blank: true},
{class: have_states ? 'form-control required' : 'form-control hidden',
disabled: !have_states}) +
form.text_field(:state_name,
class: !have_states ? 'form-control required' : 'form-control hidden',
disabled: have_states)
].join.gsub('"', "'").gsub("\n", "")
%>
</p>
<noscript>
<%= form.text_field :state_name, class: 'form-control required' %>
</noscript>
After looking at this post, I thought that :name is the method being called to generate the text in each option, but when I changed it to :abbr (which should be a property that it has) everything stayed exactly the same. I am pretty sure that my changes are running since when I make other changes it works. How would you change the option text and managing that, how would you get both the name and abbreviation and concatenate them together with a hyphen.
Just as a note: I am using Deface::Override to make changes to the code.

Form Required Doesn't Work

I have tested three ways of doing a field required, first with no gem, just the usual form_for and it did work well, but I need some good gem for making easier adding fields to insert associations, then I installed the Simple Form. Here is the code I am using:
<%= simple_form_for #post do |p| %>
<%= p.text_field :title, :required => true %> <br />
<%= p.input :content, required: true%> <br />
<%= p.input :category_id, input_html: { required: true }%>
<%= p.submit %>
<% end %>
See how I used all the three ways of getting required to true and the usual way of creating a text field of the form_for so I can see if I find a solution. No success. Even after making config.browser_validations = true in config/initializers/simple_form.rb. Why is it working for form_for but not when I am using gems? I also tried Formtastic and had the same issue.
If you place required: true in the input you should see the field has the "required" class and required="required" attribute.

Don't allow user to submit a form with empty fields in ruby on rails

I am starting use Ruby on Rails and I am having a little problem. I have a form with 3 fields, this is the code:
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div class="field">
<%= f.text_field :name, autofocus: true, placeholder: "Name" %>
</div>
<div class="field">
<%= f.email_field :email, autofocus: true, placeholder: "Email" %>
</div>
<div class="field">
<%= f.number_field :age, autofocus: true, placeholder: "Age" %>
</div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
In the email field when you write something that is not an email and try to submit, the browser (chrome or firefox ) display an error saying that the field must content an #. The same happen with the age field, if a letter is entered the browser show an error saying that the field only accept numbers.
I wanna know how to make that the browser show a message when any field is empty when you try to submit. I know how to do it in cakephp so I guess it can be done here in ruby too. I already validate the fields in the model, setting the presence in true but that only works for show a message after you submit and the page reload again.
When you use something like:
f.email_field
It is generating an HTML5 input element that tells the browser it has to be a valid email. HTML 5 also has a required='required' option that can be used to prevent blank fields.
You can add it like this:
<div class="field">
<%= f.email_field :email, autofocus: true, placeholder: "Email", :required => 'required' %>
</div>
This will add required='required' to your form element. Note that in HTML5 you only need the word required in your form element, but the only way I know to add it in Rails is to use the option form I'm showing you here.
This will prevent submitting the form without that field. This works for current versions of Firefox, Chrome, Opera, and IE11. Safari will prevent the submission but doesn't indicate why. It just does nothing.
I would check this out: http://blueashes.com/2013/web-development/html5-form-validation-fallback/
You can set the HTML required attribute to true. Just add required: true to each field.
Here's what your new form will look like:
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div class="field">
<%= f.text_field :name, required: true, autofocus: true, placeholder: "Name" %>
</div>
<div class="field">
<%= f.email_field :email, required: true, autofocus: true, placeholder: "Email" %>
</div>
<div class="field">
<%= f.number_field :age, required: true, autofocus: true, placeholder: "Age" %>
</div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
Your case is pretty custom, that's why it looks pretty easy, but what you're really trying to achieve here is called 'client-side validation'.
To be really portable and user-friendly it has to be done in JavaScript. Basically this will be a script that validates the fields and outputs the corresponding error messages to the user, preventing form submission at the same time. This is almost the same that Rails does on the server side when you submit the form.
Once the problem is defined, you can approach it in one of the following ways:
Stay with Rails. Rails is initially designed to handle form validation on the server side. You can just accept the way it is, and it will yield the cleanest, shortest and the most semantic code possible. For it to be more seamless you can easily pull in some AJAX for it, which should be easy (http://guides.rubyonrails.org/working_with_javascript_in_rails.html). To user it'll look like nothing ever got submitted.
Write some custom JS yourself to handle those validations. Either on your own, or with the aid of libraries like http://jqueryvalidation.org/. This is going to be a mess, since you'll basically have to duplicate Rails server-side validation code on the client-side in a different language. And keep it in sync.
Use one of the helper libraries for Rails. E.g. https://github.com/joecorcoran/judge looks promising, but there are others to be Googled. These guys exercise the same idea: you've got server-side validations and they should be easily usable on the client-side. Certain libraries generate JavaScript automatically, others just send the form to be validated to the server behind the scenes.
If I were you, I would choose the 1st way + AJAX. Other ways would make simple matters unnecessarily complex, and instead of writing useful stuff you'll most certainly have to dive into debugging obscure JS and cryptic meta-programmed Ruby/Rails libraries.
Hope that helps!
HTML 5 has required=true option that can be used to prevent form submission with empty fields. In rails form helpers, you can use it like
<%= f.text_field :first_name, required: true %>
<%= f.email_field :email, required: true %>

text_field with default value can not save to db in rails

I want to save the text_field to database with defaut value ,but it's not work.
<p>
<%= f.label :用户id %><br>
<%= f.text_field :user_id ,:value => "#{current_user.try :id}", disabled: true %>
</p>
<p>
<%= f.label :用户昵称 %><br>
<% user = User.find current_user.id%>
<%= f.text_field :name ,:value => user.name , disabled: true%>
</p>
Change disabled: true to readonly: true if you want the field to be un-editable but still submit a value.
"READONLY and DISABLED both remove the functionality of the input field, but to different degrees. READONLY locks the field: the user cannot change the value. DISABLED does the same thing but takes it further: the user cannot use the field in any way, not to highlight the text for copying, not to select the checkbox, not to submit the form. In fact, a disabled field is not even sent if the form is submitted."
Reference:
http://www.htmlcodetutorial.com/forms/_INPUT_DISABLED.html
http://www.w3.org/TR/html4/interact/forms.html#h-17.12
Also see this answer: https://stackoverflow.com/a/7730719/2113461

Resources