Last active
December 25, 2015 20:29
-
-
Save alexander-arce/7035909 to your computer and use it in GitHub Desktop.
Remove blank fields
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* http://www.rjguevara.com/2013/02/symfony-2-ignorar-campos-vacios-en.html | |
*/ | |
namespace Acme\TestBundle\Form\Listener; | |
use Symfony\Component\Form\FormEvent; | |
use Symfony\Component\Form\FormEvents; | |
use Symfony\Component\Form\FormFactoryInterface; | |
use Symfony\Component\EventDispatcher\EventSubscriberInterface; | |
class IgnoreBlankFieldListener implements EventSubscriberInterface | |
{ | |
private $factory; | |
private $name; | |
public function __construct(FormFactoryInterface $factory, $name) | |
{ | |
$this->factory = $factory; | |
$this->name = $name; | |
} | |
public static function isNotEmpty($var ) | |
{ | |
if(is_array($var)) | |
{ | |
$notempty = false; | |
foreach( $var as $v ) | |
{ | |
$notempty = $notempty || !IgnoreBlankFieldListener::isNotEmpty($v); | |
} | |
return $notempty; | |
} | |
else | |
return !empty ($var); | |
} | |
public static function isEmpty( $var ) | |
{ | |
return IgnoreBlankFieldListener::isNotEmpty($var); | |
} | |
public function preBind(FormEvent $event) | |
{ | |
$data = $event->getData(); | |
$form = $event->getForm(); | |
$data_name = isset($data[$this->name])?$data[$this->name]:null; | |
if($data_name && IgnoreBlankFieldListener::isEmpty($data_name) ) | |
{ | |
unset( $data[$this->name] ); | |
$event->setData($data); | |
$form->remove($this->name); | |
}else{ //Additional check for children forms | |
if($form->has($this->name)){ | |
$field = $form->get($this->name); | |
if(!$field->getData() || $field->isEmpty()) | |
{ | |
$form->remove($this->name); | |
} | |
} | |
} | |
} | |
public static function getSubscribedEvents() { | |
return array( | |
FormEvents::PRE_BIND => 'preBind', | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment