Is it possible to create a filter on a calculated field?

Viewed 222

I have an Entity that has a the following schema:

id, name, ..., startDate, endDate

I've also added a calculated field in my entity that gives me the status:

public function getStatus() {
    if (new \DateTime() < $this->getStartDate()) {
        return 'planned';
    }

    if (new \DateTime() > $this->getEndDate()) {
        return 'expired';
    }

    return 'published';
}

What I would like to do is be able to create a filter on this field. I can't seem to find it in the documentation. I've tried creating a filter on it the same way i create filters on other fields, however it doesn't appear in my swagger UI interface.

// config/services.yaml
services:
    ...

    view.search_filter:
        parent: 'api_platform.doctrine.orm.search_filter'
        arguments:
            $properties:
                id: 'exact'
                name: 'ipartial'
                ...
                status: 'exact' // doesn't seem to work
        tags:  [ 'api_platform.filter' ]
        ...

I've also checked out the documentation on writing custom filters, but from what I've seen it has to be an existing property.

1 Answers

The filter you are defining extends an ORM filter (api_platform.doctrine.orm.search_filter), which means that ultimately the filter will be converted to a database query.

Your "calculated field" value is not known until after the row is retrieved, so there is no way the filter can be automatically converted to a query.

You could either add a 'date' filter on startDate and endDate and let users filter using those, or implement one or two custom ORM filters to expose this internal logic to API consumers.

Related