Cocoon add association, how to limit number of associations

佐手、 提交于 2019-11-29 07:21:35

I would use javascript for this. You can bind to an event that is triggered upon insert of a new item: on this event count how many items there are, and hide the link if needed.

Likewise, when loading the page do the same.

So in code that would look like:

 $(function() {
   function check_to_hide_or_show_add_link() {
     if ($('#colours .nested-fields:visible').length == 5) {
       $('#colours .links a').hide();
     } else {
       $('#colours .links a').show();
     }
   }

   $('#colours').on('cocoon:after-insert', function() {
     check_to_hide_or_show_add_link();
   });

   $('#colours').on('cocoon:after-remove', function() {
     check_to_hide_or_show_add_link();
   });

   check_to_hide_or_show_add_link();     
 });

Something like this should work. Note this code is not tested :)

Hope this helps.

Andrei

I had a similar task to do and what I ended up doing was putting an onclick event on the "Add" link. This onclick event will execute before the code to add the fields is executed.

In your case, the code would look something like the following:

= link_to_add_association 'add colour', c, :colours, class: 'add-colour-link'

Then in your JavaScript (CoffeeScript in this case):

$('.add-colour-link').on 'click', (e) ->
   if $('#colours .nested-fields:visible').size() < 5
     return true #continue the execution 
   else
     #maybe display the modal to the user that only a maximum of 5 is allowed
     return false #prevent further execution
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!