php - Not Updating Entity if validation fails Symfony [form]

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
insidesetPhone($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.
Answer
Solution:
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())
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: failed to create image decoder with message 'unimplemented'
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.