Search code examples
phpyii2yii2-advanced-appyii2-modelyii2-validation

Foreign key validation rule in Yii2


I have parent_id that can have NULL value - default sets to 0.

Model

...
[['parent_id'], 'integer'],
[['parent_id'], 'default', 'value' => 0],
[['parent_id'], 'exist', 'targetAttribute' => 'id', 'skipOnEmpty' => true],
...

But exist rule didn't work.

What I'm doing wrong?

UPDATE

Today I removed the following rule and it works:

...
[['parent_id'], 'default', 'value' => 0],
...

But what do I do if want to change the default to other value?


Solution

  • change the order of rules:

    [['parent_id'], 'integer'],
    [['parent_id'], 'exist', 'targetAttribute' => 'id', 'skipOnEmpty' => true],
    [['parent_id'], 'default', 'value' => 0],