Jonathan Petitcolas
Jonathan Petitcolas

Reputation: 4574

Sonata admin: setting a filter to false by default?

I am currently using Sonata Admin to generate a datagrid with an entity having a read boolean field. I would like to filter on this property, setting it by default to false.

So, I added the following to my Admin class:

protected $datagridValues = array(
    'read' => array('value' => false),
);

Yet, it does not seem to work. The generated select list is the following:

<select id="filter_read_value" name="filter[read][value]" class="span8">
    <option value=""></option>
    <option value="1">oui</option>
    <option value="2">non</option>
</select>

I suppose this is normal, as value for false would be 0, which is the empty option.

So, I used some constants such as:

const STATUS_READ = 1;
const STATUS_UNREAD = 2;

It works, but I am wondering if there is any proper solution to avoid these two unnecessary constants?

Upvotes: 2

Views: 3747

Answers (3)

wodka
wodka

Reputation: 1380

the best solution would be to use the types of sonata-admin:

<?php
protected $datagridValues = [
    'read' => [
        'type' => Sonata\CoreBundle\Form\Type\EqualType::TYPE_IS_EQUAL,
        'value' => Sonata\CoreBundle\Form\Type\BooleanType::TYPE_NO,
    ]
];

Upvotes: 0

Baba Yaga
Baba Yaga

Reputation: 1819

You can use getFilterParameters maybe:

<?php
public function getFilterParameters()
{
    $this->datagridValues = array_merge(array(
            'booleanField' => array(
                'value' => '0',
            )
        ),
        $this->datagridValues

    );
    return parent::getFilterParameters();
}

Upvotes: 4

TautrimasPajarskas
TautrimasPajarskas

Reputation: 2796

There is a bit too little information, on how you persist your enumeration into the database, but it is pretty standard to have your value constants stored together with the possible options in your type class. There is nothing wrong in it, as long as you never reference your option as an integer.

Upvotes: 0

Related Questions