Symfony 3.2 Form best way to add a filter on textfield to remove unwanted Characters

552 Views Asked by At

I am using Symfony 3.2. I have a text field on a Symfony form. I would like to apply a "sanitize" function on form submission. What is the best way to do this? Here is a snippet of the form. The filed in question is "comment". I would like to remove unwanted characters from it. I don't really want to do everything in the controller.

$form = $this->createFormBuilder(
        array('items' => $orderItems))
        ->add('items', CollectionType::class,
            array(
                'entry_type' => ReturnItemType::class,
                'entry_options' => array('label'=>false),
                'allow_add' => true
            )
        )
        ->add('comment', TextareaType::class,
            array(
                'error_bubbling' => true,
                'constraints' => array(
                    new NotBlank()
                )
            ));
2

There are 2 best solutions below

1
Ihor Kostrov On

You can use symfony form events for this. For example PreSubmitEvent. To your form add

    ->addEventListener(
                FormEvents::PRE_SUBMIT,
                [$this, 'onPreSubmit']
            )

and

    public function onPreSubmit(FormEvent $event)
    {
        $data = $event->getData();

        if (!isset($data['comment'])) {
            return;
        }

        // do something with comment

        $event->setData($data);
    }
0
user3106759 On

So after looking at a few options i went with adding a data transform on the form itself.

$builder->add('comment', TextType::class, 
        array(
            'label' => 'Add a comment', 
            'required' => false,
        )
    )->get('comment')->addModelTransformer(return new CallbackTransformer (
        function ($originalText)
        {
            return preg_replace( 'REMOVETHISTEXT', '', $originalText);
        },
        function ($submittedComment)
        {
            return preg_replace( 'REMOVETHISTEXT', '', $submittedComment);
        }
    ));

This is a really the best way to do it from what I have read and tried out.