https://gist.github.com/webdevilopers/9cfeab0bd5c20af6d0b6adfa63d2cdcf How to pass options from resolver to Symfony Form Event
I need to get the translation_domain from the options inside an Symfony Form Event.
Since the actual event callback function for onPreSubmit can grow very big I would like to use the addEventListener method linking to the separate method instead of using the function:
http://symfony.com/doc/current/form/dynamic_form_modification.html#adding-an-event-listener-to-a-form-class Unfortunately without the function I cannot pass the $options? viause`.
The solution I came up with is to get the options from the Form Config:
$form->getConfig()->getOption('translation_domain')
<?php
class CustomerInformation extends AbstractType
{
/**
* @var Translator $translator
*/
private $translator;
public function __construct(
Translator $translator
) {
$this->translator = $translator;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addEventListener(
FormEvents::PRE_SUBMIT,
[$this, 'onPreSubmit']
);
}
public function onPreSubmit(FormEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
if (!empty($data['customerId'])) {
// ...
if (count($customer->customerPriceLists()) === 0) {
$form->addError(new FormError($this->translator->trans(
'No price list linked from QSP to customer.',
[],
$form->getConfig()->getOption('translation_domain')
)));
}
}
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'translation_domain' => 'order_entry'
]);
}
}