Friday, March 19, 2010

virtualFields in CakePHP 1.3

I found a really handy feature in CakePHP 1.3's Model Attributes. Before 1.3, you were only able to utilize one field in your model with the variable $displayField as illustrated in this link in the 1.2 book.

http://book.cakephp.org/view/438/displayField

This field, for those who aren't aware, are typically used for display of lists within your views. This is usually fine but what about cases where you want to display a concatenated field like "firstname lastname"? Enter CakePHP 1.3's new virtualFields Model attribute. This is a great addition in my book. As most things go with CakePHP, I accidentally stumbled on it. I noted in the 1.3 book included this comment under the information about displayField. "Multiple field names cannot be combined into a single display field. For example, you cannot specify, array('first_name', 'last_name') as the display field. Instead create a virtual field with the Model attribute virtualFields."

I navigated over to the description of this new virtualFields attribute and found exaclty what I was looking for. I placed the following code into my model that I'm currently working on and now all my dropdown menus magically show the my user's first name and last name magically together exactly the way I want them to show up.



class Contact extends AppModel {
var $name = 'Contact';
var $virtualFields = array(
'fullname' => "CONCAT(Contact.firstname,' ',Contact.lastname)"
);
var $displayField = 'fullname';
/* Other model code taken out for brevity. */
}


Note that now I can utilize the new virtual field 'fullname' as the single-dimensioned $displayField variable. I'm loving that because not only can this be utilized for things like lists, but also these variables can be used as a normal part of the model attributes. Remember though, as indicated in the 1.3 book, "Fields added to this property will be read as other fields in a model but will not be saveable."