Mike Mike - 2 months ago 16x
PHP Question

Force Uppercase on Symfony2 form text field

I've inherited a Symfony2 project that has a form built as such:

->add('Status', 'choice', array(
'choices' => array('' => '', 'PASS' => 'PASS', 'FAIL' => 'FAIL', 'INCOMPLETE' => 'INCOMPLETE', 'DROPPED' => 'DROPPED',),
'required' => FALSE,
->add('First_Name', 'text', array('label'=>'First Name',
'required' => FALSE))
->add('Last_Name', 'text', array('label'=>'Last Name',
'required' => FALSE))
->add('PID', 'text', array('label'=>'License Number',
'required' => FALSE))

I need to have any letters entered in the PID field to be forced to uppercase. However I cannot find a option/attribute/... to do this.

Is there any way to do this?


I’m not sure if you ask for server-side validation or assistance for client-side uppercase input. In case of the latter: you could add a CSS class or a data-* attribute (something like ->add('PID', 'text', ['label'=>'License Number', 'required' => FALSE, 'attr' => ['data-behavior' => 'uppercase']])) to the PID element. Then, you could add a JavaScript event handler in the form (preferably using jQuery or some other framework) to automatically convert lowercase to uppercase letters on blur/change. (I would prefer the data-* attribute, as this has nothing to do with CSS.)

To enforce that on the server-side, you could use a @Assert\Regex annotation.