Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

yii

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?

like image 432
felipe.zkn Avatar asked Jan 11 '23 20:01

felipe.zkn


2 Answers

Creating method

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

Is proper solution, it's not messy.

like image 122
Alex Avatar answered Feb 02 '23 08:02

Alex


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.
like image 39
Elbek Avatar answered Feb 02 '23 09:02

Elbek