2

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 3

2

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.

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

2 Comments

Yes, but doing that website-wide would be a better approach.
That actually depends, specially if you actually need some fields to default to null.
2

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

Dunno how it works, but it does...not the accepted one. +1.
0

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 null before calling the save method.
  • beforeSave shouldn't replace fields.
  • PDO::NULL_TO_STRING should 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

So, how can I make it to automatically convert null to empty string?
You can extends all your ActiveRecord from class where in beforeSave will be replace all null values to empty strings.
Yes, did that. So pitty no other solutions.

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.