7

I'm using a MySql database, so I defined the column type as Tinyint(1) in db schema.

In my ActiveRecord I've set boolean validator. Save logic is working as expected.

What I wanted now is that when I call Yii2 REST service, return boolean field as true or false instead 1 or 0, because on the client side the framework comes with strict comparison (===) and 1 is not the same as true.

Of course I could overwrite the value manually before sending the content, or on the client side before loading it into the model, but I would appreciate a cleaner solution.

Wai Ha Lee
  • 7,664
  • 52
  • 54
  • 80
edrian
  • 4,377
  • 5
  • 26
  • 34

1 Answers1

2

Inside afterFind i would modify the values from 0 or 1 to true or false:

public function afterFind() {
    $this->booleanField = ($this->booleanField === 1);
    parent::afterFind();
}
marche
  • 1,676
  • 1
  • 14
  • 24
  • 1
    Yes, I've already done that, but I would expected some "automatic" way of doing this. The field is marked as boolean in my model, isn't there a way to let JSON Response Formatter know that by itself? – edrian Oct 06 '15 at 12:30
  • I don't believe there is a way to do so automatically, because it's not something needed for most situations and if you need to do so you can add that functionality on afterFind. – marche Oct 06 '15 at 15:38
  • 1
    Yeah, I suppose you're right.. But I least I want a way to extend model or controller with this behavior (maybe just extending afterFind as you suggested). Do you know how to get all fields with "boolean" validator set? – edrian Oct 06 '15 at 15:59
  • 1
    I guess you could just call the rules method and check the array it returns. – marche Oct 06 '15 at 16:18