Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ROR pass params to modal

I'm trying to open a modal that displays a list of items. The list of items is already available in the view as a variable. How do I pass this variable to the modal?

Below is roughly how the main view looks like:

View.html.erb

<div>
  <%= @users.each do |user|%>
    <h1>user.name</h1>
    <h2>user.email</h2>
    <%= link_to remote: true, 'data-toggle' => 'modal', 'data-target' => '#taskModal do %>           
      <i><%= user.tasks.count%></i>
    <% end %>
  <% end %>
</div>

<div class="modal" id="taskModal" aria-hidden="true">
...
<%= render partial: 'list_modal' %>

list_modal is a partial with the structure of the modal.

like image 652
sotn Avatar asked Jan 20 '16 03:01

sotn


2 Answers

As opposed to having the list of items already on the view, and wanting to pass it to the modal, One thing you can do is make the button ( or link ) for opening the modal to call a controller action by ajax, and then let the action respond to JS, where you will now use the corresponding view.js file to both populate the modal as well as programmatically render it ( after populating it ).

Example:

Link to open modal:

<%= link_to "Open users list", users_open_list_modal_path, remote: true %>

Users open list modal controller action:

def open_list_modal
  @user_list = User.all
  respond_to do |format|
    format.js
  end
end

open_list_modal.js.erb:

//populate modal
$('#modal').html('#{ escape_javascript(<%= render partial: 'user_list', locals: {user_list: @user_list} %> )}');

//render modal
$('#modal').openModal();

And then on the modal itself, you can now have access to the user_list (NOT @user_list) list.

Note: In this example, I made use of both erb, js, and material-modal. If you are using something different from these ( maybe slim, haml, coffee, bootstrap...), you will have to suite the example to your case.

Hope this helps.

like image 163
x6iae Avatar answered Nov 06 '22 11:11

x6iae


you can just directly pass it to modal. here what i did thou, on my view i have a button that trigger my modal and then i created a partial (to DRY up my code) _modal.html.erband called that partial after my button.

<button type="button" class="btn btn-default" data-toggle="modal" data-target="#modal"></button

<%= render 'modal' %>

make sure your modal has id <div class="modal fade" id="modal" tabindex="-1" role="dialog">...

gl mate!

like image 37
mrvncaragay Avatar answered Nov 06 '22 11:11

mrvncaragay