symfony - Remove null values coming from empty collection form item -


i'm trying implement manytomany relation in form between 2 entities (say, product , category make simpe) , use method described in docs prototype , javascript (http://symfony.com/doc/current/cookbook/form/form_collections.html).

here line producttype create category collection :

$builder->add('categories', 'collection', array(                    'type' => 'entity',                    'options' => array(                         'class' => 'appbundle:category',                         'property'=>'name',                         'empty_value' => 'select category',                         'required' => false),                    'allow_add' => true,                    'allow_delete' => true,               )); 

when had new item, new select appear set empty value 'select category'. problem if don't change empty value, sent server , after $form->bind() product object null values in $category arraycollection.

i first though test value in setter in product entity, , add 'by_reference'=>false in producttype, in case exception stating null not instance of category.

how can make sure empty values ignored ?

i found way handle event listeners. discussion give meaning of formevents. in case, pre_bind (replaced pre_submit in 2.1 , later) allow modify data before bind entity.

looking @ implementation of form in symfony source source of information found on how use events. pre_bind, see form data updated event data, can alter $event->setdata(...). following snippet loop through data, unset null values , set back.

$builder->addeventlistener(formevents::pre_bind, function(formevent $event){     $data = $event->getdata();     if(isset($data["categories"])) {         foreach($data $key=>$value) {             if(!isset($value) || $value == "")                 unset($data[$key]);         }         $event->setdata($data); }); 

hope can others !


Comments