Concat - Combining Two Attributes

Concatenate, concatenation, or concat is a term that describes combining a string, text, or other data in a series without any gaps. If you've 2 tables, user and documents. The user table have few attributes such as firstname and lastname. Then in table documents, you need to display a drop-down menu to select the fullname of the user which required developer to combine the value of firstname and lastname in one input. Assume that your database as shown below:



To call the firstname and lastname as combination of fullname, developer need to use virtual field function to concat the respective field using the virtual field function. In this example, the virtual field concat code should be place at user model as shown below (User Model):

public $virtualFields = array(
	'fullname' => 'CONCAT(User.firstname, " ", User.lastname)' 

$virtualFields will combine firstname and lastname attributes and render it as one attributes (fullname). If you're combining something that required to have a dash (-) between 2 variables, simply add the dash inside the double quotation eg: " - "

Next, to call and display the fullname virtual concat field in document table, simply add the following code to documents controller which called the user list as shown below: (You may remove the existing list code if any)

$users = $this->Document->User->find('list', array(
		'order' => array('User.code' => 'ASC'),
		'fields' => array ('User.fullname')));

Now your user_id input in documents table will render the fullname as configured in user model. Below is an example of concatenation use to combine program code and program name.

Happy coding!