Reputation: 1391
Is there a way to retrieve the initial options passed to the FormBuilder
for the creation of the form? I know FormConfigInterface
has method getOptions()
, but I have used that and got the resolved options of the form instead, e.g: after being normalized.
So how can I get the original options passed by the user?
//by options, I mean the $options passed here
$formFactory->create('form_name', 'form_type', $options);
then I want to access $options later in and EventListener
registered to this form:
//.. in a form EventListener e.g: on preSubmit
$form = $event->getForm();
$options = $form-> ? //this is where I want to get $options that was passed above during the form's creation.
Upvotes: 2
Views: 255
Reputation: 9575
To achieve it with the current Form Component implementation is quite complicated, you'd need replicate the behavior of ResolvedTypeDataCollectorProxy
to be able to get the "passed options" after they are resolved.
I suggest you go back to the trivial method: defines a custom form option to pass the initial options.
class CustomFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->setAttribute('initial_options', $options['initial']);
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
// do something with:
$event->getForm()->getConfig()->getAttribute('initial_options');
});
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'initial' => null,
]);
}
}
So, you'd pass the "initial" option also to the form type options. Something like this:
$options['initial'] = $options;
$formFactory->create('form_name', CustomFormType::class, $options);
Upvotes: 2
Reputation: 1497
Inside your form class, you can add the following attribute and getter :
private $defaultOptions;
public function getDefaultOptions() {
return $this->defaultOptions;
}
And, in your buildForm
:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$this->defaultOptions = $options;
//...
}
Finally, in your EventListener :
//.. in a form EventListener e.g: on preSubmit
$form = $event->getForm();
$options = $form->getDefaultOptions();
Upvotes: -1