temkin
temkin

Reputation: 355

Rails 4 - how to trigger Object edit form without refreshing the page

Hi and thanks for looking into this.

I have a list of objects displayed on my page. Now when a user selects one of the objects, I'd like to show Edit form for this object without refreshing the page and allow user to update it. I already have a form partial with :remote tag. What I cannot figure out is how to trigger this Edit form and pass the correct object into it.

Thanks in advance!

Upvotes: 1

Views: 226

Answers (2)

Baldrick
Baldrick

Reputation: 24340

You can include the form partial for each item in an hidden div, and show the div with javascript only when needed :

<% @items.each do |item| %>
  <div>
    <%= item.label %>
    <a href="#" class="editLink">Edit</a>
    <div class="editFormWrapper">
      <%= render '_form', locals: {item: item} %>
    </div>
  </div>
<% end %>

css:

.editFormWrapper {
  display: none;
}

javascript (with jquery)

$(document).ready(function() {
  $('.editLink').on('click', function() {
    $(this).siblings('editFormWrapper').show();  // or .slideDown(); or any other effect
  });
});

If the page contains a lot of items, or if the hidden form is big, it may be better to use Ajax to request and include the edit form "on demand", to keep the weight of the page to minimum.

Upvotes: 1

Faberge eggs
Faberge eggs

Reputation: 141

When you render page with objects, you can render objects array in javascript variable

<script>
OBJ_ARR = {
  *obj_id1* = {
    name: 'test1',
    desc: 'test test'
  },
  *obj_id2* = {
    name: 'test2',
    desc: 'test2 test'
  },
  ......
}
</scpipt>

Next we use javascript scenario When object clicked you get certain object_id, and then you get appropriate object from our array

OBJ_ARR[object_id]

So, we put object properties to form and display that form

Upvotes: 0

Related Questions