1+ <?php
2+
3+ namespace HeimrichHannot \CategoriesBundle \Flare \FilterElement ;
4+
5+ use Contao \StringUtil ;
6+ use HeimrichHannot \CategoriesBundle \Model \CategoryModel ;
7+ use HeimrichHannot \FlareBundle \DependencyInjection \Attribute \AsFilterElement ;
8+ use HeimrichHannot \FlareBundle \Filter \FilterContext ;
9+ use HeimrichHannot \FlareBundle \Filter \FilterQueryBuilder ;
10+ use HeimrichHannot \FlareBundle \FilterElement \AbstractFilterElement ;
11+ use HeimrichHannot \FlareBundle \Form \ChoicesBuilder ;
12+ use Symfony \Component \Form \Extension \Core \Type \ChoiceType ;
13+
14+ #[AsFilterElement(
15+ alias: self ::TYPE ,
16+ palette: '{fieldGeneric_legend},fieldGeneric,filterCategory;{form_legend},placeholder ' ,
17+ formType: ChoiceType::class,
18+ )]
19+ class ParentCategoryFilterElement extends AbstractFilterElement
20+ {
21+ public const TYPE = 'parent_category ' ;
22+
23+ public function __invoke (FilterContext $ context , FilterQueryBuilder $ qb ): void
24+ {
25+ if (!$ context ->getSubmittedData ()) {
26+ return ;
27+ }
28+
29+ if (!$ targetField = $ context ->getFilterModel ()->fieldGeneric ) {
30+ $ qb ->abort ();
31+ }
32+
33+ $ qb ->where ($ qb ->expr ()->like ($ targetField , ':category ' ))
34+ ->setParameter ('category ' , '%" ' . $ context ->getSubmittedData () . '"% ' );
35+ }
36+
37+ public function getFormTypeOptions (FilterContext $ context , ChoicesBuilder $ choices ): array
38+ {
39+ $ options = $ this ->defaultFormTypeOptions (
40+ $ context ,
41+ ['placeholder ' => true ]
42+ );
43+ $ options ['choices ' ] = [];
44+
45+ $ categoryIds = StringUtil::deserialize ($ context ->getFilterModel ()->filterCategory , true );
46+
47+ if (empty ($ categoryIds )) {
48+ return $ options ;
49+ }
50+
51+ $ categories = CategoryModel::findByPids ($ categoryIds );
52+
53+ while ($ categories ->next ()) {
54+ $ options ['choices ' ][$ categories ->title ] = (string ) $ categories ->id ;
55+ }
56+
57+ return $ options ;
58+ }
59+ }
0 commit comments