Using dontrine2, I have an entity having property with following annotations:
/**
* @var string
* @Column(type="string", length=4, nullable=false)
*/
protected $someProperty;
Now when the property is set to foobar
, instead of getting an exception the string is trimmed to its first four characters, i.e. foob
which is then stored into the database.
I know that I could implement a length check in the setter. Yet then I would configure the length of the string in two places which I rather avoid.
I also could use a validation, yet this also would double the configuration.
I find it confusing that doctrine2 shortens the string implicitly, yet when setting the value to null
when nullable is false, I get an exception. This seems inconsistent.
Can I disable the trimming and force an exception? Or do I have to validate the entity myself?
Doctrine does not do any validation neither any string truncation. All exceptions you get comes from database layer.
When you try to insert null value into a column which is not allowed to be null database query fails.
When you try to insert a string value longer than length defined in a column definition MySql automatically truncate it. You can change this behaviour configuring MySql to use STRICT mode.