Skip to content

Instantly share code, notes, and snippets.

@webdevilopers
Last active September 27, 2016 09:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webdevilopers/9cfeab0bd5c20af6d0b6adfa63d2cdcf to your computer and use it in GitHub Desktop.
Save webdevilopers/9cfeab0bd5c20af6d0b6adfa63d2cdcf to your computer and use it in GitHub Desktop.
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

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