I have a problem that Yii2 model tries to save empty value as null, not as empty string. As far as I have not null mysql column, I am getting mysql error. In Yii 1 there was a config option 'nullConversion' => PDO::NULL_EMPTY_STRING . How can I achieve the same in Yii2? Just want ORM to save empty values as '', not null. Thanks
3 Answers
You can try a different approach to solve this, using rules:
public function rules() {
return [
...
[['field1', 'field2'], 'default', 'value' => ''],
...
This way you can have some fields default to empty strings instead of null, without affecting all fields.
In order to automatically convert the mysql NULL to empty strings in Yii2, use this -
'db' => [
'dsn' => 'mysql:host=127.0.0.1;dbname=database',
'attributes' => [
PDO::ATTR_ORACLE_NULLS => PDO::NULL_TO_STRING
]
],
1 Comment
Gogol
Dunno how it works, but it does...not the accepted one. +1.
Yii2 doesn't convert null to an empty string by default. If you don't want it to automatically convert a null to an empty string then:
- Check your code and make sure that field contains a
nullbefore calling thesavemethod. beforeSaveshouldn't replace fields.PDO::NULL_TO_STRINGshould not be set.
Also see this issue.
If you want to automatically convert a null to an empty string then set PDO::NULL_TO_STRING in 'db' component.
'db' => [
'dsn' => 'mysql:host=127.0.0.1;dbname=database',
'attributes' => [
PDO::NULL_TO_STRING => true
]
],
3 Comments
Volodymyr
So, how can I make it to automatically convert null to empty string?
Onedev_Link
You can extends all your ActiveRecord from class where in beforeSave will be replace all null values to empty strings.
Volodymyr
Yes, did that. So pitty no other solutions.