Home > Mobile >  How to get a value from a simple_form in the same view in Rails
How to get a value from a simple_form in the same view in Rails

Time:08-16

I need to get a value from a f.association in a form of simple_form. This gets its value from a controller and transfers all the rooms, I need the value to load a bootstrap 5 modal that I need to reload the information of the selected room.

The modal works, but I need to occupy the set_parms, to get the data.

Can you give me ideas or how to do it?

This is my existing code:

Form

<%= simple_form_for [@reservation, @item_reservation] do |f| %>
  <%= f.association :room, collection: @room.map{|r| [r.name, r.id]} %>
  <%= f.submit "Add" %>
  <button type="button"  data-bs-toggle="modal" data-bs-target="#exampleModal">
  Launch demo modal
</button>
  <%= link_to "Back", client_reservations_path(@reservation.client_id) %>
<% end %>

View

<h1>ItemReservations#new</h1>
<p>Find me in app/views/item_reservations/new.html.erb</p>
<td><%= link_to "Follow", new_reservation_user_reservation_path(@reservation)%> </td>

<%=render "form", item_reservation: @item_reservation %>
<%= link_to "Back", client_reservations_path(@reservation.client_id) %>
<!-- Modal -->
<div  id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div >
    <div >
      <div >
        <h5  id="exampleModalLabel">Modal title</h5>
        <button type="button"  data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div >
        ...
      </div>
      <div >
        <button type="button"  data-bs-dismiss="modal">Close</button>
        <button type="button" >Save changes</button>
      </div>
    </div>
  </div>
</div>

<br/>
<h2>Rooms</h2>
<div >
  <small><%= @message %></small>
</div>
<br/>
<table id="Room_select" >
  
  <head>

CodePudding user response:

Assumption:

-- you have done:

  1. Page loads with reservation form
  2. User selects a room from the select field
  3. User clicks "Launch demo modal" button

-- you need to do:

  1. Room data should be added to the modal
  2. The modal should open

If this is all correct, you have a few options:

  1. Rails 7 comes with Hotwire for situations just like this

  2. Use Rails AJAX and UJS for older versions of Rails, or if you don't want to learn Turbo and Hotwire.

  3. Use Javascript and AJAX without Rails


With any of these options, you are essentially going to:

  1. Get the currently selected option from the select field
  2. Send that option to a custom Rails controller (e.g. RoomsController#modal_show) remotely (using AJAX or Turbo (Hotwire))
  3. The controller will load the room data and send back some Javascript to execute (or HTML to render in the case of Hotwire)
  4. The returned Javascript will put the room data into the modal and trigger the modal to open
  • Related