Module: VanillaNested::ViewHelpers

Defined in:
lib/vanilla_nested/view_helpers.rb

Instance Method Summary collapse

Instance Method Details



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/vanilla_nested/view_helpers.rb', line 17

def link_to_add_nested(form, association, container_selector, link_text: nil, link_classes: '', insert_method: :append, partial: nil, partial_form_variable: :form, partial_locals: {}, tag: 'a', tag_attributes: {}, &link_content)
  association_class = form.object.class.reflections[association.to_s].klass
  object = association_class.new

  partial_name = partial || "#{association_class.name.underscore}_fields"

  html = capture do
    form.fields_for association, object, child_index: '_idx_placeholder_' do |ff|
      render partial: partial_name, locals: { partial_form_variable => ff }.merge(partial_locals)
    end
  end

  method_for_insert = i[append prepend].include?(insert_method.to_sym) ? insert_method : :append

  classes = "vanilla-nested-add #{link_classes}"
  data = {
    'container-selector': container_selector,
    'html': html,
    'method-for-insert': method_for_insert
  }

  nested_options = form.object.class.nested_attributes_options[association.to_sym]
  data['limit'] = nested_options[:limit] if nested_options[:limit]

  attributes = tag_attributes
  attributes[:class] = "#{attributes.fetch(:class, '')} #{classes}"
  attributes[:data] = attributes.fetch(:data, {}).merge(data)

  (tag, attributes) do
    if block_given?
      yield link_content
    else
      link_text || "Add #{association_class.model_name}"
    end
  end
end


65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/vanilla_nested/view_helpers.rb', line 65

def link_to_remove_nested(form, link_text: 'X', fields_wrapper_selector: nil, undo_link_timeout: nil, undo_link_text: 'Undo', undo_link_classes: '', link_classes: '', tag: 'a', tag_attributes: {}, &link_content)
  data = {
    'fields-wrapper-selector': fields_wrapper_selector,
    'undo-timeout': undo_link_timeout,
    'undo-text': undo_link_text,
    'undo-link-classes': undo_link_classes
  }

  classes = "vanilla-nested-remove #{link_classes}"

  attributes = tag_attributes
  attributes[:class] = "#{attributes.fetch(:class, '')} #{classes}"
  attributes[:data] = attributes.fetch(:data, {}).merge(data)

  capture do
    concat form.hidden_field(:_destroy, value: 0)
    concat(
      (tag, attributes) do
        if block_given?
          yield link_content
        else
          link_text.html_safe
        end
      end
    )
  end
end