Symfony 4 : validator is refreshing instead of displaying message

132 Views Asked by At

I have a symfony add form here , and on "client" section are 2 possibilities (either a client already exists, and it s selected from db, either it doesn t exist and you have to complete additional fields that are imported as CollectionFormType). When you create a new client, his phone number must be unique, so I tried adding a custom constraint "checkUnique" that check for duplicates and for format.

The problem is that, when a constraint condition from newClient field (phone) is met, the page is refreshing getting a violation "phone already exists" instead of displaying a message like this. How can I stop the page from submitting and display a message to change the phone number, without refresh?


CollectionFormType "NewClientType" that I used:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    etc just important
    $builder
        ->add('phone', TextType::class, array(
            'required' => true,
            'label' => $this->translator->trans('Telefon'),
            'constraints'=>[
                new NotBlank(['message' => $this->translator->trans('Câmpul este obligatoriu')]),
                new Callback(array($this, 'checkUnique'))
            ],
            'attr' => array(
                'placeholder' => $this->translator->trans('Telefon')
            )
        ));

}

public function checkUnique($value, ExecutionContextInterface $context) {
    $form = $context->getRoot();
    $data = $form->getData();
    $phone = str_replace("+","00",$context->getValue());
    if (!ctype_digit($phone)) {
        $context->buildViolation($this->translator->trans("Format invalid"))
            ->addViolation();
    } else if ($this->entityManager->getRepository(Clients::class)->findOneBy(["phone" => $phone])) {
        $context->buildViolation($this->translator->trans("Telefonul exista deja"))
            ->addViolation();
    }
}

FormType which contains CollectionFormType "NewClientType":

public function buildForm(FormBuilderInterface $builder, array $options) {

    etc just important
    $form->add('newClient', CollectionType::class, [
        'entry_type' => ClientsNewType::class,
        'allow_add'    => true,
        'allow_delete' => true,
    ]);
}

(I'm using Prototype to render this form).

0

There are 0 best solutions below