add index to nested forms
Hi guys.
currently struggling to retrieve child index reference in nested forms.
I have my main form:
<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put, class: 'form-horizontal' }) do |f| %>
<%= render 'shared/devise_errors' %>
<div id="profiles">
<%= f.fields_for :profiles do |profile_form| %>
<%= render 'profile_fields', f: profile_form%>
<%end%>
</div>
<div class="actions">
<%= f.submit "Enregistrer", class: "btn btn-primary float-right" %>
</div>
<% end %>
and sub form _profile_fields.html.erb:
<div class="card text-justify" >
<div class="card-header">
<h4 class="card-title">
<%indexi = f.options[:child_index].to_i+1 %>
<%index= indexi.to_s %>
<div class="form-group row">
<%= f.label :label, class:'info col-md-4 col-form-label'%>
<div class="input-group col-md-8">
<%= f.text_field :label, class: "form-control", placeholder: "Profile #{index}",:value:(f.object.label || "Profile #{index}") %>
(...)
this index is stuck to same figure when I add some new profile forms (child of user).
I probaby have to refactor but unclear how. seems to me that many have experienced a similar issue in the past. answers not really clear. is there anything missing in rails to be able to do this in an easy way?
thks Jack.
I changed it for:
<%= render partial:'profile_fields', locals: {f: profile_form, i: profile_form.index}%>
but receiving a
undefined local variable or method `i' for #<#Class:0x,...
for my subform line:
<%= f.text_field :label, class: "form-control", placeholder: "Profile #{i}" %>
presumably profile_form.index is not defined ?
Seems strange to me. In the meantime, I found a workaround using CSS.
this is the top of my sub-form:
<section><%= f.label :label, class:'info col-md-4 col-form-label'%></section>
and this is the CSS added:
body {
counter-reset: section;
}
section {
counter-increment: section;
white-space: nowrap;
overflow: hidden;
}
section label:after {
content: ' ' counter(section);
}