-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwidget.php
More file actions
355 lines (310 loc) · 14.7 KB
/
Copy pathwidget.php
File metadata and controls
355 lines (310 loc) · 14.7 KB
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
<?php
/**
* FormTool handler per widget mobile_lookup
*
* Gestisce la costruzione del widget mobile_lookup per campi in fields.ini
*
* @author plcats
*/
require_once dirname(__FILE__) . '/ml_lookup_util.php';
$GLOBALS['HTML_QUICKFORM_ELEMENT_TYPES']['mobile_lookup'] = array(
dirname(__FILE__) . DIRECTORY_SEPARATOR . 'QuickForm_mobile_lookup.php',
'HTML_QuickForm_mobile_lookup'
);
class Dataface_FormTool_mobile_lookup
{
/**
* Risolve il nome base del campo record anche in contesti grid
* (es. fk_item[0] -> fk_item).
*/
private function resolveBaseFieldName($fieldName)
{
if (!is_scalar($fieldName)) {
return '';
}
$name = trim((string) $fieldName);
if ($name === '') {
return '';
}
$bracketPos = strpos($name, '[');
if ($bracketPos !== false) {
$name = substr($name, 0, $bracketPos);
}
return $name;
}
/**
* Unisce widget:filters:* e chiave filters[] per il JSON passato al JS.
*/
private function extractWidgetFilters(&$widget)
{
$filters = array();
if (isset($widget['filters']) && is_array($widget['filters'])) {
$filters = $widget['filters'];
}
foreach ($widget as $key => $value) {
if (!is_string($key) || strpos($key, 'filters:') !== 0) {
continue;
}
$filterKey = substr($key, 8);
if ($filterKey === '' || ($filterKey[0] === '-' && $filterKey !== '-sort')) {
continue;
}
$filters[$filterKey] = $value;
}
return $filters;
}
/**
* Legge il valore grezzo (chiave FK) del campo.
*
* Usare getValue()/strval(), come il value attribute dell'input lookup nativo.
*/
private function resolveCurrentValue(&$record, $fieldBase)
{
if ($fieldBase === '') {
return '';
}
$delegate = $record->_table->getDelegate();
if ($delegate !== null && method_exists($delegate, $fieldBase . '__pullValue')) {
$method = $fieldBase . '__pullValue';
$pullVal = $delegate->$method($record, null);
if ($pullVal !== null && $pullVal !== false) {
return is_scalar($pullVal) ? (string) $pullVal : '';
}
return '';
}
$currentValue = '';
$rawCurrentValue = $record->getValue($fieldBase);
if ($rawCurrentValue !== null && $rawCurrentValue !== false && is_scalar($rawCurrentValue)) {
$currentValue = trim((string) $rawCurrentValue);
}
if ($currentValue === '') {
$currentValue = trim((string) $record->strval($fieldBase));
}
return $currentValue;
}
/**
* Costruisce il widget mobile_lookup
*
* @param Dataface_Record $record Record corrente
* @param array $field Definizione campo da fields.ini
* @param HTML_QuickForm $form Form oggetto
* @param string $formFieldName Nome del campo nel form
* @param bool $new Se è un nuovo record
* @return HTML_QuickForm_mobile_lookup Widget element
*/
function &buildWidget(&$record, &$field, &$form, $formFieldName, $new = false)
{
static $tableMetaCache = array();
static $seedOptionsCache = array();
static $currentValueLabelCache = array();
$widget =& $field['widget'];
$factory =& Dataface_FormTool::factory();
// Nel form filtri (find) evita preload AJAX/Select2: i campi testo/vocabulary
// dedicati al find coprono la ricerca senza caricare le lookup complete.
$app = Dataface_Application::getInstance();
$currentAction = (isset($app->_query['-action']) && is_scalar($app->_query['-action']))
? strtolower(trim((string) $app->_query['-action']))
: '';
if ($currentAction === 'find') {
$widget['preloadOptions'] = 'none';
}
$tableNameFromWidget = (isset($widget['table']) && is_scalar($widget['table'])) ? trim((string) $widget['table']) : '';
$hasLookupTable = ($tableNameFromWidget !== '');
$requestedPreloadRaw = (isset($widget['preloadOptions']) && is_scalar($widget['preloadOptions'])) ? (string) $widget['preloadOptions'] : 'selected';
$requestedPreloadMode = strtolower(trim($requestedPreloadRaw));
if (!in_array($requestedPreloadMode, array('selected', 'first100', 'none'))) {
$requestedPreloadMode = 'selected';
}
// mobile_lookup usa solo widget:table (+ keycol/labelcol). Il vocabulary
// del campo (valuelists.ini) non e' supportato: in grid puo' azzerare
// il valore FK e duplica la logica gia' coperta da AJAX.
$options = array();
$currentFieldName = isset($field['name']) ? $field['name'] : $formFieldName;
$currentFieldBase = $this->resolveBaseFieldName($currentFieldName);
$currentValue = $this->resolveCurrentValue($record, $currentFieldBase);
if ($hasLookupTable) {
// Se non c'è vocabulary, costruisci opzioni dalla tabella target
// Supporta labelcol multipli o usa title del record
$targetTable = $tableNameFromWidget;
$keyCol = isset($widget['keycol']) ? $widget['keycol'] : '';
$labelCol = isset($widget['labelcol']) ? $widget['labelcol'] : '';
$labelColExpression = '';
$useLabelExpression = false;
$tableMetaKey = $targetTable;
// Strategia preload per ridurre overhead in grid:
// - selected (default): carica solo la label del valore corrente
// - first100: carica prime 100 opzioni + valore corrente
// - none: non carica opzioni iniziali
$preloadMode = $requestedPreloadMode;
if (!in_array($preloadMode, array('selected', 'first100', 'none'))) {
$preloadMode = 'selected';
}
$targetTableObj = null;
if (!isset($tableMetaCache[$tableMetaKey])) {
$tableMetaCache[$tableMetaKey] = array(
'loaded' => false,
'obj' => null,
'defaultKey' => 'id',
'canEdit' => 0,
'canNew' => 0,
'titleColumn' => null,
'tableSql' => ''
);
try {
$targetTableObj = Dataface_Table::loadTable($targetTable);
$keys = $targetTableObj->keys();
$keyNames = array_keys($keys);
$defaultKey = !empty($keyNames) ? $keyNames[0] : 'id';
$tablePerms = $targetTableObj->getPermissions();
$tableMetaCache[$tableMetaKey] = array(
'loaded' => true,
'obj' => $targetTableObj,
'defaultKey' => $defaultKey,
'canEdit' => !empty($tablePerms['edit']) ? 1 : 0,
'canNew' => !empty($tablePerms['new']) ? 1 : 0,
'titleColumn' => $targetTableObj->titleColumn(),
'tableSql' => $targetTableObj->sql()
);
} catch (Exception $e) {
// Keep safe defaults.
}
}
$meta = $tableMetaCache[$tableMetaKey];
if (empty($keyCol)) {
$keyCol = $meta['defaultKey'];
$widget['keycol'] = $keyCol;
}
// Calcola permessi per pulsanti modifica/nuovo se non forzati in fields.ini.
if (!isset($widget['canEdit']) || $widget['canEdit'] === '') {
$widget['canEdit'] = $meta['canEdit'];
}
if (!isset($widget['canNew']) || $widget['canNew'] === '') {
$widget['canNew'] = $meta['canNew'];
}
$targetTableObj = $meta['obj'];
// title=1 / widget:useTitle=1: risolvi subito (serve per label valore corrente).
$useTitleForLookup = !empty($field['title']) || !empty($widget['useTitle']);
if ($useTitleForLookup) {
$widget['useTitle'] = 1;
}
$needsSeedOptions = ($preloadMode === 'first100');
// Anche con preload=none va mantenuta la label del valore corrente,
// altrimenti in edit/grid i record gia' selezionati risultano vuoti.
$needsCurrentValueLabel = ($currentValue !== null && $currentValue !== '');
if ($needsSeedOptions || $needsCurrentValueLabel) {
$link = xf_ml_resolve_db_link();
$lookupFrom = xf_ml_resolve_lookup_from($targetTable);
$tableSql = $lookupFrom['tableSql'];
$fromClause = $lookupFrom['fromClause'];
if ($link) {
// Se labelcol è vuoto, usa il title del record
if (empty($labelCol)) {
if (!empty($meta['titleColumn'])) {
$labelColExpression = $meta['titleColumn'];
$useLabelExpression = true;
} else {
$labelCol = 'id';
}
}
$seedCacheKey = $targetTable . '|' . $keyCol . '|' . $labelCol . '|' . ($useLabelExpression ? 'title' : 'cols');
if ($needsSeedOptions) {
if (!isset($seedOptionsCache[$seedCacheKey])) {
$seedOptionsCache[$seedCacheKey] = array();
if ($useLabelExpression) {
$keySafe = preg_match('/^[a-zA-Z0-9_]+$/', $keyCol) ? "`$keyCol`" : '`id`';
$labelSelect = "($labelColExpression) as label";
$sql = "SELECT $keySafe as keyval, $labelSelect FROM $fromClause ORDER BY $keySafe LIMIT 100";
$result = mysqli_query($link, $sql);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$seedOptionsCache[$seedCacheKey][$row['keyval']] = $row['label'];
}
mysqli_free_result($result);
}
} else {
// Supporto labelcol multipli
$labelCols = array_map('trim', explode(',', $labelCol));
$labelColsSafe = array();
foreach ($labelCols as $col) {
if (preg_match('/^[a-zA-Z0-9_]+$/', $col)) {
$labelColsSafe[] = "`$col`";
}
}
if (!empty($labelColsSafe)) {
$keySafe = preg_match('/^[a-zA-Z0-9_]+$/', $keyCol) ? "`$keyCol`" : '`id`';
if (count($labelColsSafe) > 1) {
$labelSelect = "CONCAT_WS(' - ', " . implode(', ', $labelColsSafe) . ") as label";
} else {
$labelSelect = "$labelColsSafe[0] as label";
}
$sql = "SELECT $keySafe as keyval, $labelSelect FROM $fromClause ORDER BY $labelColsSafe[0] LIMIT 100";
$result = mysqli_query($link, $sql);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$seedOptionsCache[$seedCacheKey][$row['keyval']] = $row['label'];
}
mysqli_free_result($result);
}
}
}
}
if (!empty($seedOptionsCache[$seedCacheKey])) {
$options = $options + $seedOptionsCache[$seedCacheKey];
}
}
// Se il valore corrente non è presente (o useTitle), risolvi la label
if ($needsCurrentValueLabel && ($useTitleForLookup || !array_key_exists($currentValue, $options))) {
$currentLabelCacheKey = $seedCacheKey . '|val|' . $currentValue . ($useTitleForLookup ? '|title' : '');
if (!isset($currentValueLabelCache[$currentLabelCacheKey])) {
$currentValueLabelCache[$currentLabelCacheKey] = xf_ml_lookup_label_for_value(
$targetTable,
$keyCol,
$labelCol,
$currentValue,
$useTitleForLookup
);
}
$options[$currentValue] = $currentValueLabelCache[$currentLabelCacheKey];
}
}
}
}
// Crea elemento custom mobile_lookup con le opzioni
$widgetLabel = isset($widget['label']) ? $widget['label'] : $formFieldName;
$el =& $factory->addElement('mobile_lookup', $formFieldName, $widgetLabel, $options);
if (PEAR::isError($el)) {
return $el;
}
// Imposta proprietà widget da fields.ini
if (!empty($field['title']) || !empty($widget['useTitle'])) {
$widget['useTitle'] = 1;
}
$widgetFilters = $this->extractWidgetFilters($widget);
if (!empty($widgetFilters)) {
$widget['filters'] = $widgetFilters;
}
$el->setProperties($widget);
return $el;
}
/**
* Nessun pullValue: come la lookup standard Xataface, il valore cella grid
* passa intatto da grid_filter (passthrough del colval). Un pullValue custom
* alterava i valori in grid (comportamento diverso dalla lookup standard).
*
* @see Dataface_FormTool_grid_filter::pullValue()
* @see Dataface_FormTool::pullField() per campi standalone (getValueAsString)
*/
/**
* Estrae il valore dal form (widget) per salvarlo nel record (form -> record).
* In Xataface questo metodo si chiama pushValue.
*/
function pushValue(&$record, &$field, &$form, &$element, $new = false)
{
$val = $element->getValue();
// Se è un array (come può succedere con select in POST ma trattata come text), prendi il primo valore
if (is_array($val)) {
$val = reset($val);
}
return $val;
}
}