Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get nested form field id number from cocoon

I am trying to get the following result:

<input class="file required" id="page_media_attributes_1367414416272_image" multiple="multiple" name="page[media_attributes][1367414416272][image]" type="file">

Is there any dynamic tag I can add to this:

<div class='span3'> 
  <%= f.input :image, as: :file, :input_html => { :multiple => true, :name => 'page[media_attributes][Something dynamic][image]' } %>
  <%= f.input :name %>

  <%= link_to_remove_association "remove image", f %>
</div>

That would insert the number 1367414416272 instead of [Something dynamic] to get the html above?

The number is different every time, and I believe it is generated by Cocoon since these fields are added dynamically by cocoon.

like image 912
Ole Henrik Skogstrøm Avatar asked Sep 05 '25 03:09

Ole Henrik Skogstrøm


1 Answers

Yes, the numbers are automatically generated by Cocoon. From the "add new" javascript function of cocoon:

new_id = new Date().getTime() + cocoon_element_counter++

I think you have to use javascript too in order to find all "cocoon" elements and parse their id attribute to get the random number and then change their name accordingly.

Draft:

$(document).ready(function(){
    $('input[id^="page_media_attributes_"][id$="_image"]').each(function(){
        var current = $(this);
        var rx = /page_media_attributes_(.*)_image/;
        num = rx.exec(current.attr('id'))[1];
        current.attr('name','page[media_attributes][' + num + '][image]');
    });
});

Of course, this has to be executed on each new dynamically generated element.

So if you go this way, you have to "functionalize" the code above and call it once after document loads for every specific selector you want, and then explicitly for each dynamically added element by cocoon (according to the documentation, special events are fired upon additions/removals).

like image 140
Lazarus Lazaridis Avatar answered Sep 07 '25 18:09

Lazarus Lazaridis