1+ <?php
2+ declare (strict_types=1 );
3+
4+ namespace PlumSearch \FormParameter ;
5+
6+ use Cake \Routing \Router ;
7+
8+ /**
9+ * Class LookupParameter
10+ *
11+ * A custom parameter for autocomplete lookups using existing endpoints
12+ *
13+ * @package App\FormParameter
14+ */
15+ class LookupParameter extends BaseParameter
16+ {
17+ /**
18+ * Default configuration
19+ *
20+ * @var array
21+ */
22+ protected $ _defaultConfig = [
23+ 'visible ' => true ,
24+ 'autocompleteUrl ' => null ,
25+ 'idName ' => 'id ' ,
26+ 'valueName ' => 'name ' ,
27+ 'query ' => 'search=%QUERY ' ,
28+ 'wildcard ' => '%QUERY ' ,
29+ 'minLength ' => 2 ,
30+ 'delay ' => 300 ,
31+ ];
32+
33+ /**
34+ * Constructor
35+ *
36+ * @param \PlumSearch\FormParameter\ParameterRegistry $registry ParameterRegistry object.
37+ * @param array $config Object settings.
38+ */
39+ public function __construct (\PlumSearch \FormParameter \ParameterRegistry $ registry , array $ config = [])
40+ {
41+ parent ::__construct ($ registry , $ config );
42+ $ config ['field ' ] = $ config ['name ' ] . '_lookup ' ;
43+ $ this ->setConfig ($ config );
44+ }
45+
46+ /**
47+ * Get autocomplete URL
48+ *
49+ * @return string
50+ */
51+ public function autocompleteUrl (): string
52+ {
53+ $ url = $ this ->getConfig ('autocompleteUrl ' );
54+ if (is_array ($ url )) {
55+ return Router::url ($ url );
56+ }
57+ return (string )$ url ;
58+ }
59+
60+ /**
61+ * Initialize inner parameters
62+ *
63+ * @return void
64+ */
65+ public function initializeInnerParameters (): void
66+ {
67+ $ paramName = $ this ->getConfig ('name ' );
68+ $ this ->_dependentParameters [$ paramName ] = new \PlumSearch \FormParameter \HiddenParameter ($ this ->_registry , [
69+ 'name ' => $ paramName ,
70+ ]);
71+ }
72+
73+ /**
74+ * Build values list
75+ *
76+ * @return array
77+ */
78+ public function values (): array
79+ {
80+ $ name = $ this ->getConfig ('field ' );
81+ $ paramName = $ this ->getConfig ('name ' );
82+ $ param = $ this ->_dependentParameters [$ paramName ];
83+
84+ return [
85+ $ name => $ this ->value (),
86+ $ paramName => $ param ->value (),
87+ ];
88+ }
89+
90+ /**
91+ * Get form input configuration
92+ *
93+ * @return array
94+ */
95+ public function formInputConfig (): array
96+ {
97+ $ config = parent ::formInputConfig ();
98+ $ config ['data-id-name ' ] = $ this ->getConfig ('idName ' );
99+ $ config ['data-value-name ' ] = $ this ->getConfig ('valueName ' );
100+ $ config ['data-query ' ] = $ this ->getConfig ('query ' );
101+ $ config ['data-wildcard ' ] = $ this ->getConfig ('wildcard ' );
102+ $ config ['data-min-length ' ] = $ this ->getConfig ('minLength ' );
103+ $ config ['data-delay ' ] = $ this ->getConfig ('delay ' );
104+ $ config ['data-url ' ] = $ this ->autocompleteUrl ();
105+ $ config ['class ' ] = 'lookup-autocomplete ' ;
106+
107+ return $ config ;
108+ }
109+ }
0 commit comments