Barrosy
Barrosy

Reputation: 1457

How do I prevent null value form Symfony

I want to know how I can make sure that I will not receive a null value from a form within Symfony, server side. The code I am using now:

public function insertAction(Request $request)
{           
    $movie = new Movie();

    if($request->get('title') != null)
    {
        $movie->setTitle($request->get('title'));
    }

    if(str_replace('.', '', $request->get('price')) != null)
    {
        $movie->setPrice(str_replace('.', '', $request->get('price')));
    }

    if($request->get('description') != null)
    {
        $movie->setDescription($request->get('description'));
    }

    $em = $this->getDoctrine()->getManager();
    $em->persist($movie);
    $em->flush();
    return $this->redirectToRoute('movies');
}

But whenever I send an empty form I still get to see the following error: An exception occurred while executing 'INSERT INTO movie (title, price, description) VALUES (?, ?, ?)' with params [null, null, null]:SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null. What can I do to improve my code? Thanks in advance.

Edit: This is my solution: http://pastebin.com/4Z088SNz

Upvotes: 0

Views: 1183

Answers (2)

ROLO
ROLO

Reputation: 581

short answer: use the validator component and add a NotNull constraint to your field

long answer: use properly the form component and the validator component

1) add the NotNull constraint to your entity

2) implement this

$form = $this->createForm(new MovieType(), new Movie());
$form->handleRequest($request);

if($form->isValid()){
  ... persist ...
}

3) MovieType must be mapped to your entity Movie via defaults

Upvotes: 2

Paweł Mikołajczuk
Paweł Mikołajczuk

Reputation: 3812

Use validation in your entity. Example:

use Symfony\Component\Validator\Constraints as Assert;

class Movie
{
    /**
     * @Assert\NotNull()
     */
    protected $title;
}

You can validate it manually:

$validator = $this->get('validator');
$errors = $validator->validate($movie);

if (count($errors) > 0) {
    // do stuff here
}

Or use integration with Symfony form component.

Read more here: http://symfony.com/doc/current/book/validation.html#using-the-validator-service

Upvotes: 1

Related Questions