Yii2 model get method for field containing underscore

Rich Harding

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.

rob006

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:

  1. Object properties.
  2. Attributes from database.
  3. 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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related