3

I have a Employee table which display like this:

+-------------------------------+
|  id  |    name    |   code    |
---------------------------------
|  1   | Employee 1 |    A1     |
|  2   | Employee 2 |    A2     |
| ...  |    ...     |   ...     |
+-------------------------------+

And I want to create a filter by code column in this table. My query will be like this:

SELECT name FROM employee WHERE code LIKE .% $filter %.

I searched in backpack document and trying to do like this

$this->crud->addFilter(
    [
        'type' => 'select2',
        'name' => 'code',
        'label' => 'Filter',
    ],
    function () {
        return Employee::select('code')->distinct()->get()->toArray();
    },
    function ($value) {
        $this->crud->addClause('where', 'code', $value);
    }
);

But it got error: htmlspecialchars() expects parameter 1 to be string, array given. How I can fix this?

Thank you very much!

atymic
  • 3,093
  • 1
  • 13
  • 26
Tomato
  • 759
  • 2
  • 14
  • 26
  • Can you post the stack trace of where the `htmlspecialchars` error is coming from? – atymic Jul 20 '19 at 02:48
  • This is my full error: ""htmlspecialchars() expects parameter 1 to be string, array given (View: D:\xampp\htdocs\fox-steps-admin-master\vendor\backpack\crud\src\resources\views\filters\select2.blade.php)" – Tomato Jul 20 '19 at 02:51

1 Answers1

4

Your code to generate the list of employee codes is returning an array like this at the moment, while the package is expecting an array of strings.

[
    ['code' => 'A1'],
    ['code' => 'A2'],
];

To fix the issue, you need to pluck the code column from the array, and key it by the code:

$this->crud->addFilter([
        'type' => 'select2',
        'name' => 'code',
        'label' => 'Filter',
    ],
    function() {
        return Employee::select('code')->distinct()->get()->pluck('code', 'code')->toArray();
    },
    function($value) {
        $this->crud->addClause('where', 'code', $value);
    });

This will result in something like:

[
    'A1' => 'A1',
    'A2' => 'A2',
];
atymic
  • 3,093
  • 1
  • 13
  • 26
  • thanks for your help! I can get the list of code to filter now. But when I choose a code to filter, in my url, it will get the number to filter like this employee?code=0. I need to use the name like employee?code=A1. Can I do this? – Tomato Jul 20 '19 at 03:08
  • Hmm, strange. Could you post the output of the query `Employee::select('code')->distinct()->get()->pluck('code', 'code')->toArray()` – atymic Jul 20 '19 at 05:51
  • You can test it with `php artisan tinker` – atymic Jul 20 '19 at 05:51
  • 1
    it's work! I fixed pluck('code') into pluck('code','code'). Thank you very much! – Tomato Jul 20 '19 at 08:15