1

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?

lorem monkey
  • 3,942
  • 3
  • 35
  • 49
Marsick
  • 138
  • 1
  • 11
  • You should define `targetClass` and `targetAttribute` for that rule. `[['parent_id'], 'exist', 'targetClass' => 'app\models\Parent', 'targetAttribute' => 'id', 'skipOnEmpty' => true],` – ThanhPV Aug 03 '16 at 02:45
  • I have `targetAttribute`, `targetClass` is same model by default. – Marsick Aug 03 '16 at 06:25
  • Can I ask why do you have both `NULL` and `0` as possible values for this column? Don't they mean the same thing? – Clyff Aug 03 '16 at 18:53
  • Not both, if I create new record I didn't set `parent_id` so it is **NULL**, but into database set to default value - 0. – Marsick Aug 03 '16 at 20:38
  • What do you mean "didn't work"? Allows to insert rows with not existent parent id? Or throws some exception? Have you tried to change the order of rules (move rule `default` at the end)? – oakymax Aug 05 '16 at 10:46

1 Answers1

3

change the order of rules:

[['parent_id'], 'integer'],
[['parent_id'], 'exist', 'targetAttribute' => 'id', 'skipOnEmpty' => true],
[['parent_id'], 'default', 'value' => 0],
oakymax
  • 1,454
  • 1
  • 14
  • 21