src / Bundle / Form / Type / NewsType.php
class NewsType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('body')
;
$subscriber = new AddExpiresAtFieldSubscriber($builder->getFormFactory());
$builder->addEventSubscriber($subscriber);
}
// ...
}
src / Bundle / Form / EventListener / AddExpiresAtFieldSubscriber.php
class AddExpiresAtFieldSubscriber implements EventSubscriberInterface
{
private $factory;
public function __construct(FormFactoryInterface $factory)
{
$this->factory = $factory;
}
public static function getSubscribedEvents()
{
return array(FormEvents::PRE_SET_DATA => 'preSetData');
}
public function preSetData(FormEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
if (null === $data) {
return;
}
// if is not new (updating data) add the field
if ($data->getId()) {
$form->add($this->factory->createNamed('expires_at', 'datetime', null, array(
'input' => 'datetime',
'widget' => 'single_text',
'format' => 'dd/MM/yyyy HH:mm'
)));
}
}
}
E caso você tenha problemas para adicionar ou remover um campo:
https://github.com/symfony/symfony/pull/4552#issuecomment-6809655