FIX duplicate id setup_collection_buttons on base.js #1211

Closed
wants to merge 2 commits into
from

Projects

None yet

4 participants

@rc2c
rc2c commented Mar 7, 2013

FIX duplicate id of an embedForm when removing and adding multiple field.

@rande rande commented on the diff Mar 27, 2013
Resources/public/base.js
jQuery(proto).insertBefore(jQuery(this).parent());
jQuery(this).trigger('sonata-collection-item-added');
+ index++;
@rande
rande Mar 27, 2013 Sonata Project member

Why index++ ?

@rande rande commented on the diff Mar 27, 2013
Resources/public/base.js
@@ -159,15 +159,25 @@ var Admin = {
var proto = container.attr('data-prototype');
// Set field id
var idRegexp = new RegExp(container.attr('id')+'___name__','g');
- proto = proto.replace(idRegexp, container.attr('id')+'_'+(container.children().length - 1));
-
+ // force index to 0
+ var index = 0;
+ // if nb child > 0 get dynamically the last id
+ if(container.children().length - 1 > 0)
+ {
+ var last_div = container.find('.sonata-collection-row:last >:first-child');
+ var id_parts = last_div.attr('id').split('_');
+ index = parseInt(id_parts[id_parts.length-1])+1;
@rande
rande Mar 27, 2013 Sonata Project member

You should add the base in parseInt

@rande
Member
rande commented Mar 27, 2013

Can you explain how to reproduce the issue ?

@rande rande closed this Jan 15, 2014
@jsampedro77

I have faced a similar problem when using 'collection' with a doctrine array field. The problem is caused because the entity getter receives a named array as a value, instead of an array. So the origin of the problem has not to do with Sonata.

I.E I have a field named $locales mapped as a Doctrine2 array type. It stores the locales a user can handle.

The form Admin section looks like this:

           $formMapper ->add('locales', 'collection', array(
                'type' => 'locale',
                'prototype_name' => '_locales_',
                'options' => array(
                    'label' => false,
                ),
                'allow_add' => true,
                'allow_delete' => true
            ))

Then, one the value is set, instead of getting an array like array('es', 'en') , it gets array(0 => 'es', 1=>'en'). So the next time that value is used, the collection will be created with an explicit id. The problem arises when any item, but the last one, is removed from the collection. This causes that the base.js script index calculation based on counting existing items, gets a wrong repeated value, causing the "overwriting" of collection items.

So, in order to solve this I just made sure that a simple array is stored/returned.

public function setLocales($locales)
{
    $this->locales = array_values($locales);
}

Hope this helps to anyone facing the same problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment