Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to show modal window in controller's action?

So I've got controller PagesController with actions index and full_search. Action index is for home page. On home page I've got the button 'search' and text_field. If user types sometiong in text_field and clicks on button 'search' he/she goes to action full_search. In this action I try to find something by user's query. if I don't find anything I should just show a modal window with 'no results' otherwise redirect to another page

def full_search
  ...do search...
  if search_result.empty?
    show modal window with text 'no results'
  else
    redirect to another page
  end
end

How can I show modal window(like function alert in js)? I think I have to use javascript..but where???

if search_result is empty I don't need to render any view...I just need to stay at the same page and show modal window

like image 987
Vitalii Paprotskyi Avatar asked Mar 12 '23 00:03

Vitalii Paprotskyi


2 Answers

Step 1.

In your rendered view, have a div with id "my_modal_content" where will insert the modal's content and show the modal.

Step 2.

Render a js.erb file which will append the modal to our page

#your rails controller method
def my_method
  if something == true
    respond_to do |format|

      format.js { render :partial => 'somewhere/somefile.js.erb' }
      #I'm assuming its js request
    end
  else
    redirect to another page
  end
end

Step 4.

Write your js.erb file like this, which appends modal and then shows it.

#_somefile.js.erb file

$("#my_modal_content").html("<%= escape_javascript(render 'somewhere/my_modal') %>");
$("#myModal").modal('show');

Step 3.

Modal partial file _my_modal.html.erb placed within views/somewhere/ with you modal content ready.

<div class="modal fade" tabindex="-1" id="myModal" role="dialog">
  <div class="modal-dialog">
    ...<!-- all your content insdie -->
  </div>
</div>

Update

If you want to show an alert, its pretty straight forward. You just render js

if search_result.empty?
  message = "No result found. Try something else!"
  respond_to do |format| 
    format.js { render js: "alert(#{message});" }
  end
else
  redirect to another page
end
like image 132
Kumar Avatar answered Mar 15 '23 01:03

Kumar


You can save a variable with true or false in your controller: @var = true

And then in a view use javascript:

if (<%= @var%> == true) {
  alert("some text");
}
like image 22
Nadiya Avatar answered Mar 15 '23 00:03

Nadiya