Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to pass options from resolver to Symfony Form Event
<?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'
]);
}
}
@webdevilopers
Copy link
Author

webdevilopers commented Sep 27, 2016

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:

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')

Opinions?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment