Created
February 11, 2019 19:17
-
-
Save sstok/6d0e96236087176f0398e0b90ad6a546 to your computer and use it in GitHub Desktop.
TransformationFailureExtension.php (testing only)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Symfony\Component\Form\AbstractTypeExtension; | |
use Symfony\Component\Form\Extension\Core\Type\FormType; | |
use Symfony\Component\Form\FormBuilderInterface; | |
use Symfony\Component\Form\FormError; | |
use Symfony\Component\Form\FormEvent; | |
use Symfony\Component\Form\FormEvents; | |
class TransformationFailureExtension extends AbstractTypeExtension | |
{ | |
public function buildForm(FormBuilderInterface $builder, array $options) | |
{ | |
$builder->addEventSubscriber(new TransformationFailureListener()); | |
} | |
public static function getExtendedTypes(): iterable | |
{ | |
return [FormType::class]; | |
} | |
} | |
class TransformationFailureListener implements EventSubscriberInterface | |
{ | |
public static function getSubscribedEvents() | |
{ | |
return [ | |
FormEvents::POST_SUBMIT => ['convertTransformationFailureToFormError', -1024], | |
]; | |
} | |
public function convertTransformationFailureToFormError(FormEvent $event) | |
{ | |
$form = $event->getForm(); | |
if ($form->getTransformationFailure() === null || ! $form->isValid()) { | |
return; | |
} | |
foreach ($form as $child) { | |
if (! $child->isSynchronized()) { | |
return; | |
} | |
} | |
$clientDataAsString = is_scalar($form->getViewData()) ? (string) $form->getViewData() : \gettype($form->getViewData()); | |
$config = $form->getConfig(); | |
$messageTemplate = $config->getOption('invalid_message'); | |
$messageParameters = array_replace(['{{ value }}' => $clientDataAsString], $config->getOption('invalid_message_parameters')); | |
$message = strtr($messageTemplate, $messageParameters); | |
$form->addError(new FormError($message, $messageTemplate, $messageParameters, null, $form->getTransformationFailure())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment