Skip to content

Refreshing Input fields

Nathan Watson edited this page Mar 12, 2018 · 14 revisions

Overview

When filling out a form, there are often selection input fields containing items from another model. A selection can become stale, in which case it should be refreshed in order to allow the user to continue without having to retype all form inputs due to a manual, full-page refresh.

Why might the selection items become stale? As an example, the Biosample model links to the Donor model and the donor is a required input field. When entering a new biosample, the user will need to select the right donor. If the donor that is needed doesn't appear in the donor selection list, then the user will need to open a new tab, go to the Donors page, and add a new donor record. Then, the user can switch back to the other tab, and in order for the new donor to appear in the donor selection list, we can add some logic to allow the user to refresh this selection list.

How Pulsar implements refreshing an input field

If you guessed AJAX, then you'd be correct. A refresh icon is added right after any label tag that has the class "refresh". This icon tag of the label will also have the class "refresh", and this all happens in application.js:

$("label.refresh").after('<i class="refresh fa fa-refresh"></i>')

The tedious part though is that a custom click handler needs to be registered with each refresh icon. Extending the example above regarding a user interacting with the form for filling out a new biosample, the donor selection input looks like this:

<%= f.association :donor,
   collection: Donor.order(:name),
   label_method: :name,
   prompt: "Choose The Donor",
   label_html: {
       class: "refresh",
       "data-toggle": "tooltip",
       "title": "The donor of the biosample"
   }
%>

The important part in this stub is the addition of the "refresh" class to the label.

The next important task is to add the click handler. I did this in the biosamples.js.coffee file as follows:

#Refresh the donors list in the form when the refresh fa-icon is clicked:
  $(document).on "click", "i.refresh", (event) ->
    $.get "/donors/select_options", (responseText,status,jqXHR) ->
      $(".biosample_donor select").html(responseText)