Merge 2 Fields In Gridview And Search

I have a grid view with a Name and a Last Name.I’m trying to marge both fields like this:




			'value'=>function ($data) {

				$value = CHtml::encode($data->name) ." ". ($data->lastname);

				return $value;



I defined a variable called $fullName in my model. It works fine but I cant make the search work. I’ve been looking trough the forums but I can’t find anything clear.

Any ideas?


Make sure you add that variable in your model’s rules() method in the “safe on search” entry.

After that, you can add something like the following to your model’s search() method:

    if ($this->fullName)


        $criteria->addSearchCondition('CONCAT(name, " ", lastname)', $this->fullName);


That should be customised based on how you want the filter to function.

Hi AlexInt,

In order to filter by a concatenated field, you have to use a SQL like the following:

    ... WHERE CONCAT(`name`, ' ', `lastname`) LIKE '%something%' ...

So you have to include a line like the following in your search method:


   $criteria->compare("CONCAT(`name`, ' ', `lastname`)", $this->fullName, true);

Note that what you have done so far work fine only for displaying, because they are concatenating the 2 fields in PHP layer, not in SQL layer. In order to filter by it using CActiveDataProvider, we have to concatenate them in SQL layer.

I didn’t realise that you could use an expression for the column in the compare method. The docs state

where other methods seem to say

The code behind the method seems to accept an expression though, so I’ve learned something new today.

Ah, yes, Keith. "compare" is a convenient pre-processor to "addSearchCondition" and "addInCondition".

Search working with $criteria->addSearchCondition(concat…)


I’d actually recommend Softark’s solution now that I’ve found out it works. It’s a little bit less code because you can do away with the conditional statement.