简体   繁体   中英

Yii Framework - How do I get a different value for a field?

I have a table with a field called 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 it creating a getter like getVatFree() , but it seems like a messy solution, because then I'll have two properties to the same field, even though it would serve different purposes.

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

Creating method

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

Is proper solution, it's not messy.

You could do like

$vat_free = YES or NO

but right before save this object you would override object class with beforeSave() method like following:

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

and override afterFind() to do the reverse(for beforeSave()) translate. But this is even messy and will not work if u do bulk save or retrieve.

I see 2 solutions.

  1. Go with what you have said getVatFree() , this is whole purpose of OOP encapsulation.
  2. Instead of making 1 or 0 in db, do Y or N values, you can use them in both places without problems.

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

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 normal.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM