Difference between #3 and #4 of
Understanding Virtual Attributes and get/set methods

Revision #4 has been created by Maurizio Domba Cerin on Mar 31, 2011, 7:17:01 AM with the memo:

spaces adjustment
« previous (#3) next (#5) »


Title unchanged

Understanding Virtual Attributes and get/set methods

Category unchanged


Yii version unchanged

Tags unchanged

Virtual Attributes; __get; __set

Content changed

Yii treats functions beginning with "get" as special, so let's make one to provide the full name in a single step:

class Person extends CActiveRecord {

public function getFullName()
return $this->firstname . " " . $this->lastname;
// in a view somewhere

echo $form->dropDownList($model, 'personid',    CHtml::listData( Person::model()->findAll(), 'id', 'fullname' )   );
Now, the dropdown will show full user names in the dropdown, which makes for a better user experience. Attempting to provide a dropdown including firstname + lastname without a model helper function like this is more work and less useful.

**EXTRA BONUS** - In the future, if you add a MiddleName to the Person database table, you only have to modify the `getFullname()` method in order to automatically update all the views that use `$model->fullname`.
65 0
Viewed: 156 534 times
Version: 1.1
Category: Tutorials
Written by: Steve Friedl
Last updated by: GOsha
Created on: Mar 31, 2011
Last updated: 6 years ago
Update Article


View all history