Derived attribute in model

Hi all,

Curious what would be the proper way to add a derived attribute to a model (ActiveRecord).

The order number for my order class is a combination of two fields that both exist in the database, being id and customername.

So e.g.

id = 100

customername = ‘ACME’

Order number then would be ‘ACME-100’

Since id and customer name are in the database I can use things as $order->id etc.

How can I create a getter/setter for the derived attribute ordernumber so I don’t need to concatenate the two fields time and time again? Instead I’d like to use $order->ordernumber which would do that for me.

Cheers,

G

create a property on your model in this form:




public function getOrderNumber(){

    return $this->customername . '-'.$this->id;


}



Later on your code you can just call : model->orderNumber();

Thanx, works wonderfully :slight_smile:

Folks,

I know that this is an old thread, but it pertains to a problem I’ve seen. When I create derived attributes in a CGridview as shown above, I cannot seem to filter based on this new derived attribute. I observe:

  1. Typing a filter criteria into the filter textfield does nothing

  2. If my derived attribute adds any characters (such as a hyphen), then this hyphen appears in the filter box.

So I am assuming that the inner workings of the filter mechanism are calling the getter behind the scenes, and somehow need to be adjusted to fix this. Has anyone done it before?

Thanks,

Bill