Piotr Pankowski
Piotr Pankowski

Reputation: 2406

Doctrine2: skip not set columns

I have following entity:

class Employee {

/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $employeeId;

/**
 * @ORM\Column(type="string", length=45, unique=true)
 */
protected $username;

/**
 * @ORM\Column(type="string", length=255, nullable=false)
 */
protected $email;

and I'm running following code:

$employee = new Employee();
$employee->setUsername('test');

$em = $this->getDoctrine()->getManager();
$em->persist($employee);
$em->flush();

As you can see I didn't set value for email column.

But on persists I get:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'email' cannot be null

because Doctrine adds all entity columns to the INSERT query and set null value for email column.

Is there a way to skip not set columns on insert? Or to make Doctrine insert '' (empty string) as default value for non null, string columns?

Upvotes: 1

Views: 1826

Answers (3)

moonwave99
moonwave99

Reputation: 22817

You may either allow your column to be null, setting nullable=true:

/**
 * @ORM\Column(type="string", length=255, nullable=true)
 */
protected $email;

This won't raise the SQL error. But if you want to be consistent, use validation so you can deal with empty fields before persistance:

use Symfony\Component\Validator\Constraints as Assert;

...

/**
 * @Assert\NotBlank()
 * @ORM\Column(type="string", length=255)
 */
protected $email;

This way you can handle validation errors in a more specific way, like stated in docs for example:

$author = new Author();
// ... do something to the $author object

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

if (count($errors) > 0) {
    return new Response(print_r($errors, true));
} else {
    return new Response('The author is valid! Yes!');
}

If you want just plain default values for columns, have a look at this question.

Upvotes: 2

Krzysztof Ożóg
Krzysztof Ożóg

Reputation: 44

It's rather problem with your data model not with doctrine. You explicit declare that every record should have some value in email column. So either you remove NOT NULL constrain from entity or you just set some value on email column. In this case doctrine is only doing what you've told it to do.

Upvotes: 0

Piotr Pankowski
Piotr Pankowski

Reputation: 2406

I seems that I just have to use entity __construct to set default values:

__construct() {
    $this->email = '';
}

Upvotes: 0

Related Questions