nested_form_fields icon indicating copy to clipboard operation
nested_form_fields copied to clipboard

Limit add link

Open Awatatah opened this issue 9 years ago • 4 comments

is there a way to limit f.add_nested_fields_link to a number? Meaning, let's say someone clicks the f.add_nested_fields_link link, I only want the person to add 1 nested object. How can I make the link not be shown after clicked x amount of times?

Awatatah avatar Jul 05 '16 21:07 Awatatah

You can use the fields_added and fields_removed events for this. Just hide the link when there are x nested forms on the page and show when there are x-1 nested forms. Alternatively, you can also use the click event of the add_nested_fields_link. Just make sure when you count the nested forms you only count the visible forms because when you remove a nested form, it is only hidden, not removed, until the form is submitted.

ncri avatar Jul 06 '16 16:07 ncri

Great gem!

Can you elaborate on how either of those solutions could be performed? I've got multiple nested forms on one page, and I'd like to limit the number of nested_fields that can be created for each of them.

I see the CoffeeScript samples in the Readme, but I'm having a hard time connecting those with what would need to happen in this situation.

Thanks!

jeremysenn avatar Dec 07 '16 21:12 jeremysenn

You can roughly do something like this for example:

$your_container.on 'click', '.add_nested_fields_link', ->
  if $your_container.find('.some_class_in_your_nested_fields:visible').length == max_items - 1
    $(this).hide()
  true

$your_container.on 'click', '.remove_nested_fields_link', ->
  if $your_container.find('.some_class_in_your_nested_fields:visible').length == max_items
      $your_container.find('.add_nested_fields_link').show()
  true

ncri avatar Dec 08 '16 07:12 ncri

Great! Thank you very much for the help!

jeremysenn avatar Dec 09 '16 15:12 jeremysenn