M
M
MainMaster2020-05-06 12:20:39
symfony
MainMaster, 2020-05-06 12:20:39

How to group form validation in Symfony 4.4.8?

There was a question: I have such a form

namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\Url;
/**
 * Class CommonFieldType
 * Implements adjacent fields for the short link form and the file upload form
 * @package App\Form
 */
class CommonFieldType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('url',TextType::class,['constraints' => new Url()])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            // Configure your form options here
        ]);
    }
}

Symfony has a standard filter for checking url

Symfony\Component\Validator\Constraints\Url


To use it I write

['constraints' => new Url()]


But I need to check more max length how to do it? There is such a way

['constraints' => new Length(['max' => 255])]


But the field can still be empty. But how do I combine these three checks? That is, the condition for checking the form: if it is not empty, check for the validity of the url and for the length. The official documentation says

If you are using validation groups, you need to either reference the Default group when creating the form, or set the correct group on the constraint you are adding: new NotBlank(['groups' => ['create', 'update'] ]);


But to be honest, it did not help me at all, tell me how to do it?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question