cnizzardini / cakephp-datatable

CakePHP Component for interoperability between CakePHP 2.x and jQuery DataTables plugin.
62 stars 49 forks source link

Solution to search on virtual fields #36

Open fr0z3nfyr opened 7 years ago

fr0z3nfyr commented 7 years ago

I noticed in your wiki that search feature is not available on virtual fields.

Either, I'm missing something or you fixed the issue but forgot to update wiki (which seems unlikely as there is an open issue #3 regarding this though very old - from 2013). In any case, just wanted to mention that the solution that works flawlessly for me is to create the virtual field in model constructor like below (instead of in controller action as suggested by you in wiki):

    /* Model constructor
    ** create virtual field for all possible model aliases of User model */
    public function __construct($id = false, $table = null, $ds = null) {
        parent::__construct($id, $table, $ds);
        $this->virtualFields['full_name'] = sprintf(
            'CONCAT(%s.first_name, CASE WHEN %s.middle_name = "" OR %s.middle_name IS NULL THEN " " ELSE CONCAT(" ", %s.middle_name, " ") END, %s.last_name)', $this->alias, $this->alias, $this->alias, $this->alias, $this->alias
        );
    }

This is a very raw example of how I create my virtual fields in model, in this example, I concatenated first_name, middle_name and last_name columns.

When i tried to perform a search, the SQL was perfectly formatted as expected and returned correct entries in a very valid JSON for DT to parse. The where conditions in SQL had something like this: ... AND CONCAT(User.first_name, CASE WHEN User.middle_name = "" OR User.middle_name IS NULL THEN " " ELSE CONCAT(" ", User.middle_name, " ") END, User.last_name) LIKE '%test user%' ... which is pretty valid (try on mySQL for yourself).

Hope this helps!