I'd like to add autocomplete="off"
to all <form>
tag in my symfony project and I'm looking for the best way to do such.
I don't want to change all templates to change {{form_start}}
call or manually add attribute on form object in controller, neither add listener or subscriber on each form.
I am looking for a global solution, like a service that change all forms in one call.
I think if it's the default behavior of all your forms, it's better to think about a root solution. Extending type by default will do the trick
class FormTypeExtension extends AbstractTypeExtension
{
/**
* Return the class of the type being extended.
*/
public static function getExtendedTypes(): iterable
{
// return FormType::class to modify (nearly) every field in the system
return [FormType::class];
}
public function buildView(FormView $view, FormInterface $form, array $options): void
{
if (isset($view->vars['method'])) { // Make sure we're on the base form
$view->vars['attr']['autocomplete'] = isset($view->vars['attr']['autocomplete']) ? $view->vars['attr']['autocomplete'] : "off"; // let the possibility to override for specific forms
}
}
}
you just have to use it like that
class DefaultController extends AbstractController
{
/**
* @Route("/", name="home")
*/
public function home() {
$form1 = $this->createForm(DemoType::class, new Demo());
$form2 = $this->createForm(DemoType::class, new Demo(), ['attr' => ['autocomplete' => "on"]]);
return $this->render('demo.html.twig', ['form1' => $form1->createView(), 'form2' => $form2->createView()]);
}
}