forked from pollen8/fabrik
/
cascadingdropdown.php
1323 lines (1148 loc) · 37 KB
/
cascadingdropdown.php
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Plugin element to render cascading dropdown
*
* @package Joomla.Plugin
* @subpackage Fabrik.element.cascadingdropdown
* @copyright Copyright (C) 2005-2015 fabrikar.com - All rights reserved.
* @license GNU/GPL http://www.gnu.org/copyleft/gpl.html
*/
// No direct access
defined('_JEXEC') or die('Restricted access');
require_once JPATH_SITE . '/plugins/fabrik_element/databasejoin/databasejoin.php';
/**
* Plugin element to render cascading drop-down
*
* @package Joomla.Plugin
* @subpackage Fabrik.element.cascadingdropdown
* @since 3.0
*/
class PlgFabrik_ElementCascadingdropdown extends PlgFabrik_ElementDatabasejoin
{
/**
* J Parameter name for the field containing the label value
*
* @var string
*/
protected $labelParam = 'cascadingdropdown_label';
/**
* J Parameter name for the field containing the concat label
*
* @var string
*/
protected $concatLabelParam = 'cascadingdropdown_label_concat';
/**
* Returns javascript which creates an instance of the class defined in formJavascriptClass()
*
* @param int $repeatCounter Repeat group counter
*
* @return array
*/
public function elementJavascript($repeatCounter)
{
$input = $this->app->input;
$id = $this->getHTMLId($repeatCounter);
$params = $this->getParams();
if ($this->getDisplayType() === 'auto-complete')
{
$autoOpts = array();
$autoOpts['observerid'] = $this->getWatchId($repeatCounter);
$autoOpts['formRef'] = $this->getFormModel()->jsKey();
$autoOpts['storeMatchedResultsOnly'] = true;
FabrikHelperHTML::autoComplete($id, $this->getElement()->id, $this->getFormModel()->getId(), 'cascadingdropdown', $autoOpts);
}
FabrikHelperHTML::script('media/com_fabrik/js/lib/Event.mock.js');
$opts = $this->getElementJSOptions($repeatCounter);
$opts->showPleaseSelect = $this->showPleaseSelect();
$opts->watch = $this->getWatchId($repeatCounter);
$watchElementModel = $this->getWatchElement();
$opts->watchChangeEvent = $watchElementModel->getChangeEvent();
$opts->displayType = $params->get('cdd_display_type', 'dropdown');
$opts->id = $this->getId();
$opts->listName = $this->getListModel()->getTable()->db_table_name;
// This bizarre chunk of code handles the case of setting a CDD value on the QS on a new form
$rowId = $input->get('rowid', '', 'string');
$fullName = $this->getFullName();
$watchName = $this->getWatchFullName();
// If returning from failed posted validation data can be in an array
$qsValue = $input->get($fullName, array(), 'array');
$qsValue = FArrayHelper::getValue($qsValue, 0, null);
$qsWatchValue = $input->get($watchName, array(), 'array');
$qsWatchValue = FArrayHelper::getValue($qsWatchValue, 0, null);
$useQsValue = $this->getFormModel()->hasErrors() && $this->isEditable() && $rowId === '' && !empty($qsValue) && !empty($qsWatchValue);
$opts->def = $useQsValue ? $qsValue : $this->getValue(array(), $repeatCounter);
// $$$ hugh - for reasons utterly beyond me, after failed validation, getValue() is returning an array.
if (is_array($opts->def) && !empty($opts->def))
{
$opts->def = $opts->def[0];
}
$watchGroup = $this->getWatchElement()->getGroup()->getGroup();
$group = $this->getGroup()->getGroup();
$opts->watchInSameGroup = $watchGroup->id === $group->id;
$opts->editing = ($this->isEditable() && $rowId !== '');
$opts->showDesc = $params->get('cdd_desc_column', '') === '' ? false : true;
$opts->advanced = $this->getAdvancedSelectClass() != '';
$formId = $this->getFormModel()->getId();
$opts->autoCompleteOpts = $opts->displayType == 'auto-complete'
? FabrikHelperHTML::autoCompleteOptions($opts->id, $this->getElement()->id, $formId, 'cascadingdropdown') : null;
$this->elementJavascriptJoinOpts($opts);
$data = $this->getFormModel()->data;
// Was otherwise using the none-raw value.
$opts->value = $this->getValue($data, $repeatCounter, array('raw' => true));
if (is_array($opts->value) && count($opts->value) > 0)
{
$opts->value = JArrayHelper::getValue($opts->value, 0);
}
return array('FbCascadingdropdown', $id, $opts);
}
/**
* Get the field name to use as the column that contains the join's label data
*
* @param bool $useStep use step in element name
*
* @return string join label column either returns concat statement or quotes `tablename`.`elementname`
*/
public function getJoinLabelColumn($useStep = false)
{
$params = $this->getParams();
$join = $this->getJoin();
$db = $this->getDb();
if (($params->get('cascadingdropdown_label_concat') != '') && $this->app->input->get('override_join_val_column_concat') != 1)
{
$val = $params->get('cascadingdropdown_label_concat');
if ($join)
{
$val = $this->parseThisTable($val, $join);
}
$w = new FabrikWorker;
$val = $w->parseMessageForPlaceHolder($val, array());
return 'CONCAT_WS(\'\', ' . $val . ')';
}
$label = FabrikString::shortColName($join->params->get('join-label'));
if ($label == '')
{
// This is being raised with checkbox rendering and using drop-down filter, everything seems to be working with using the element name though!
// JError::raiseWarning(500, 'Could not find the join label for ' . $this->getElement()->name . ' try unlinking and saving it');
$label = $this->getElement()->name;
}
if ($this->isJoin())
{
$joinTableName = $this->getDbName();
$label = $this->getLabelParamVal();
}
else
{
$joinTableName = $join->table_join_alias;
}
return $useStep ? $joinTableName . '___' . $label : $db->qn($joinTableName . '.' . $label);
}
/**
* Reset cached data, needed when rendering table if CDD
* is in repeat group, so we can build optionVals
*
* @deprecated - not used
*
* @return void
*/
protected function _resetCache()
{
unset($this->optionVals);
unset($this->sql);
}
/**
* Draws the html form element
*
* @param array $data to pre-populate element with
* @param int $repeatCounter repeat group counter
*
* @return string elements html
*/
public function render($data, $repeatCounter = 0)
{
$db = $this->getDb();
$params = $this->getParams();
$name = $this->getHTMLName($repeatCounter);
$opts = array('raw' => 1);
$default = (array) $this->getValue($data, $repeatCounter, $opts);
/* $$$ rob don't bother getting the options if editable as the js event is going to get them.
* However if in readonly mode the we do need to get the options
* $$$ hugh - need to rethink this approach, see ticket #725. When editing, we need
* to build options and selection on server side, otherwise daisy chained CDD's don't
* work due to timing issues in JS between onComplete and get_options calls.
* $tmp = $this->isEditable() ? array() : $this->_getOptions($data);
* So ... we want to get options if not editable, or if editing an existing row.
* See also small change to attachedToForm() in JS, and new 'editing' option in
* elementJavascript() above, so the JS won't get options on init when editing an existing row
*/
$tmp = array();
$rowId = $this->app->input->string('rowid', '', 'string');
$showPlease = $this->showPleaseSelect();
// $$$ hugh testing to see if we need to load options after a validation failure, but I don't think we do, as JS will reload via AJAX
if (!$this->isEditable() || ($this->isEditable() && $rowId !== ''))
{
$tmp = $this->_getOptions($data, $repeatCounter);
}
else
{
if ($showPlease)
{
$tmp[] = $this->selectOption();
}
}
$imageOpts = array('alt' => FText::_('PLG_ELEMENT_CALC_LOADING'), 'style' => 'display:none;padding-left:10px;', 'class' => 'loader');
$this->loadingImg = FabrikHelperHTML::image('ajax-loader.gif', 'form', @$this->tmpl, $imageOpts);
// Get the default label for the drop down (use in read only templates)
$defaultLabel = '';
$defaultValue = '';
foreach ($tmp as $obj)
{
if (in_array($obj->value, $default))
{
$defaultValue = $obj->value;
$defaultLabel = $obj->text;
break;
}
}
$id = $this->getHTMLId($repeatCounter);
$class = 'fabrikinput inputbox ' . $params->get('bootstrap_class', '');
$disabled = '';
if (count($tmp) == 1)
{
$class .= ' readonly';
// Selects don't have readonly properties !
}
$w = new FabrikWorker;
$default = $w->parseMessageForPlaceHolder($default);
$displayType = $params->get('cdd_display_type', 'dropdown');
$html = array();
if ($this->canUse())
{
// $$$ rob display type not set up in parameters as not had time to test fully yet
switch ($displayType)
{
case 'checkbox':
$this->renderCheckBoxList($data, $repeatCounter, $html, $tmp, $default);
$defaultLabel = implode("\n", $html);
break;
case 'radio':
$this->renderRadioList($data, $repeatCounter, $html, $tmp, $default);
$defaultLabel = implode("\n", $html);
break;
case 'multilist':
$this->renderMultiSelectList($data, $repeatCounter, $html, $tmp, $default);
$defaultLabel = implode("\n", $html);
break;
case 'auto-complete':
$this->renderAutoComplete($data, $repeatCounter, $html, $default);
break;
default:
case 'dropdown':
// Jaanus: $maxWidth to avoid drop-downs become too large (when choosing options they would still be of their full length
$maxWidth = $params->get('max-width', '') === '' ? '' : ' style="max-width:' . $params->get('max-width') . ';"';
$advancedClass = $this->getAdvancedSelectClass();
$attributes = 'class="' . $class . ' ' . $advancedClass . '" ' . $disabled . ' size="1"' . $maxWidth;
$html[] = JHTML::_('select.genericlist', $tmp, $name, $attributes, 'value', 'text', $default, $id);
break;
}
$html[] = $this->loadingImg;
$html[] = ($displayType == 'radio') ? '</div>' : '';
}
if (!$this->isEditable())
{
if ($params->get('cascadingdropdown_readonly_link') == 1)
{
$listId = (int) $params->get('cascadingdropdown_table');
if ($listId !== 0)
{
$query = $db->getQuery(true);
$query->select('form_id')->from('#__{package}_lists')->where('id = ' . $listId);
$db->setQuery($query);
$popupFormId = $db->loadResult();
$url = 'index.php?option=com_fabrik&view=details&formid=' . $popupFormId . '&listid=' . $listId . '&rowid=' . $defaultValue;
$defaultLabel = '<a href="' . JRoute::_($url) . '">' . $defaultLabel . '</a>';
}
}
return $defaultLabel . $this->loadingImg;
}
$html[] = $this->renderDescription($tmp, $default);
return implode("\n", $html);
}
/**
* Add the description to the element's form HTML
*
* @param array $options Select options
* @param array $default Default values
*
* @return string
*/
protected function renderDescription($options = array(), $default = array())
{
$params = $this->getParams();
if ($params->get('cdd_desc_column', '') !== '')
{
$layout = $this->getLayout('form-description');
$displayData = new stdClass;
$displayData->opts = $options;
$displayData->default = FArrayHelper::getValue($default, 0);
$displayData->showPleaseSelect = $this->showPleaseSelect();
return $layout->render($displayData);
}
return '';
}
/**
* Does the element store its data in a join table (1:n)
*
* @return bool
*/
public function isJoin()
{
if (in_array($this->getDisplayType(), array('checkbox', 'multilist')))
{
return true;
}
else
{
return parent::isJoin();
}
}
/**
* Get the display type (list,checkbox,multiselect etc.)
*
* @since 3.0.7
*
* @return string
*/
protected function getDisplayType()
{
return $this->getParams()->get('cdd_display_type', 'dropdown');
}
/**
* Get a list of the HTML options used in the database join drop down / radio buttons
*
* @param array $data From current record (when editing form?)
* @param int $repeatCounter Repeat group counter
* @param bool $incWhere Do we include custom where in query
* @param array $opts Additional options passed into _getOptionVals()
*
* @return array option objects
*/
protected function _getOptions($data = array(), $repeatCounter = 0, $incWhere = true, $opts = array())
{
$tmp = $this->_getOptionVals($data, $repeatCounter);
return $tmp;
}
/**
* Gets the options for the drop down - used in package when forms update
*
* @return void
*/
public function onAjax_getOptions()
{
$input = $this->app->input;
$filterView = $input->get('filterview', '');
$this->loadMeForAjax();
/**
* $$$ hugh -added test for $filterView, and only do filter stuff if we are being
* called in a filter context, not in a regular form display context.
*/
if (!empty($filterView) && $this->getFilterBuildMethod() == 1)
{
// Get distinct records which have already been selected: http://fabrikar.com/forums/showthread.php?t=30450
$listModel = $this->getListModel();
$db = $listModel->getDb();
$obs = $this->getWatchElement();
$obsName = $obs->getFullName(false, false);
// From a filter...
if ($input->get('fabrik_cascade_ajax_update') == 1)
{
$obsValue = $input->get('v', array(), 'array');
}
else
{
// Standard
$obsValue = (array) $input->get($obs->getFullName(true, false) . '_raw');
}
foreach ($obsValue as &$v)
{
$v = $db->quote($v);
}
$where = $obsName . ' IN (' . implode(',', $obsValue) . ')';
$opts = array('where' => $where);
$ids = $listModel->getColumnData($this->getFullName(false, false), true, $opts);
$key = $this->queryKey();
if (is_array($ids))
{
array_walk($ids, create_function('&$val', '$db = JFactory::getDbo();$val = $db->quote($val);'));
$this->autocomplete_where = empty($ids) ? '1 = -1' : $key . ' IN (' . implode(',', $ids) . ')';
}
}
$filter = JFilterInput::getInstance();
$data = $filter->clean($_POST, 'array');
$opts = $this->_getOptionVals($data);
$this->_replaceAjaxOptsWithDbJoinOpts($opts);
echo json_encode($opts);
}
/**
* Test for db join element - if so update option labels with related join labels
*
* @param array &$opts standard options
*
* @return void
*/
protected function _replaceAjaxOptsWithDbJoinOpts(&$opts)
{
$groups = $this->getFormModel()->getGroupsHiarachy();
$watch = $this->getWatchFullName();
foreach ($groups as $groupModel)
{
$elementModels = $groupModel->getPublishedElements();
foreach ($elementModels as $elementModel)
{
$fullName = $elementModel->getFullName();
if ($fullName == $watch)
{
/**
* $$$ hugh - not sure what this is for, but changed class name to 3.x name,
* as it was still set to the old 2.1 naming.
*/
if (get_parent_class($elementModel) == 'plgFabrik_ElementDatabasejoin')
{
$data = array();
/** @var plgFabrik_ElementDatabasejoin $elementModel */
$joinOpts = $elementModel->_getOptions($data);
}
/**
* $$$ hugh - I assume we can break out of both foreach now, as there shouldn't
* be more than one match for the $watch element.
*/
break 2;
}
}
}
if (isset($joinOpts))
{
$matrix = array();
foreach ($joinOpts as $j)
{
$matrix[$j->value] = $j->text;
}
foreach ($opts as &$opt)
{
if (array_key_exists($opt->text, $matrix))
{
$opt->text = $matrix[$opt->text];
}
}
}
}
/**
* Get array of option values
*
* @param array $data Data
* @param int $repeatCounter Repeat group counter
* @param bool $incWhere Do we add custom where statement into sql
* @param array $opts Additional options passed into buildQuery()
*
* @return array option values
*/
protected function _getOptionVals($data = array(), $repeatCounter = 0, $incWhere = true, $opts = array())
{
$params = $this->getParams();
if (!isset($this->optionVals))
{
$this->optionVals = array();
}
$db = $this->getDb();
$opts = array();
$opts['repeatCounter'] = $repeatCounter;
$sql = $this->buildQuery($data, $incWhere, $opts);
$sqlKey = (string) $sql;
$sqlKey .= $this->isEditable() ? '0' : '1';
$eval = $params->get('cdd_join_label_eval', '');
if (trim($eval) === '' && array_key_exists($sqlKey, $this->optionVals))
{
return $this->optionVals[$sqlKey];
}
$db->setQuery($sql);
FabrikHelperHTML::debug((string) $db->getQuery(), 'cascadingdropdown _getOptionVals');
$this->optionVals[$sqlKey] = $db->loadObjectList();
if (trim($eval) !== '')
{
foreach ($this->optionVals[$sqlKey] as $key => &$opt)
{
// Allow removing an option by returning false
if (eval($eval) === false)
{
unset($this->optionVals[$sqlKey][$key]);
}
}
}
/*
* If it's a filter, need to use filterSelectLabel() regardless of showPleaseSelect()
* (should probably shift this logic into showPleaseSelect, and have that just do this
* test, and return the label to use.
*/
$filterView = $this->app->input->get('filterview', '');
if ($filterView == 'table')
{
array_unshift($this->optionVals[$sqlKey], JHTML::_('select.option', $params->get('cascadingdropdown_noselectionvalue', ''), $this->filterSelectLabel()));
}
else
{
if ($this->showPleaseSelect())
{
array_unshift($this->optionVals[$sqlKey], $this->selectOption());
}
}
// Remove tags from labels
if ($this->canUse() && in_array($this->getDisplayType(), array('multilist', 'dropdown')))
{
foreach ($this->optionVals[$sqlKey] as $key => &$opt)
{
$opt->text = strip_tags($opt->text);
}
}
return $this->optionVals[$sqlKey];
}
/**
* Create the select option for drop-down
*
* @return object
*/
private function selectOption()
{
$params = $this->getParams();
return JHTML::_('select.option', $params->get('cascadingdropdown_noselectionvalue', ''), $this->_getSelectLabel());
}
/**
* Do you add a please select option to the cdd list
*
* @since 3.0b
*
* @return bool
*/
protected function showPleaseSelect()
{
$params = $this->getParams();
if (!$this->canUse())
{
return false;
}
if (!$this->isEditable())
{
return false;
}
if (in_array($this->getDisplayType(), array('checkbox', 'multilist', 'radio')))
{
return false;
}
return (bool) $params->get('cascadingdropdown_showpleaseselect', true);
}
/**
* Get the full name of the element to observe. When this element changes
* state, the cdd should perform an ajax lookup to update its options
*
* @return string
*/
protected function getWatchFullName()
{
$elementModel = $this->getWatchElement();
return $elementModel->getFullName();
}
/**
* Get the HTML id for the watch element
*
* @param int $repeatCounter repeat group counter
*
* @return string
*/
protected function getWatchId($repeatCounter = 0)
{
$elementModel = $this->getWatchElement();
return $elementModel->getHTMLId($repeatCounter);
}
/**
* Get the element to watch. Changes to this element will trigger the cdd's lookup
*
* @return plgFabrik_Element
*/
protected function getWatchElement()
{
if (!isset($this->watchElement))
{
$watch = $this->getParams()->get('cascadingdropdown_observe');
if ($watch == '')
{
throw new RuntimeException('No watch element set up for cdd' . $this->getElement()->id, 500);
}
$this->watchElement = $this->getFormModel()->getElement($watch, true);
if (!$this->watchElement)
{
// This element is a child element, so $watch is in the parent element (in another form)
$pluginManager = FabrikWorker::getPluginManager();
$parent = $pluginManager->getElementPlugin($watch);
// These are the possible watch elements
$children = $parent->getElementDescendents();
// Match the possible element ids with the current form's element ids
$elementIds = $this->getFormModel()->getElementIds();
$matched = array_values(array_intersect($elementIds, $children));
// Load the matched element
$this->watchElement = $pluginManager->getElementPlugin($matched[0]);
}
}
return $this->watchElement;
}
/**
* Create the sql query used to get the possible selectable value/labels used to create
* the drop-down/checkboxes
*
* @param array $data data
* @param bool $incWhere include where
* @param array $opts query options
*
* @return mixed JDatabaseQuery or false if query can't be built
*/
protected function buildQuery($data = array(), $incWhere = true, $opts = array())
{
$input = $this->app->input;
$sig = isset($this->autocomplete_where) ? $this->autocomplete_where . '.' . $incWhere : $incWhere;
$sig .= '.' . serialize($opts);
$repeatCounter = FArrayHelper::getValue($opts, 'repeatCounter', 0);
$db = FabrikWorker::getDbo();
if (isset($this->sql[$sig]))
{
return $this->sql[$sig];
}
$params = $this->getParams();
$watch = $this->getWatchFullName();
$whereVal = null;
$groups = $this->getFormModel()->getGroupsHiarachy();
$formModel = $this->getFormModel();
$watchElement = $this->getWatchElement();
// Test for ajax update
if ($input->get('fabrik_cascade_ajax_update') == 1)
{
// Allow for multiple values - e.g. when observing a db join rendered as a checkbox
$whereVal = $input->get('v', array(), 'array');
}
else
{
if (isset($formModel->data) || isset($formModel->formData))
{
$watchOpts = array('raw' => 1);
if (isset($formModel->data))
{
if ($watchElement->isJoin())
{
$id = $watchElement->getFullName(true, false) . '_id';
$whereVal = FArrayHelper::getValue($formModel->data, $id);
}
else
{
$whereVal = $watchElement->getValue($formModel->data, $repeatCounter, $watchOpts);
}
}
else
{
/*
* If we're running onAfterProcess, formData will have short names in it, which means getValue()
* won't find the watch element, as it's looking for full names. So if it exists, use formDataWithTableName.
*/
if (is_array($formModel->formDataWithTableName) && array_key_exists($watch, $formModel->formDataWithTableName))
{
$whereVal = $watchElement->getValue($formModel->formDataWithTableName, $repeatCounter, $watchOpts);
}
else
{
$whereVal = $watchElement->getValue($formModel->formData, $repeatCounter, $watchOpts);
}
}
// $$$ hugh - if not set, set to '' to avoid selecting entire table
if (!isset($whereVal))
{
$whereVal = '';
}
}
else
{
// $$$ hugh - probably rendering table view ...
$watchRaw = $watch . '_raw';
if (isset($data[$watchRaw]))
{
$whereVal = $data[$watchRaw];
}
else
{
// $$$ hugh ::sigh:: might be coming in via swapLabelsForvalues in pre_process phase
// and join array in data will have been flattened. So try regular element name for watch.
$noJoinWatchRaw = $watchElement->getFullName(true, false) . '_raw';
if (isset($data[$noJoinWatchRaw]))
{
$whereVal = $data[$noJoinWatchRaw];
}
else
{
// $$$ hugh - if watched element has no value, we have been selecting all rows from CDD table
// but should probably select none.
// Unless its a cdd autocomplete list filter - seems sensible to populate that with the values matching the search term
if ($this->app->input->get('method') !== 'autocomplete_options')
{
$whereVal = '';
}
}
}
}
}
$where = '';
$whereKey = $params->get('cascadingdropdown_key');
if (!is_null($whereVal) && $whereKey != '')
{
$whereBits = strstr($whereKey, '___') ? explode('___', $whereKey) : explode('.', $whereKey);
$whereKey = array_pop($whereBits);
if (is_array($whereVal))
{
foreach ($whereVal as &$v)
{
// Jaanus: Solving bug: imploded arrays when chbx in repeated group
if (is_array($v))
{
foreach ($v as &$vchild)
{
$vchild = FabrikString::safeQuote($vchild);
}
$v = implode(',', $v);
}
else
{
$v = FabrikString::safeQuote($v);
}
}
// Jaanus: if count of where values is 0 or if there are no letters or numbers, only commas in imploded array
$where .= count($whereVal) == 0 || !preg_match('/\w/', implode(',', $whereVal)) ? '4 = -4' : $whereKey . ' IN ' . '(' . str_replace(',,', ',\'\',', implode(',', $whereVal)) . ')';
}
else
{
$where .= $whereKey . ' = ' . $db->quote($whereVal);
}
}
$filter = $params->get('cascadingdropdown_filter');
/* $$$ hugh - temporary hack to work around this issue:
* http://fabrikar.com/forums/showthread.php?p=71288#post71288
* ... which is basically that if they are using {placeholders} in their
* filter query, there's no point trying to apply that filter if we
* aren't in form view, for instance when building a search filter
* or in table view when the cdd is in a repeat group, 'cos there won't
* be any {placeholder} data to use.
* So ... for now, if the filter contains {...}, and view!=form ... skip it
* $$$ testing fix for the bandaid, ccd JS should not be submitting data from form
*/
if (trim($filter) != '')
{
$where .= ($where == '') ? ' ' : ' AND ';
$where .= $filter;
}
$w = new FabrikWorker;
// $$$ hugh - add some useful stuff to search data
$placeholders = is_null($whereVal) ? array() : array('whereval' => $whereVal, 'wherekey' => $whereKey);
$join = $this->getJoin();
$where = $this->parseThisTable($where, $join);
if (!empty($this->autocomplete_where))
{
$where .= $where !== '' ? ' AND ' . $this->autocomplete_where : $this->autocomplete_where;
}
$data = array_merge($data, $placeholders);
$where = $w->parseMessageForRepeats($where, $data, $this, $repeatCounter);
$where = $w->parseMessageForPlaceHolder($where, $data);
$table = $this->getDbName();
$key = $this->queryKey();
$orderBy = 'text';
$tables = $this->getFormModel()->getLinkedFabrikLists($params->get('join_db_name'));
$listModel = JModelLegacy::getInstance('List', 'FabrikFEModel');
$val = $params->get('cascadingdropdown_label_concat');
if (!empty($val))
{
$val = $this->parseThisTable($val, $join);
$val = $w->parseMessageForPlaceHolder($val, $data);
$val = 'CONCAT_WS(\'\', ' . $val . ')';
$orderBy = $val;
}
else
{
$val = FabrikString::safeColName($params->get($this->labelParam));
$val = preg_replace("#^`($table)`\.#", $db->qn($join->table_join_alias) . '.', $val);
foreach ($tables as $tid)
{
$listModel->setId($tid);
$listModel->getTable();
$formModel = $this->getFormModel();
$formModel->getGroupsHiarachy();
$orderBy = $val;
// See if any of the tables elements match the db joins val/text
foreach ($groups as $groupModel)
{
$elementModels = $groupModel->getPublishedElements();
foreach ($elementModels as $elementModel)
{
$element = $elementModel->element;
if ($element->name == $val)
{
$val = $elementModel->modifyJoinQuery($val);
}
}
}
}
}
$val = str_replace($db->qn($table), $db->qn($join->table_join_alias), $val);
$query = $db->getQuery(true);
$query->select('DISTINCT(' . $key . ') AS value, ' . $val . 'AS text');
$desc = $params->get('cdd_desc_column', '');
if ($desc !== '')
{
$query->select(FabrikString::safeColName($desc) . ' AS description');
}
$query->from($db->qn($table) . ' AS ' . $db->qn($join->table_join_alias));
$query = $this->buildQueryJoin($query);
$where = FabrikString::rtrimword($where);
if ($where !== '')
{
$query->where($where);
}
if (!JString::stristr($where, 'order by'))
{
$query->order($orderBy . ' ASC');
}
$this->sql[$sig] = $query;
FabrikHelperHTML::debug((string) $this->sql[$sig]);
return $this->sql[$sig];
}
/**
* Get the the field name used for the foo AS value part of the query
*
* @since 3.0.8
*
* @return string
*/
protected function queryKey()
{
$db = FabrikWorker::getDbo();
$join = $this->getJoin();
$table = $this->getDbName();
$params = $this->getParams();
$key = FabrikString::safeColName($params->get('cascadingdropdown_id'));
$key = str_replace($db->qn($table), $db->qn($join->table_join_alias), $key);
return $key;
}
/**
* Get the element name or concat statement used to build the dropdown labels or
* table data field
*
* @return string
*/
protected function getLabelOrConcatVal()
{
$params = $this->getParams();
$join = $this->getJoin();
if ($params->get('cascadingdropdown_label_concat') == '')
{
return $this->getLabelParamVal();
}
else
{
$w = new FabrikWorker;
$val = $this->parseThisTable($params->get('cascadingdropdown_label_concat'), $join);
$val = $w->parseMessageForPlaceHolder($val, array());
return 'CONCAT_WS(\'\', ' . $val . ')';
}
}
/**
* Load connection object
*
* @return object connection table
*/
protected function loadConnection()
{