Skip to content

Commit fe4fd99

Browse files
committed
Added example in custom filter
Added an example in the Custom Filter section of the documentation to show how to use multiple properties in a custom filter
1 parent 2bc0b43 commit fe4fd99

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

core/filters.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1269,6 +1269,43 @@ class Offer
12691269
}
12701270
```
12711271

1272+
When creating a custom filter you can specify multiple properties of a resource using the usual filter syntax:
1273+
```php
1274+
<?php
1275+
// api/src/Entity/Offer.php
1276+
1277+
namespace App\Entity;
1278+
1279+
use ApiPlatform\Core\Annotation\ApiFilter;
1280+
use ApiPlatform\Core\Annotation\ApiResource;
1281+
use App\Filter\CustomAndFilter;
1282+
1283+
#[ApiResource]
1284+
#[ApiFilter(CustomAndFilter::class, properties={"name", "cost"})]
1285+
class Offer
1286+
{
1287+
// ...
1288+
public string $name;
1289+
public int $cost;
1290+
}
1291+
```
1292+
These properties can then be accessed in the custom filter like this:
1293+
```php
1294+
//App/Filter/CustomAndFilter.php
1295+
protected function filterProperty(string $property, $value, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null) {
1296+
$rootAlias = $queryBuilder->getRootAliases()[0];
1297+
foreach (array_keys($this->getProperties()) as $prop) { //NOTE: we use array_keys because getProperties() returns a map of property => strategy
1298+
if (!$this->isPropertyEnabled($prop, $resourceClass) || !$this->isPropertyMapped($prop, $resourceClass)) {
1299+
return;
1300+
}
1301+
$parameterName = $queryNameGenerator->generateParameterName($prop);
1302+
$queryBuilder
1303+
->andWhere(sprintf('%s.%s LIKE :%s', $rootAlias, $prop, $parameterName))
1304+
->setParameter($parameterName, "%" . $value . "%");
1305+
}
1306+
}
1307+
```
1308+
12721309
#### Manual Service and Attribute Registration
12731310

12741311
If you don't use Symfony's automatic service loading, you have to register the filter as a service by yourself.

0 commit comments

Comments
 (0)