-
Notifications
You must be signed in to change notification settings - Fork 201
/
InputfieldPageAutocomplete.module
372 lines (315 loc) · 13.9 KB
/
InputfieldPageAutocomplete.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
<?php
/**
* ProcessWire Page Auto Completion select widget
*
* This Inputfield connects the jQuery UI Autocomplete widget with the ProcessWire ProcessPageSearch AJAX API.
*
* ProcessWire 2.x
* Copyright (C) 2015 by Ryan Cramer
* This file licensed under Mozilla Public License v2.0 http://mozilla.org/MPL/2.0/
*
* https://processwire.com
*
* @property int $parent_id Limit results to this parent, or if combined with findPagesSelector, the search is performed as $pages->get($parent_id)->find() rather than $pages->find().
* @property int $template_id Limit results to pages using this template.
* @property string $labelFieldName Field to display in the results. (default=title)
* @property string $labelFieldFormat Format string to display in the results, overrides labelFieldName when used (default=blank).
* @property string $searchFields Field(s) to search for text. Separate multiple by a space. (default=title)
* @property string $operator Selector operator to use in performing the search (default: %=)
* @property string $findPagesSelector Optional selector to use for finding pages (default=blank)
* @property int $maxSelectedItems Maximum number of items that may be selected (0=unlimited, default).
* @property bool $useList Whether or not to use a separate selected list. If false specified, selected item will be populated directly to the input. (default=true)
* @property bool $allowAnyValue Allow any value to stay in the input, even if not selectable? (default=false)
* @property string $disableChars Autocomplete won't be triggered if input contains any of the characters in this string. (default=blank)
* @property bool $useAndWords When true, each word will be isolated to a separate searchFields=searchValue, which enables it to duplicate ~= operator behavior while using a %= operator (default=false).
*
*/
class InputfieldPageAutocomplete extends Inputfield implements InputfieldHasArrayValue {
public static function getModuleInfo() {
return array(
'title' => __('Page Auto Complete', __FILE__), // Module Title
'summary' => __('Multiple Page selection using auto completion and sorting capability. Intended for use as an input field for Page reference fields.', __FILE__), // Module Summary
'version' => 111,
);
}
/**
* Initialize variables used for the autocompletion
*
*/
public function init() {
parent::init();
// limit results to this parent, or if combined with a 'findPagesSelector',
// the search is performed as $pages->get($parent_id)->find() rather than $pages->find()
$this->set('parent_id', 0);
// limit results to pages using this template
$this->set('template_id', 0);
// field to display in the results
$this->set('labelFieldName', 'title');
// format string to display in the results (instead of labelFieldName, when used)
$this->set('labelFieldFormat', '');
// field(s) to search for text, separate multiple by a space
$this->set('searchFields', 'title');
// operator to use in performing the search
$this->set('operator', '%=');
// optional selector to use for all other properties
$this->set('findPagesSelector', '');
// maximum number of items that may be selected
$this->set('maxSelectedItems', 0);
// whether or not to use the selection list
// if not used, selected value will be populated directly to input
$this->set('useList', true);
// allow a non-selectable value to stay in the autocomplete input?
// useful for situations where autocomplete might be used for collection of other values
// like when used with ProcessPageEditLink
$this->set('allowAnyValue', false);
// autocomplete won't be triggered if input contains any characters present in this string
$this->set('disableChars', '');
// when true, each word will be isolated to a separate searchFields=searchValue, which
// enables it to duplicate ~= operator behavior while using a %= operator.
$this->set('useAndWords', false);
}
/**
* Render a selected list item
*
*/
protected function ___renderListItem($label, $value, $class = '') {
if($class) $class = " $class";
if(strpos($label, '&') !== false) $label = $this->wire('sanitizer')->unentities($label);
$label = $this->wire('sanitizer')->entities($label);
$out =
"\n<li class='ui-state-default$class'>" .
"<i class='fa fa-sort fa-fw'></i> " .
"<span class='itemValue'>$value</span>" .
"<span class='itemLabel'>$label</span> " .
"<a class='itemRemove' href='#'><i class='fa fa-trash'></i></a>" .
"</li>";
return $out;
}
/**
* Render the selected items list
*
*/
protected function ___renderList() {
$out = "\n<ol id='{$this->id}_items' data-id='{$this->id}' data-name='{$this->name}'>" . $this->renderListItem("Label", "1", "itemTemplate");
foreach($this->value as $page_id) {
if(!$page_id) continue;
$page = $this->pages->get((int) $page_id);
if(!$page || !$page->id) continue;
$value = $this->labelFieldFormat ? $page->getMarkup($this->labelFieldFormat) : $page->get($this->labelFieldName);
$value = strip_tags($value);
if(!strlen($value)) $value = $page->get('title|name');
$out .= $this->renderListItem($value, $page->id);
}
$out .= "\n</ol>";
return $out;
}
/**
* Render the autocompletion widget
*
*/
public function ___render() {
if($this->maxSelectedItems == 1) $this->useList = false;
$out = $this->useList ? $this->renderList() : '';
$value = implode(',', $this->value);
$url = $this->getAjaxUrl();
// convert our list of search fields to a CSV string for use in the ProcessPageSearch query
$searchField = '';
$searchFields = str_replace(array(',', '|'), ' ', $this->searchFields);
foreach(explode(' ', $searchFields) as $key => $name) {
$name = trim($name);
// @esrch pr#994 --
if(strpos($name, '.')) {
list($name, $subname) = explode('.', $name);
$name = $this->wire('sanitizer')->fieldName($name);
$subname = $this->wire('sanitizer')->fieldName($subname);
if($name && $subname) $name .= "-$subname";
// -- pr#994
} else {
$name = $this->wire('sanitizer')->fieldName($name);
}
if($name) $searchField .= ($searchField ? ',' : '') . $name;
}
if(!$searchField) $searchField = 'title';
$addNote = $this->_('Hit enter to add as new item');
$labelField = $this->labelFieldFormat ? "autocomplete_$this->name" : $this->labelFieldName;
$operator = $this->operator;
$id = $this->id;
$max = (int) $this->maxSelectedItems;
$class = $this->useList ? 'has_list' : 'no_list';
if($this->useAndWords) $class .= " and_words";
if($this->allowAnyValue) $class .= " allow_any";
$disableChars = $this->disableChars;
if($disableChars) {
$hasDoubleQuote = strpos($disableChars, '"') !== false;
$hasSingleQuote = strpos($disableChars, "'") !== false;
if($hasDoubleQuote && $hasSingleQuote) {
$this->error("disableChars cannot have both double and single quotes");
$disableChars = str_replace('"', '', $disableChars);
}
if($hasSingleQuote) $disableChars = "data-disablechars=\"$disableChars\" ";
else $disableChars = "data-disablechars='$disableChars' ";
}
$attrs =
"data-max='$max' " .
"data-url='$url' " .
"data-label='" . $this->wire('sanitizer')->entities($labelField) . "' " .
"data-search='$searchField' " .
"data-operator='$operator'";
$textValue = '';
$remove = '';
if(!$this->useList) {
if(count($this->value)) {
$item = $this->wire('pages')->getById($this->value)->first();
if($item && $item->id) {
$textValue = $this->labelFieldFormat ? $item->getMarkup($this->labelFieldFormat) : $item->get($labelField);
if(!strlen($textValue)) $textValue = $item->get('title|name');
$textValue = strip_tags($textValue);
if(strpos($textValue, '&') !== false) $textValue = $this->wire('sanitizer')->unentities($textValue);
$textValue = $this->wire('sanitizer')->entities($textValue);
}
}
$remove = "<i class='fa fa-fw fa-times-circle InputfieldPageAutocompleteRemove'></i>";
}
$addingLabel = $this->wire('sanitizer')->entities1($this->_('New item:'));
$out .= <<< _OUT
<p>
<input type='hidden' name='{$this->name}[]' id='$id' class='InputfieldPageAutocompleteData' value='$value' $attrs/>
<input type='text' data-parent-input='$id' id='{$id}_input' class='$class' value='$textValue' $disableChars/>
<i class='fa fa-fw fa-angle-double-right InputfieldPageAutocompleteStatus'></i>
$remove
<span class='notes InputfieldPageAutocompleteNote' data-adding='$addingLabel'><br />$addNote</span>
</p>
_OUT;
/*
<script>
$(document).ready(function() {
InputfieldPageAutocomplete.init('$id', '$url', '$labelField', '$searchField', '$operator');
console.log('initAutocomplete: $id');
});
</script>
*/
return $out;
}
/**
* Convert the CSV string provided in the $input to an array of ints needed for this fieldtype
*
*/
public function ___processInput(WireInputData $input) {
parent::___processInput($input);
$value = $this->attr('value');
if(is_array($value)) $value = reset($value);
$value = trim($value);
if(strpos($value, ",") !== false) $value = explode(",", $value);
else if($value) $value = array($value);
else $value = array();
foreach($value as $k => $v) {
$value[$k] = (int) $v;
}
$this->attr('value', $value);
return $this;
}
/**
* Get the AJAX search URL that will be queried (minus the actual term)
*
* This URL is focused on using the AJAX API from ProcessPageSearch
*
*/
protected function getAjaxUrl() {
$selector = $this->findPagesSelector;
if($this->parent_id) {
if($selector) {
// if a selector was specified, AND a parent, then we'll use the parent as a root
$selector .= ",has_parent={$this->parent_id}";
} else {
// otherwise matches must be direct children of the parent
$selector = "parent_id={$this->parent_id}";
}
}
if($this->template_id) {
$selector .= ",templates_id={$this->template_id}";
}
// allow for full site matches
if(!strlen($selector)) $selector = "id>0";
// match no more than 50, unless selector specifies it's own limit
if(strpos($selector, 'limit=') === false) $selector .= ",limit=50";
// replace non-escaped commas with ampersands
$selector = preg_replace('/(?<!\\\\),\s*/', '&', $selector);
if(strpos($selector, '.')) {
// replace things like children.count with children-count since "." is not allowed in URL var names
$selector = preg_replace('/(^|&)([_a-zA-Z0-9]+)\.([_a-zA-Z0-9]+)=/', '$1$2-$3=', $selector);
}
// specify what label field we want to retrieve
if($this->labelFieldFormat) {
$name = "autocomplete_" . $this->attr('name');
$this->wire('modules')->get('ProcessPageSearch')->setDisplayFormat($name, $this->labelFieldFormat);
$selector .= "&format_name=$name";
}
$selector .= "&get=" . $this->labelFieldName;
return $this->config->urls->admin . "page/search/for?" . $selector;
}
/**
* Install the autocomplete module
*
* Make sure we're in InputfieldPage's list of valid page selection widgets
*
*/
public function ___install() {
$data = wire('modules')->getModuleConfigData('InputfieldPage');
$data['inputfieldClasses'][] = $this->className();
wire('modules')->saveModuleConfigData('InputfieldPage', $data);
}
/**
* Uninstall the autocomplete module
*
* Remove from InputfieldPage's list of page selection widgets
*
*/
public function ___uninstall() {
$data = wire('modules')->getModuleConfigData('InputfieldPage');
foreach($data['inputfieldClasses'] as $key => $value) {
if($value == $this->className()) unset($data['inputfieldClasses'][$key]);
}
wire('modules')->saveModuleConfigData('InputfieldPage', $data);
}
/**
* Provide configuration options for modifying the behavior when paired with InputfieldPage
*
*/
public function ___getConfigInputfields() {
$inputfields = parent::___getConfigInputfields();
$fieldset = wire('modules')->get('InputfieldFieldset');
$fieldset->label = $this->_('Autocomplete Advanced Options');
$fieldset->collapsed = Inputfield::collapsedYes;
$recommended = $this->_('Recommended');
$field = $this->modules->get('InputfieldRadios');
$field->setAttribute('name', 'operator');
$field->label = $this->_('Autocomplete search operator');
$field->description = $this->_("The search operator that is used in the API when performing autocomplete matches.");
$field->notes = $this->_("If you aren't sure what you want here, leave it set at the default: *=");
$field->required = false;
$field->addOption('*=', '*= ' . $this->_("Contains phrase or partial word (using fulltext index) - Recommended"));
$field->addOption('%=', '%= ' . $this->_("Contains phrase or partial word (using LIKE)") . " - $recommended");
$field->addOption('~=', '~= ' . $this->_("Contains all the [full] words, in any order"));
$field->addOption('^=', '^= ' . $this->_("Starts with word/phrase"));
$field->addOption('$=', '$= ' . $this->_("Ends with word/phrase"));
$field->addOption('=', '= ' . $this->_("Equals [exact]"));
$field->attr('value', $this->operator);
$field->collapsed = Inputfield::collapsedNo;
$fieldset->add($field);
$field = $this->modules->get('InputfieldText');
$field->attr('name', 'searchFields');
$field->label = $this->_('Fields to query for autocomplete');
$field->description = $this->_('Enter the names of the fields that should have their text queried for autocomplete matches. Typically this would just be the title field, but you may add others by separating each with a space. Note that this is different from the "Label Field" (above). Here you are specifying what fields will be searched, not what fields will be shown.');
$field->collapsed = Inputfield::collapsedNo;
$field->attr('value', $this->searchFields);
$notes = $this->_('Indexed text fields include:');
foreach(wire('fields') as $f) {
if(!$f->type instanceof FieldtypeText) continue;
$notes .= ' ' . $f->name . ',';
}
$field->notes = rtrim($notes, ',');
$fieldset->add($field);
$inputfields->add($fieldset);
return $inputfields;
}
}