Model name: listing
;
Field name: contact_name
.
User input involved, so I want to format the output, consistently, with some variant of getContactName
, i.e. any call to $model->contact_name
returns the formatted output. Yes, I can use, for example, getContactName
and $model->contactName
, but I have not found any variant of getcontact_name
that will work with the default $model->contact_name
.
I'm aware that I could configure Gii to create some additional functions, and various other workarounds, but I'm interested, after a decent Google, in whether there is a straightforward solution.
getContact_name()
will not work if you already have attribute (or regular object property) with contact_name
as a name. Attributes from database have precedence over getters/setters - you can see this in __get()
source code. And obviously __get()
will never be called if you have real property with this name. So value will be searched in this order:
- Object properties.
- Attributes from database.
- Getters/setters (including relations).
You should either use different name (contactName
), or do formatting using afterFind
event or override __get()
to change order of data sources (this could be tricky). You may be also interested in this PR.
You can override the afterFind()
method for your desired model and override the default value , or format the default value to your desired format.
You can override the method by adding the below into your model Listing
.
Lets say we need to format the default contact name which is saved like rich-harding
in the table and we will format it as Rich Harding
public function afterFind() {
parent::afterFind();
$names=explode("-",$this->contact_name);
$this->contact_name=implode(" ", array_map('ucfirst',$names));
}