Commit 7bd0245a authored by Emma's avatar Emma 🦉

prevent duplicate form submission

parent e2ed9bd0
Pipeline #55524845 passed with stages
in 19 minutes and 6 seconds
<?php
namespace App\Form\Extension;
use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
/**
* Prevent submitting a form multiple times by invalidating its CSRF token ID
* after validation passes.
*/
final class PreventMultipleSubmitExtension extends AbstractTypeExtension {
public static function getExtendedTypes(): array {
return [FormType::class];
}
public function buildForm(FormBuilderInterface $builder, array $options): void {
$builder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) {
$form = $event->getForm();
if (
!$form->isRoot() ||
!$form->isValid() ||
!$form->getConfig()->getOption('csrf_protection')
) {
return;
}
// from symfony's FormTypeCsrfExtension.php
$tokenId = $form->getConfig()->getOption('csrf_token_id')
?: $form->getName()
?: \get_class($form->getConfig()->getType()->getInnerType());
/* @var CsrfTokenManagerInterface */
$tokenManager = $form->getConfig()->getOption('csrf_token_manager');
$tokenManager->refreshToken($tokenId);
}, -10);
}
}
{{ form_start(form, {attr: {class: 'comment-form'}}) }}
{{ form_errors(form) }}
<div class="comment-row">
{{ form_row(form.comment, {attr: {rows: 6}}) }}
</div>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment