Yii Framework. How to get a different value for the field?

I have a table with a field vat_free. So, my model was created with a property $vat_free. Its value can be 0 or 1 .

I want my view to show No or Yes instead of 0 or 1 . I can do this by creating a getter, for example getVatFree(), but it seems like a messy solution, because then I will have two properties in one field, although it will work for different purposes.

So how can I use only the original property $vat_free? Can't I change its getter?

+4
source share
3 answers

You can do

$vat_free = YES or NO

but before saving this object, you override the class of the object using a method beforeSave(), for example:

beforeSave(){
   if($this->vat_free = YES){
         $this->vat_free = 1
   }else{
$this->vat_free = 0;
   }
}

and override afterFind()to do the reverse (for beforeSave ()) translation. But this is not even messy and will not work if you are doing mass saving or retrieving.

I see 2 solutions.

  • Go with what you said getVatFree(), this is the whole goal of OOP encapsulation.
  • Instead of doing 1 or 0 in db, do the values ​​Y or N, you can use them in both places without any problems.
+3
source

Way to create

public function getVatFreeString(){
    return $this->vat_free ? 'Yes':'No';
}

The right decision is not dirty.

+4
source

In your model, create a new field that will be used only for display.

class User extends CActiveRecord
{

  public $displayVatFreeFlag;

  public function rules() { ... }

  public function afterFind()
  {
     $this->displayVatFreeFlag = ($this->vat_free ? 'Yes':'No');
  }
}

Then in your field, display the field as usual.

Vat free : <?php echo $model->displayVatFreeFlag; ?>
+2
source

Source: https://habr.com/ru/post/1535785/


All Articles