使用纯 JavaScript 实现 Rails 动态嵌套表单
Rails dynamic nested forms using vanilla JS
Similar to cocoon, but with no jquery dependency!
Example:
Just add it to your gemfile
gem 'vanilla_nested'
# or, to use latest code from git:
gem 'vanilla_nested', github: 'arielj/vanilla-nested', branch: :mainRequire the js:
//= require vanilla_nestedAdd the package too (gem is required for the helper methods) using:
yarn add vanilla-nested
# or, to use latest code from git:
yarn add arielj/vanilla-nestedAnd then use it in your application.js as:
import "vanilla-nested";Add the importmap config:
pin "vanilla-nested", to: "vanilla_nested.js", preload: trueAnd then use it in your application.js as:
import "vanilla-nested";To update the gem use either:
gem update vanilla_nested # if using the gem from RubyGems
# or
gem update --source vanilla_nested # if using the gem from githubIf using webpacker, you need to update the node package too with:
yarn upgrade vanilla-nestedYou can clear the webpacker cache just in case if changes are not reflecting with
rails webpacker:clobber
# models/order.rb
class Order
Note that:
link_to_remove_nested receives the nested form as a parameter, it adds a hidden [_destroy] fieldlink_to_add_nested expects the form builder, the name of the association and the selector of the container where the gem will insert the new fieldsThe default value is Add , but it can be changed using the parameter link_text:
link_to_add_nested(form, :order_items, '#order-items', link_text: I18n.t(:some_key))This way you can, for example, internationalize the text.
By default, the link to add new fields has the class vanilla-nested-add which is required, but you can add more classes passing a string:
link_to_add_nested(form, :order_items, '#order-items', link_classes: 'btn btn-primary')This way you can style the link with no need of targeting the specific vanilla nested class.
By default, new fields are appended to the container, you can change that with the insert_method option. For now, only :append and :prepend are supported:
link_to_add_nested(form, :order_items, '#order-items', insert_method: :prepend)The default partial's name is inferred using the association's class name. If your Order has_many :order_items and the class of those items is OrderItem, then the inferred name is order_item_fields. You can use any partial name you like, though:
link_to_add_nested(form, :order_items, '#order-items', partial: 'my_partial')link_to_add_nested needs to render an empty template in order to later append/prepend it. To do that, it passes the form as a local variable. If your partial uses form, you don't have to do anything, but if you using another variable name, just customize it here.
# orders/_order_item_fields.html.erb
link_to_add_nested(form, :order_items, '#order-items', partial_form_variable: :ff)You can also pass more local variables to the partial by setting the partial_locals value.
link_to_add_nested(form, :order_items, '#order-items', partial_locals: { key: 'value' })The HTML tag that will be generated. An `` tag by default.
link_to_add_nested(form, :order_items, '#order-items', tag: 'span')HTML attributes to set for the generated HTML tag. It's a has with key value pairs user for the content_tag call, so it support any attribute/value pair supported by content_tag
link_to_add_nested(form, :order_items, '#order-items', link_text: '+', tag_attributes: {title: "Add Order"})
# +class attributes are appended to the vanilla-nested-add class and the custom classes specified with the link_classes argument.
link_to_add_nested(form, :order_items, '#order-items', link_text: '+', tag_attributes: {class: "some-class"}, link_classes: 'another-class')
# +If you need html content, you can use a block:
The default value is "X", but it can be changed using the parameter link_text:
link_to_remove_nested(form, link_text: "remove")If you need html content, you can use a block:
By default, the link to remove fields has the class vanilla-nested-remove which is required, but you can add more classes passing a space separated string:
link_to_remove_nested(form, link_classes: 'btn btn-primary')This way you can style the link with no need of targeting the specific vanilla nested class.
By default, the link to remove the fields assumes it's a direct child of the wrapper of the fields. You can customize this if you can't make it a direct child.
# orders/_order_item_fields.html.erb
Note that:
closest() method, so it looks on the ancestors.closest(), there is no IE supported (https://caniuse.com/#search=closest). You may want to add a polyfill or define the method manually if you need to support it.The HTML tag that will be generated. An `` tag by default.
link_to_remove_nested(ff, tag: 'p')HTML attributes to set for the generated HTML tag. It's a has with key value pairs user for the content_tag call, so it support any attribute/value pair supported by content_tag
link_to_remove_nested(ff, link_text: 'X', tag_attributes: {title: "Delete!"})
# Xclass attributes are appended to the vanilla-nested-remove class and the custom classes specified with the link_classes argument, just like the link_to_add_nested helper.
You can tell the plugin to add an "undo" link right after removing the fields (as a direct child of the fields wrapper! this is not customizable!).
link_to_remove_nested(ff, undo_link_timeout: 2000, undo_link_text: I18n.t('undo_remove_fields'), undo_link_classes: 'btn btn-secondary')Options are:
undo_link_timeout: milliseconds, greater than 0 to turn the feature on, default: nilundo_link_text: string with the text of the link, great for internationalization, default: 'Undo'undo_link_classes: space separated string, default: ''There are some events that you can listen to add custom callbacks on different moments. All events bubbles up the dom, so you can listen for them on any ancestor.
Triggered right after the fields wrapper was inserted on the container.
document.addEventListener('vanilla-nested:fields-added', function(e){
// e.type == 'vanilla-nested:fields-added'
// e.target == container div of the fields
// e.detail.triggeredBy == the "add" link
// e.detail.added == the fields wrapper just inserted
})Triggered right after the fields wrapper was inserted on the container if the current count is >= limit, where limit is the value configured on the model: accepts_nested_attributes_for :assoc, limit: 5. You can listen to this event to disable the "add" link for example, or to show a warning.
document.addEventListener('vanilla-nested:fields-limit-reached', function(e){
// e.type == 'vanilla-nested:fields-added'
// e.target == container div of the fields
// e.detail.triggeredBy == the "add" link
})Triggered when the fields wrapper if fully hidden (aka ""removed""), that is: after clicking the "remove" link with no timeout OR after the timeout finished.
document.addEventListener('vanilla-nested:fields-removed', function(e){
// e.type == 'vanilla-nested:fields-removed'
// e.target == fields wrapper ""removed""
// e.detail.triggeredBy == the "remove" link if no undo action, the 'undo' link if it was triggered by the timeout })Triggered when the fields wrapper if hidden with an undo option.
document.addEventListener('vanilla-nested:fields-hidden', function(e){
// e.type == 'vanilla-nested:fields-hidden'
// e.target == fields wrapper hidden
// e.detail.triggeredBy == the "remove" link
})Remove vs Hidden
Behind the scene, the wrapper is never actually removed, because we need to send the
[_destroy]parameter. But there are 2 different stages when removing it.
- If there's no "undo" action configured, the wrapped is set to
display: noneand considered "removed".- If you use the "undo" feature, first the children of the wrapper are hidden (triggering the
hiddenevent) and then, after the timeout passes, the wrapper is set todisplay: none(triggering theremovedevent).
Triggered when the user undo the removal using the "undo" link.
document.addEventListener('vanilla-nested:fields-hidden-undo', function(e){
// e.type == 'vanilla-nested:fields-hidden-undo'
// e.target == fields wrapper unhidden
// e.detail.triggeredBy == the "undo" link
})You can run the tests following these commands:
If you make changes in the JS files, you have to tell yarn to refresh the code inside the node_modules folder running
./bin/update-gem(oryarn upgrade vanilla-nestedandrails webpacker:clobber), and then restart the rails server or re-run the tests.
Before, it used SomeClass.name.downcase, this created a problem for classes with more than one word:
Now it uses SomeClass.name.underscore:
If you used the old version, you'll need to change the partial name or provide the old name as the partial: argument.
Mostly single/double quotes, spacing, etc.
Just so Solargraph plugins on editors like VS-Code can give you some documentation.
Mostly on the javascript code
So it can be used as a node module using yarn to integrate it using webpacker.
accepts_nested_attributes_forYou can listen to the vanilla-nested:fields-limit-reached event that will fire when container has more or equals the amount of children than the limit option set on the accepts_nested_attributes_for configuration.
If you were using webpacker, remember to replace the vanilla_nested.js file in your app/javascript folder
You can set multiple classes for the "X" link
You can pass a bl
暂无开放 Issues,或尚未同步最近议题。