I am mikek's Blog

The personal blog of Mike Karthauser, who you may know from Brightstorm Limited or the internet.

CakePHP virtual Fields

Something pretty useful in the CakePHP right now is VirtualFields.

A virtual field is a way to combine several fields to make a new ‘virtual’ one that exists when you read from the model. So with ‘firstname’ and ‘surname’ you can make a ‘full_name’ field which will allow you to use this within a find(‘list’) – a notoriously tricky task otherwise.

To do this on the User Model for example, just add the following to your app/models/user.php.

var $virtualFields = array(
'full_name' => 'CONCAT(User.firstname, " ", User.surname)'

Simple and powerful.

Available in CakePHP 1.3.*


Filed under: code snippets, , ,

One Response

  1. Guillaume says:

    Though it’s a very easy way to benefit from virtual fields, one big advice I can gie (mentioned in the documentation) is to define them in the Model::__construct() method to avoid problem when using aliases!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

mikek on twitter

Error: Twitter did not respond. Please wait a few minutes and refresh this page.

%d bloggers like this: