Created
May 6, 2015 13:11
-
-
Save webdevilopers/baf0331d2d2bbd4b8e08 to your computer and use it in GitHub Desktop.
Remove field type from symfony form using PRE_SET_DATA event
This file contains hidden or 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 | |
namespace Acme\AppBundle\Controller; | |
use Symfony\Bundle\FrameworkBundle\Controller\Controller; | |
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; | |
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; | |
use Acme\AppBundle\Form\RemoveType; | |
class FormController extends Controller | |
{ | |
/** | |
* @Route("/form/remove") | |
* @Template() | |
*/ | |
public function removeAction() | |
{ | |
$data = array('foo' => 'FOO'); | |
$form = $this->createForm(new RemoveType(), $data); | |
return array('form' => $form->createView()); | |
} | |
} |
This file contains hidden or 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
{% extends "::base.html.twig" %} | |
{% block body %} | |
{# {{ form(form) }}#} | |
{{ form(form.foo) }} | |
{% if (form.bar) is defined %} | |
{{ form(form.bar) }} | |
{% endif %} | |
{% endblock %} |
This file contains hidden or 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 | |
namespace Acme\AppBundle\Form; | |
use Symfony\Component\Form\AbstractType; | |
use Symfony\Component\Form\FormBuilderInterface; | |
use Symfony\Component\Form\FormEvent; | |
use Symfony\Component\Form\FormEvents; | |
/** | |
* @author Michael Borchers <[email protected]> | |
*/ | |
class RemoveType extends AbstractType | |
{ | |
public function buildForm(FormBuilderInterface $builder, array $options) | |
{ | |
$builder | |
->add('foo') | |
->add('bar') | |
; | |
$builder->addEventListener(FormEvents::PRE_SET_DATA, | |
function (FormEvent $event) { | |
$data = $event->getData(); | |
$form = $event->getForm(); | |
$form->remove('bar'); | |
dump($data); | |
}); | |
} | |
public function getName() { | |
return 'remove'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment