Not Updating Entity if validation fails Symfony [form]

Viewed 231

Using Symfony 3.4 I want to not update and get the proper error when the input field is not matching regex.

here is my phone field inside entity

     /**
     * @var string
     *
     * @ORM\Column(name="phone", type="string", length=20, unique=true, nullable=false)
     * @Assert\NotBlank(message="Phone is required.")
     * @Assert\Regex(
     *      pattern=Presenter::PHONE_REGEX,
     *      message="Not a valid phone number"
     * )
     */
    private $phone;

I've tried to catch error while setting $phone inside setPhone($phone) like below

    /**
     * Set phone
     *
     * @param string $phone
     *
     * @return Worker
     */
    public function setPhone($phone)
    {
        if (preg_match(Presenter::PHONE_REGEX, $phone))
            $this->phone = $phone;
        return $this;
    }

And I get "Phone is required" message instead of "not a valid phone number" (Because phone is required in WorkerType).

I've searched google and found a thread on github didn't get what the end result was tho. I really need help on how should I properly prevent the entity update and get the correct error for it.

1 Answers

Add 'mapped' => false param in the WorkerType for phone field by PRE_SUBMIT event.

$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
      $phoneAttrs = [
          'mapped' => false,
          // add other attrs
      ];
      $event->getForm()->add('phone', TextType::class, phoneAttrs);
}

After form submitting call setPhone manually if field is valid:

if ($form->get('phone')->isValid() {
    $entity->setPhone($form->get('phone')->getData())
}
Related