I have a form which contains a collection. So I have:
/* my type */
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
To add to Chadwick Meyer, (in Symfony 4, but probably applies to earlier versions), an event listener is needed to access the data in a collection because many times data hasn't been created yet and/or hasn't been associated or embedded to the collection. However, there are some intricacies associated with actually getting at the data in the collection via the event listener that becomes important in everyday usage.
In your photo form builder, you'll have to include an event listener:
/*Photo Type*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('photoname')
->add('size');
$builder->addEventListener(FormEvents::POST_SET_DATA,
function (FormEvent $event) {
$form = $event->getForm();
// this would be your entity
$photo = $event->getData();
//Do something with the photo data.
}
);
}
However... if you want to do something with it, you need to make sure you test for nulls as the event is triggered multiple times before and after the data is actually created dynamically. For example, if you want to modify the form on the fly like add some sort of submit button:
/*Photo Type*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('photoname')
->add('size')
$builder->addEventListener(FormEvents::POST_SET_DATA,
function (FormEvent $event) use ($formModifier) {
$form = $event->getForm();
// this would be your entity
$photo = $event->getData();
$formModifier($form,$photo);
}
);
$formModifier = function (FormInterface $form, Photo $photo = null) {
if (!empty($photo)){//Critical to do this test to avoid errors and get to events with data
$form->add('submitButton', SubmitType::class, array(
'label' => 'Do Something',
));
}
};
}
Finally, please note that in certain cases, not all the data will be associated with a particular entity until it is actually persisted in the database. For example, if the entity is being newly created, it will not have its id yet which is usually automatically generated by doctrine or similar during persist. Therefore, in order to associate a submit button or similar to this entity in the collection before it is persisted, you'll probably have to make the 'name' field unique or create a separate field for the entity to hold a unique type parameter and generate it in a unique manner prior to persisting in order to associate something like a submit button to the entity during form creation.