I’m following the tutorial How to Dynamically Generate Forms Using Form Events. I’m stuck on the creation of AddNameFieldSubscriber:
$subscriber = new AddNameFieldSubscriber($builder->getFormFactory());
My question is simple: how FormFactory can access and modify an arbitrary form field previously created by the $builder? And why we are passing the FormFactory instead of the $builder itself?
Assuming we have just two fields (“name” and “price”) in the builder:
class ProductType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$subscriber = new AddProductTypeSubscriber($builder->getFormFactory());
$builder->addEventSubscriber($subscriber);
$builder->add('name');
$builder->add('price');
}
public function getName() { return 'product'; }
}
I’d like to set required = false (just an example) in the subscriber:
class ProductTypeSubscriber 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(DataEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
if (null === $data) return;
// Access "name" field and set require = false
}
}
I could be wrong about it this, but I don’t believe you can change a form’s attributes after its been created. However, you can add to the form.
Instead of adding the ‘name’ field in
ProductType::buildForm, you can defer this to the subscriber: