vanilla-nested
vanilla-nested copied to clipboard
Opening form with multiple empty child records and duplicate values from
What is the proper way to preload some empty vanilla-nested rows in a form?
Right now, I'm simply calling he .click() method on button.vanilla-nested-add. I call it 3 times in a row to get three empty records as a default layout for my form. Unfortunately, my input elements often get duplicate names.
Using document.querySelector("button.vanilla-nested-add").click();
<div id="calc-alt">
<%= link_to_add_nested(f, :calc_alternatives, '#calc-alt') %>
<!-- pre-populate form with 3 blank rows -->
<script>
document.addEventListener('turbo:load', function() {
document.querySelector("button.vanilla-nested-add").click();
document.querySelector("button.vanilla-nested-add").click();
document.querySelector("button.vanilla-nested-add").click();
});
</script>
</div>
I think the issue with my way of doing this, is in vanilla_nested.js, I think Date.now() is used to help dynamically rename the input fields, but when I call this function three times in a row, Date.now often returns the same value. I also tried to substitute performance.now() instead of Date.now, but I still get duplicates sometimes.
https://github.com/arielj/vanilla-nested/blob/cab8f390dc99eed933952f6fcc14603bad30c6a8/app/assets/javascripts/vanilla_nested.js#L10C1-L10C73
Test for duplicate with Date.now via: https://jsfiddle.net/2rfuzvbj/
Compare Date.now with performance.now via: https://jsbench.me/hploqs196b/
I'm probably doing it completely wrong... So if you have any tips on how to get multiple empty rows to load as the form loads please let me know!
@erwin, what is the context of your request?
when you are clicking document.querySelector("button.vanilla-nested-add").click(); at the turbo:load time, it means you only need to "preload" the nested attributes when first loading the page?
I'm not super familiar with the gem but to me, the Rails way to load nested attributes is at the controller side, like so:
class User
has_many :items
end
class Item
belong_to :user
end
class UsersController < ApplicationController
def new
@user.new(items: [Item.new, Item.new, Item.new])
end
end
then in the frontend you should be loading the nested attributes somehow pass the @user.items or if you assigned them in a variable just pass the @items into it.
Does that make sense to you?
@JuanVqz thank you very much. I had completely missed that somehow.
I updated my controller to use logic like you suggest:
@user.new(items: [Item.new, Item.new, Item.new])
And then updated my _form view to use <%= form_with model: @article do |form| %> and it all works great!
https://guides.rubyonrails.org/form_helpers.html#dealing-with-model-objects
Thanks so much!
nice to know it worked for you @erwin!
If you are happy with the result, can you please close the issue?
thanks @JuanVqz! that is the intended way, yes