1

Symfony 4 as a backend, Angular as frontend. I have a simple form - let's say two fields which cannot be blank.

Entity:

/**
 * @var string
 *
 * @ORM\Column(name="signature", type="string", length=32, unique=true)
 * @JMSSerializer\Expose
 */
private $signature;

/**
 * @var int
 *
 * @ORM\Column(name="status", type="integer")
 * @JMSSerializer\Expose
 */
private $status;

So default is NOT NULL.

After leaving one of those fields blank and submitting the form I get 500 error. Dev.log says: "Integrity constraint violation: 1048 Column 'status' cannot be null". Obviously. But how to catch this error? Or maybe just prevent submitting a form with blank fields on Angular side?

My controller:

public function postAction(Request $request)
{
    $form = $this->createForm('App\Form\ItemType', null, [
        'csrf_protection' => false,
    ]);
    $form->submit($request->request->all());

    if (!$form->isValid()) {            
        return $form;
    }
    ...

As suggested elsewhere I could send an array of errors:

$errors = [];
foreach ($form->getErrors(true) as $error) {
    if ($error->getOrigin()) {
        $errors[$error->getOrigin()->getName()][] = $error->getMessage();
    }
}

But isValid() method is never called.

BTW) Is it a good idea to return a form as a response in this case? I have seen this in some tutorial. But maybe returning

new View(null, Response::HTTP_BAD_REQUEST) 

with some additional info would be a better option?

1 Answer 1

1

Hi @Tompo if you want to use form for validation you need to do like this in your entity

use Symfony\Component\Validator\Constraints as Assert;

/**
 * @var string
 *
 * @ORM\Column(name="signature", type="string", length=32, unique=true)
 * @Assert\NotBlank(message="Please enter a signature")
 * @JMSSerializer\Expose
 */
private $signature;

/**
 * @var int
 *
 * @ORM\Column(name="status", type="integer")
 * @Assert\NotBlank(message="Please enter a status")
 * @JMSSerializer\Expose
 */
private $status;

Now you can get call if fileds are blank, after this you need to edit your controller for display errors messages

Sign up to request clarification or add additional context in comments.

1 Comment

Thats it! I had no idea this applies also to rest api.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.