baby how it is done meme

Symfony 5+ how to make a form field hidden from display

This is easier than it sounds, but I am writing this in case I need to remember what the answer is.

At first I wasn’t paying attention to all of the many different Symfony form types in this long list.  I totally didn’t see the HiddenType in the list or I didn’t notice it.

I tried to simply add a class using attr in the definition. This kind of worked. It just showed the name of the field in a label, which wouldn’t work for my design and use.

HiddenType works exactly like what I needed.

When building a form in a FormType class you can create hidden fields like this one which hides a nonce for AJAX request validation.

->add('ajaxString', HiddenType::class, [
    'mapped' => false,
    'attr' => ['class' => 'hidden-field', 'value' => $secretString]
])

Always add ‘mapped’ false for any field you want to tell Symfony to ignore, like this field used for processing AJAX requests. $secretString is just a random 32 character string I am storing in a session on the backend and sending with the AJAX request to make sure the request is coming from my app.


Posted

in

by

Tags:

Comments

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: