phpyii2

Yii2 - mysql default blank string displays as two single quotes in form field


I got table in MySQL with default blank string value. In SQL it looks like:

`key` TINYTEXT NOT NULL DEFAULT '',

In the model i set rule with blank string as default value:

[['key'], 'default', 'value' => ''],

And i try to do simple form with it

    <?= $form->field($model, 'key')->textarea(['rows' => 6]) ?>

In the form i see textarea with two single quotes as default value.

two single quotes

All fields with default blank string value got this bug.

My connection params:

return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=xxx',
    'username' => 'xxx',
    'password' => 'xxx',
    'charset' => 'utf8',
];

How can i fix it?

I try to dump $model->key before form display and got this value - two single quotes. I seen ActiveRecord::loadDefaultValues and tried dump there - got this bug there.

bad default value

I found only one decision - set no default value and set blank string in the model code. But this is no right because i got other soft works with this db and it use default values.


Solution

  • in your model use virtual attribute, replace validation rule and form field with it

    public function getKeyAttr()
    {
        return $this->key == "''" ? null : $this->key;
    }
    
    public function setKeyAttr($val)
    {
        $this->key = $val ? $val : "''";
    }
    
    //in rules():
    [['keyAttr'], 'default', 'value' => null]
    
    //in view:
    $form->field($model, 'keyAttr')->textarea(['rows' => 6])