Search code examples
phpcakephpcakephp-3.0cakedc

cakeDC Search and checkboxes


I have a search form with a checkbox.

index.ctp

...
echo $this->Form->input('active', 
[
    'label' => 'Select only active users',
]);
...

I'd like the following behavior:

  • if active is unchecked list all records (no condition added to the query)
  • if active is checked list only records where active = true

Instead, because of the hidden field, when active is unchecked a value of 0 is passed to the component and only the records with active = false are showed

if I remove the hidden field:

echo $this->Form->input('active', 
[
    'label' => 'Select only active users',
    'hiddenField' => false
]);

then active=1 is passed in the GET parameters and it's not possible to uncheck the input anymore.

I solved creating my own hidden field instead of the one created by cakephp and setting its value to null

$this->Form->hidden('active', ['value' => ''])

but I don't like this solution. Is there any way to tell cake so set the default value of the hidden field to null or to change the cakeDC Search plugin default behavior when working with checkboxes?


Solution

  • following mark's comment here is the solution

    template file

    ...
    echo $this->Form->input('active', 
    [
        'label' => 'Select only active users',
    ]);
    ...
    

    table file

    $filterArgs = [
        'active' => [
            'name' => 'active',
            'type' => 'value',
        ],
    ]
    

    controller file

    $presetVars = array(
        'active' => [
            'name' => 'afa',
            'type' => 'value',
            'emptyValue' => '0',
        ],
    );
    

    (honestly I still don't understand why we have to set the parameter both in the table file and in the controller)