Creating compound attributes in Yii
Let’s say you have a database table called persons with separate attributes (fields) for lastName
and firstNames
. Elsewhere in your website, you want to refer to the underlying record in this table using the person’s whole name as a single entity (e.g. to provide a link, for example: <a href="http://example.com/index.php?r=Person/view&id=1">Jane Q. Public</a>
.
Sometimes, you might be able to refer to the two attributes separately. For example, if you simply wanted to echo the content in a view somewhere you could use code like this:
<?php echo CHtml::encode($data->person->firstNames) . ' ' . CHtml::encode($data->person->lastName); ?>
This is a little inefficient if you are doing it a lot throughout your site, because you need to keep re-entering the same code correctly over and over again (and avoiding this is a main reason for going with an MVC framework like Yii in the first place). But the real trouble comes if you want to use the attributes in a context where the method you are invoking expects a single attribute—as is the case, for example, with the yii linking method CHtml::link.
The way round this is to create a new compound attribute in your model. This means taking the two underlying attributes in your table and combining them into a single attribute already arranged the way you want that you can then invoke in other methods. Or in this case, adding something like this to the Person model:
public function getFirstNamesLastName()
{
return $this->firstNames . ' ' . $this->lastName;
}
Once this function is declared, you can invoke it, in exactly the same way you would have invoked the “original” attributes lastName
or [firstNames
], using the attribute name FirstNamesLastName
: e.g.
<?php
CHtml::link(CHtml::encode($data->person->FirstNamesLastName),
array('person/view', 'id'=>$data->person->person_id)); ?>
(Note: there is a much more efficient way of encoding this last example using the same principle. See this post).
Commenting is closed for this article.