Jay Killeen
Jay Killeen

Reputation: 2922

How do I add autofocus to a form field if it is the edit form?

I am new to ruby on rails and working through the Rails Tutorial book and also Rails Programming from pragmatic studio. However for my project I need to find solutions now so sad I can't spend more time on the researching.

My question is, once I am able to add, show and edit forms I am being instructed to create partials, ie _forms.html.erb and then rendering those forms on the edit, show and new pages.

On my _forms.html.erb partial, how can I implement some flow using if statements based on the page that the form is being rendered for.

For example, when _form.html.erb is being rendered for the show page I want certain form_for labels/fields to be set to readonly: true. At the bottom of the form I want submit, edit, change buttons based on the page aswell.

So far I am trying to use the parems[:action] == "new" or "edit" etc to implement the control flow as follows:

Old code under the edit.html.erb file:

      <%= f.label :patform_type %>
      <%= f.text_field :patform_type,autofocus: true %>

New code under the _form.html.erb file:

      <%= f.label :patform_type %>
      <%= f.text_field :patform_type %>
        <% if params[:action] == "new" %>
          <%= ,autofocus: true %>
        <% end %>

My original code has been influenced by these posts: Rails not editable text field How to disable all form_for input fields in Ruby on Rails app?

Once I get this right then I am hoping I can use it to wrap it around other elements like the submit, edit buttons etc or other fields.

Also if someone knows a better way can you please let me know as I don't know what I don't know.

Thanks for any assistance/ideas you can provide.

Upvotes: 1

Views: 1260

Answers (1)

Sherwyn Goh
Sherwyn Goh

Reputation: 1352

You probably have to stick with a bunch of if/else statements if you need such depth of logic within the form, but I would recommend having the forms typed into their respective erb file, and not be rendered from a partial with a ton of logic.

A partial is meant for repeated code, and your code is not exactly what I would describe as repeatable. It is also not immediately understandable and will contain code that is essentially a waste of time to read:

For example, if I am reading the edit action's view and I see:

if params[:action] == "new"

It will be testing for an action that isn't even relevant to the current view, unlike logic such as:

if current_user.admin?

which will be more suitable for partial-based logic.

Hope that helps, enjoy RoR

Upvotes: 2

Related Questions