MIOLO20
Carregando...
Procurando...
Nenhuma entrada encontrada
gridcontrols.class
Ir para a documentação deste ficheiro.
1<?php
2
3class MBaseGrid extends MControl
4{
8 public function column()
9 {
10 return new MGridColumn();
11 }
12}
13
15{
16 var $grid; // grid which this columns belongs to
17 var $title; // column title
18 var $footer; // column footer
19 var $options; // array for mapping of data value to display value
20 var $align; // column align - rigth, center, left
21 var $nowrap; // column wrap/nowrap
22 var $width; // column width in pixels or percent
23 var $order; // column position on the grid
24 var $value; // value at current row
25 var $basecontrol; // base Control to render value
26 var $control; // array of Control clonning of basecontrol
27 var $index; // column index in the data array
28
29 public $replace;
30
31 public $numberFormat = false;
32
33 public $colorOptions = array();
34
41 public $hidden;
42
43 function __construct($title = '', $align = 'left', $nowrap = false,
44 $width = 0, $visible = true, $options = null,
45 $order = false, $replace = NULL, $numberFormat = false,
46 $colorOptions = array())
47 {
48 parent::__construct();
49
50 $this->setClass('m-grid-column');
51 $this->visible = $visible;
52 $this->title = $title;
53 $this->options = $options;
54 $this->align = $align;
55 $this->nowrap = $nowrap;
56 $this->width = $width;
57 $this->order = $order;
58 $this->value = '';
59 $this->index = 0;
60 $this->footer = null;
61 $this->basecontrol = new MLabel('');
62 $this->control = array();
63 $this->replace = $replace;
64 $this->numberFormat = $numberFormat;
65 $this->colorOptions = $colorOptions;
66 }
67
68 public function getGrid()
69 {
70 return $this->grid;
71 }
72
73 public function setGrid(MGrid $grid)
74 {
75 $this->grid = $grid;
76
77 return $this;
78 }
79
80 public function getTitle()
81 {
82 return $this->title;
83 }
84
85 public function setTitle($title)
86 {
87 $this->title = $title;
88
89 return $this;
90 }
91
92 public function getFooter()
93 {
94 return $this->footer;
95 }
96
97 public function setFooter($footer)
98 {
99 $this->footer = $footer;
100
101 return $this;
102 }
103
104 public function getOptions()
105 {
106 return $this->options;
107 }
108
109 public function setOptions($options)
110 {
111 $this->options = $options;
112
113 return $this;
114 }
115
116 public function getAlign()
117 {
118 return $this->align;
119 }
120
121 public function setAlign($align)
122 {
123 $this->align = $align;
124
125 return $this;
126 }
127
128 public function getNowrap()
129 {
130 return $this->nowrap;
131 }
132
133 public function setNowrap($nowrap)
134 {
135 $this->nowrap = $nowrap;
136
137 return $this;
138 }
139
140 public function getWidth()
141 {
142 return $this->width;
143 }
144
145 public function setWidth($width)
146 {
147 $this->width = $width;
148
149 return $this;
150 }
151
152 public function getOrder()
153 {
154 return $this->order;
155 }
156
157 public function setOrder($order)
158 {
159 $this->order = $order;
160
161 return $this;
162 }
163
164 public function getValue()
165 {
166 return $this->value;
167 }
168
169 public function setValue($value)
170 {
171 $this->value = $value;
172
173 return $this;
174 }
175
176 public function getBasecontrol()
177 {
178 return $this->basecontrol;
179 }
180
182 {
183 $this->basecontrol = $basecontrol;
184
185 return $this;
186 }
187
188 public function getControl($pos)
189 {
190 return $this->control;
191 }
192
193 public function setControl($control, $pos = 0)
194 {
195 $this->control = $control;
196
197 return $this;
198 }
199
200 public function getIndex()
201 {
202 return $this->index;
203 }
204
205 public function setIndex($index)
206 {
207 $this->index = $index;
208
209 return $this;
210 }
211
212 public function getReplace()
213 {
214 return $this->replace;
215 }
216
217 public function setReplace($replace)
218 {
219 $this->replace = $replace;
220
221 return $this;
222 }
223
227 public function setHidden($hidden)
228 {
229 $this->hidden = $hidden;
230 }
231
232 public function getConstructorArgsData()
233 {
234 $args = new stdClass();
235 $args->title = $this->title;
236 $args->align = $this->align;
237 $args->nowrap = $this->nowrap;
238 $args->width = $this->width;
239 $args->visible = $this->visible;
240 $args->options = $this->options;
241 $args->order = $this->order;
242 $args->replace = $this->replace;
243 $args->numberFormat = $this->numberFormat;
244
245 return $args;
246 }
247
248 function generate()
249 {
250 $i = $this->grid->currentRow;
251 $row = $this->grid->data[$i];
252 $this->control[$i] = clone $this->basecontrol; // clonning
253 $value = $row[$this->index];
254 $this->control[$i]->value = $value;
255
256 if ( $this->numberFormat )
257 {
258 $this->control[$i]->value = number_format($value, 2, ',', '.');
259 }
260
262
263 $this->generateColumnOptions();
264
265 if ( $this->hidden )
266 {
267 $this->control[$i]->addBoxStyle('display', 'none');
268 }
269
270 return $this->control[$i];
271 }
272
273 public function generateColumnOptions()
274 {
275 $originalValue = $this->control[$this->grid->currentRow]->value;
276
277 if ( $this->options )
278 {
279 $this->control[$this->grid->currentRow]->value = $this->options[$originalValue];
280
281 if ( $this->grid->showid )
282 {
283 $this->control[$this->grid->currentRow]->value .= " (" . $originalValue . ")";
284 }
285 }
286
287 if (strpos(MIOLO::getInstance()->getTheme()->id, "sbootstrap") !== false)
288 {
289 $this->generateColoredLabels($originalValue);
290 }
291 }
292
293 public function generateColoredLabels($valueOfColumn)
294 {
295 if (count($this->colorOptions) > 0 && key_exists($valueOfColumn, $this->colorOptions))
296 {
297 $badgeLabel = new MBadge($this->control[$this->grid->currentRow]->value, $this->colorOptions[$valueOfColumn]);
298 $this->control[$this->grid->currentRow]->value = $badgeLabel->generate();
299 }
300 // Quando forem apenas um booleano, então ele faz sozinho, senão precisa informar as cores
301 else if (count($this->options) == 2 && (key_exists(DB_FALSE, $this->options) && key_exists(DB_TRUE, $this->options)))
302 {
303 if (MUtil::getBooleanValue($valueOfColumn))
304 {
305 $badgeLabel = new MBadge($this->control[$this->grid->currentRow]->value, MBadge::COLOR_GREEN);
306 }
307 else if (strlen($valueOfColumn) > 0)
308 {
309 $badgeLabel = new MBadge($this->control[$this->grid->currentRow]->value, MBadge::COLOR_RED);
310 }
311
312 if (!empty($badgeLabel))
313 {
314 $this->control[$this->grid->currentRow]->value = $badgeLabel->generate();
315 }
316 }
317 }
318
320 {
321 $colunasCep = array_filter($this->grid->columns, function($column){
322 return ($column->title == 'CEP');
323 });
324
325 foreach ($colunasCep as $key => $t)
326 {
327 if ( $key == $this->index && !empty($this->control[$this->grid->currentRow]->value)
328 && is_numeric($this->control[$this->grid->currentRow]->value)
329 && strlen($this->control[$this->grid->currentRow]->value) == 8 )
330 {
331 $mascarado = substr($this->control[$this->grid->currentRow]->value, 0, 5);
332 $mascarado .= "-";
333 $mascarado .= substr($this->control[$this->grid->currentRow]->value, 5, 3);
334 $this->control[$this->grid->currentRow]->value = $mascarado;
335 }
336 }
337 }
338}
339
340
342{
343 var $href; // link - replaces #?# with column's value
344
345 function __construct($title = '', $href, $width = 0, $visible = true, $options = null, $order = false, $filter = false)
346 {
347 parent::__construct($title, null, false, $width, $visible, $options, $order, $filter);
348
349 $this->align = 'left';
350 $this->href = $href;
351 $this->basecontrol = new Hyperlink('', '', $href);
352 $this->basecontrol->setClass('m-grid-column-link');
353 }
354
355 function generate()
356 {
357 $i = $this->grid->currentRow;
358 $row = $this->grid->data[$i];
359 $this->control[$i] = clone $this->basecontrol; // clonning
360 $value = $row[$this->index];
361 $n = count($row);
363
364 for ($r = 0; $r < $n; $r++)
365 {
366 $href = str_replace("#$r#", trim($row[$r]), $href);
367 }
368
369 $href = str_replace('#?#', $value, $href);
370 $this->control[$i]->href = $href;
371 $this->control[$i]->action = $href;
372 $this->control[$i]->label = $value;
373
374 if ( $this->hidden )
375 {
376 $this->control[$i]->addBoxStyle('display', 'none');
377 }
378
379 return $this->control[$i];
380 }
381}
382
384{
388 public $control;
389
390 public function __construct($control, $title='', $align='left', $nowrap=false, $width=0, $visible=true)
391 {
392 parent::__construct($title, $align, $nowrap, $width, $visible);
393 $this->basecontrol = $control;
394 }
395
396 public function generate()
397 {
398 $i = $this->grid->currentRow;
399 $row = $this->grid->data[$i];
400 $this->control[$i] = clone $this->basecontrol;
401 $name = $this->control[$i]->getName();
402
403 // If the name is not an array, add brackets to transform it.
404 if ( strpos($name, "[") === false && strpos($name, "]") === false )
405 {
406 $name .= "[$i]";
407 }
408 else
409 {
410 // Position of the identifier character which will be substituted.
411 $pos = strpos($name, '%');
412
413 // If the name is ok with grid naming rules, line number is between %. E.g. %N%.
414 if ( !$pos === false )
415 {
416 $rowNumber = substr($name, $pos + 1, -2);
417 $name = str_replace("%$rowNumber%", trim($row[$rowNumber]), $name);
418 }
419 }
420
421 $this->control[$i]->setName($name);
422 $this->control[$i]->setId($name);
423 $n = count($row);
424
425 for ( $r = 0; $r < $n; $r++ )
426 {
427 $this->control[$i]->setValue(str_replace("%$r%", trim($row[$r]), $this->control[$i]->getValue()));
428 }
429
430 if ( $this->hidden )
431 {
432 $this->control[$i]->addBoxStyle('display', 'none');
433 }
434
435 return $this->control[$i];
436 }
437}
438
440{
441 public $grid; // grid which this action belongs to
442 public $type; // "text", "image", "select" or "none"
443 public $alt; // image alt
444 public $value; // image/text label for on
445 public $valueoff; // image/text label for off
446 public $href; // link pattern - replaces
447 // #n# with value of column "n"
448 // %n% with urlencode(value) of column "n"
449 // $id with value of column "index"
450 public $index; // deprecated
451 public $enabled;
452 public $target;
453
454 public function __construct($grid, $type, $alt, $value, $href, $enabled = true, $index = null)
455 {
456 parent::__construct();
457 $this->grid = $grid;
458 $this->type = $type;
459 $this->alt = $alt;
460
461 if ( is_array($value) )
462 {
463 $this->value = $value[0];
464 $this->valueoff = $value[1];
465 }
466 else
467 {
468 $this->value = $this->valueoff = $value;
469 }
470
471 $this->href = $href;
472 $this->index = $index;
473 $this->enabled = $enabled;
474 }
475
476 public function enable()
477 {
478 $this->enabled = true;
479 }
480
481 public function disable()
482 {
483 $this->enabled = false;
484 }
485
486 public function GenerateLink($row)
487 {
488 $index = $row[$this->grid->index];
489 $href = preg_replace('#\$id#', $index, $this->href);
490 $n = count($row);
491
492 // substitute named parameters
493 foreach ( (array) $row as $tempKey => $tempValue )
494 {
495 $href = str_replace("%$tempKey%", urlencode($tempValue), $href);
496 }
497
498 // substitute positional parameters
499 for ($r = 0; $r < $n; $r++)
500 {
501 if( is_object($row[$r]) )
502 {
503 $row[$r] = $row[$r]->generate( );
504 }
505
506 $href = str_replace("%$r%", urlencode($row[$r]), $href);
507 $href = str_replace("#$r#", $row[$r], $href);
508 $href = str_replace('"', '', $href);
509 }
510
511 return $href;
512 }
513
514 public function generate()
515 {
516 }
517
518 public function setTarget($target)
519 {
520 $this->target = $target;
521 }
522
523}
524
526{
530 public $path;
531
532 public function __construct($grid, $value, $href, $alt=NULL)
533 {
534 parent::__construct($grid, 'image', $alt, $value, $href);
535
536 $class = "m-grid-action-icon-{$this->value}-on";
537
538 preg_match_all("#{$class}[\s]*\{[\s]*background-image:[\s]*url\‍((.*?)\‍);[\s]*\}#i", $this->grid->css, $match);
539
540 $this->path = ( isset($match[1][0]) ? $match[1][0] : null);
541 }
542
543 public function generate()
544 {
546 $class = "m-grid-action-icon";
547
548 if ( !$path )
549 {
550 $path = $this->grid->getImage($this->value);
551 }
552
553 if ($this->enabled)
554 {
555 $row = $this->grid->data[$this->grid->currentRow];
556 $href = $this->generateLink($row);
557
558 $control = ( $this->grid->linktype == 'hyperlink') ?
559 new MImageLink('', $this->alt, $href, $path) :
560 new MImageButton('', $this->alt, $href, $path
561 );
562 $control->setTarget( $this->target );
563 }
564 else
565 {
566 $control = new MImage('', $this->alt, $path);
567 $control->setClass('m-grid-action-icon-off');
568 }
569
570 $control->setClass($class);
571
572 return $control;
573 }
574}
575
577{
578
580 {
581 parent::__construct($grid, 'text', null, $value, $href);
582 $this->attributes = "width=\"20\" align=\"center\"";
583 }
584
585 function generate()
586 {
587 $value = $this->value;
588
589 if ( $this->enabled )
590 {
591 $row = $this->grid->data[$this->grid->currentRow];
592 $n = count($row);
593
594 for ($r = 0; $r < $n; $r++)
595 {
596 $value = str_replace("%$r%", $row[$r], $value);
597 }
598
599 $href = $this->generateLink($row);
600 $control = ( $this->grid->linktype == 'hyperlink') ?
601 new HyperLink('', $value, $href) :
602 new LinkButton('', $value, $href
603 );
604 $control->setTarget( $this->target );
605 $control->setClass('m-grid-link');
606 }
607 else
608 {
609 $control = new MSpan('', $value, 'm-grid-link-disable');
610 }
611
612 return $control;
613 }
614}
615
617{
618 public function __construct($grid, $index=0)
619 {
620 parent::__construct($grid, 'select', null, null, null, true, $index);
621 }
622
623 public function generate()
624 {
625 $i = $this->grid->currentRow;
626 $row = $this->grid->data[$i];
627 $index = $row[$this->grid->index];
628
629 if ( $this->grid instanceof SGrid )
630 {
631 $primaryKeys = array_values($this->grid->getPrimaryKey());
632 $indexPrimaryKey = $row[str_replace("%", "", $primaryKeys[0])];
633
634 $index = $this->grid->indexPrimaryKey ? $indexPrimaryKey : $index;
635 }
636
637 $onclick = "javascript:gridChk(this,'" . $this->grid->name . "[$i]" . "');";
638
639 $control = new MCheckBox("select" . $this->grid->name . "[$i]", $index, '');
640 $control->addAttribute('onclick', $onclick);
641
642 // Put the MGridActionSelect attributes on the check box
643 foreach ( $this->attrs->getItems() as $attr => $value )
644 {
645 $value = trim($value, '"');
646
647 if ( strtolower($attr) == 'onclick' )
648 {
649 $value = "$onclick $value";
650 }
651
652 $control->addAttribute($attr, $value);
653 }
654
655 return $control;
656 }
657}
658
660{
662 {
663 parent::__construct($id, "[$label]", $href);
664 $this->setClass('m-grid-link');
665 }
666}
667
669{
670 var $grid; // grid which this filter belongs to
671 var $type; // "text", "selection"
672 var $label; // image alt
673 var $value; // image/text label for on/off
674 var $index; // column index in the data array
677
679 {
680 parent::__construct();
681 $this->grid = $grid;
682 $this->type = $type;
683 $this->label = $label;
684 $this->index = $index;
685 $this->enabled = $enabled;
686 $this->control = null;
687 }
688
689 function generate()
690 {
691 if ( $this->enabled )
692 {
693 $array[] = new MSpan('', $this->label . '&nbsp;', 'm-grid-font');
694 $this->control->setValue( ( $this->grid->getFiltered() ) ? $this->value : NULL);
695 $array[] = $this->control->generate();
696 $array[] = '&nbsp;&nbsp;&nbsp;';
697 }
698
699 return $array;
700 }
701}
702
704{
705 function __construct($grid, $label, $value = '', $index = 0, $enabled = false)
706 {
707 parent::__construct($grid, 'text', $label, $value, $index, $enabled);
708
709 $this->control = new MTextField("m-grid-filter-text-$index", $value, $label, 20);
710 $this->value = $this->page->request($this->control->name) ? $this->page->request($this->control->name) : $value;
711 }
712}
713
715{
716
717 function __construct($grid, $label, $options = array(), $index = 0, $enabled = false)
718 {
719 parent::__construct($grid, 'selection', $label, '', $index, $enabled);
720
721 $this->control = new MSelection("m-grid-filter-sel-$index", '', $label, $options);
722 $this->value = $this->page->request($this->control->name) ? $this->page->request($this->control->name) : $value;
723 }
724}
725
727{
728
729 function __construct($grid, &$control, $type = 'text', $index = 0, $enabled = false)
730 {
731 parent::__construct($grid, $type, $control->label, $control->value, $index, $enabled);
732
733 $this->control = $control;
734 $this->value = $this->page->request($this->control->name) ? $this->page->request($this->control->name) : $control->value;
735 }
736}
737
738class MGrid extends MBaseGrid
739{
740 var $title; // table display title
741 var $filters; // array of grid filter controls
742 var $filtered; // is filtered?
743 var $filter; // show/hide filters
744 var $orderby; // base column to sort
745 var $ordered; // is ordered?
746 var $data; // table data cells
747 var $actions; // array with actions controls
748 var $select; // a column for select action
749 var $showid; // show ids or not?
750 var $columns; // array with columns
751 var $icons; // action icons
752 var $errors; // array of errors
753 var $pageLength; // max number of rows to show - 0 to all rows
754 var $rowCount; // total number of rows
755 var $href; // grid url
756 var $pn; // gridnavigator
757 var $headerLinks; // array of headerlinks
758 var $linktype; // hyperlink or linkbutton (forced post)
759 var $width; // table width for the grid
760 var $rowmethod; // method to execute (callback) at each row
761 var $index; // the column to act as index of grid
764 var $currentRow=0; // index of row to renderize
765 var $box;
771 var $name;
772 var $css;
774 public $header;
775 protected $isShowHeaders= true;
776 protected $scrollable = false;
777 protected $scrollWidth = '99%';
778 protected $scrollHeight = '99%';
779 protected $orderByDatabase = false; // Quando o orderBy da grid é feito por banco
780 private $gridMostraTotalNumeric = false;
781
785 private $offset = NULL;
786
790 private $hiddenControls = array();
791
792 /*
793 * @var boolean Show all export buttons.
794 */
796
797 /*
798 * @var boolean Show export as CSV button, it needs an exportGridAsCSV_click method on form.
799 */
801
802 /*
803 * @var boolean Show export as HTML button, it needs an exportGridAsHTML_click method on form.
804 */
806
807 /*
808 * @var boolean Show export as PDF button, it needs an exportGridAsPDF_click method on form.
809 */
811
812 private $generateDataCalled = false;
813
814/*
815 Grid constructor
816 $data - the data array
817 $columns - array of columns objects
818 $href - base url of this grid
819 $pageLength - max number of rows to show (0 to show all)
820*/
821
825 public $colSortingCleanURL = false;
826
828
829 public $query;
830
831 private $idResult;
832
838 protected $gerarQuebraDeLinhaActions = false;
839
840 public function __construct($data, $columns, $href, $pageLength=15, $index=0, $name='', $useSelecteds=TRUE, $useNavigator=TRUE, $showExport=FALSE, $gridMostraTotalNumeric=false, $fixedTableHeader=true)
841 {
842 global $state;
843
844 parent::__construct(NULL);
845 $this->addStyleFile('m_grids.css');
846 $this->setColumns($columns);
847 $this->href = $href;
848 $this->pageLength = $pageLength;
849 $this->headerLinks = array();
850 $this->width = '';
851 $this->setLinkType('linkbutton');
852 $this->box = new MBox('', 'backContext', '');
853 $this->rowmethod = null;
854 $this->index = $index;
855 $this->emptyMsg = _M('No records found!');
856 $this->data = $data;
857 $this->rowCount = count($this->data);
858 $this->controls = array();
859 $this->select = NULL;
860 $this->name = $name;
861 $this->showExport = $showExport;
862 $this->gridMostraTotalNumeric = $gridMostraTotalNumeric;
863
864 $this->pageNumber = MUtil::NVL($state->get('pn_page', $this->name),'1');
865 $this->prevPage = MUtil::NVL($state->get('grid_page', $this->name),'1');
866 $state->set('grid_page', $this->pageNumber, $this->name);
867
868// $this->setCurrentPage( $this->pageNumber );
869
870 $this->selecteds = array();
871 $this->selectsreadonly = array();
872 $this->allSelecteds = array();
873
874 $this->setUseSelecteds($useSelecteds);
875
876// if (!$useNavigator) {
877 $this->handlerSelecteds();
878// }
879 $this->page->addScript('m_grid.js');
880
881 $this->css = file_get_contents($this->manager->getTheme()->getPath() . '/m_grids.css');
882
883 $this->actionColumnName = _M('Action');
884
886 if ( $fixedTableHeader )
887 {
888 $this->page->addScript("../themes/{$MIOLO->getTheme()->getName()}/scripts/fixed_table_header.js");
889 }
890 $this->page->addScript("../themes/{$MIOLO->getTheme()->getName()}/scripts/sagu.js");
891 }
892
893 function setShowHeaders( $show=true )
894 {
895 $this->isShowHeaders = $show;
896 }
897
898 function showHeaders( )
899 {
901 }
902
904 {
905 global $state;
906
907 $this->pageNumber = $pageNumber;
908 $state->set('grid_page', $pageNumber, $this->name);
909 $this->prevPage = MUtil::NVL($state->get('grid_page', $this->name),'1');
910 }
911
912 function getURL($filter = false, $order = false, $item = '')
913 {
915 $url .= ($filter) ? "&__filter=1" : "&__filter=0";
916
917 if ($order)
918 {
919 $url .= "&orderby={$this->orderby}";
920
921 // Adiciona order by inverso (DESC / ASC)
922 $currentOrder = MIOLO::_REQUEST('orderby');
923
924 if ( strlen($currentOrder) > 0 && ( $this->orderby == $currentOrder ) )
925 {
926 if ( strlen($this->getOrderMode()) <= 0 || $this->getOrderMode() == 'asc' )
927 {
928 $orderMode = 'desc';
929 }
930 else
931 {
932 $orderMode = 'asc';
933 }
934
935 $url .= '&ordermode=' . $orderMode;
936 }
937 }
938
939 // concatena function na url
940 // code fix para componente grid do slinkedform, para funcionar a ordenacao e os formularios corretamente
941 if ( ( strlen( ( isset($_REQUEST['function']) ? $_REQUEST['function'] : null) ) > 0 ) && !preg_match('/function=/', $url) )
942 {
943 $url .= '&function=' . $_REQUEST['function'];
944 }
945
946 if ($item)
947 {
948 $url .= $item;
949 }
950
951 return $url;
952 }
953
959 public function getOrderMode()
960 {
961 return MIOLO::_REQUEST('ordermode');
962 }
963
964 function setTitle($title)
965 {
966 $this->caption = $this->title = $title;
967 }
968
970 {
971 $this->pageLength = $pageLength;
972 }
973
974 function getPageLength()
975 {
976 return $this->pageLength;
977 }
978
980 {
981 $this->footer = $footer;
982 }
983
985 {
986 $this->columns = array();
987
988 if ( ! is_array($columns) )
989 {
990 $columns = array($columns);
991 }
992
993 foreach ($columns as $k => $c)
994 {
995 $this->columns[$k] = $c;
996 $this->columns[$k]->index = $k;
997 $this->columns[$k]->grid = $this;
998 }
999 }
1000
1002 {
1003 $this->linktype = strtolower($linktype);
1004 }
1005
1007 {
1008 if ( ! is_array($controls) )
1009 {
1010 $controls = array($controls);
1011 }
1012
1013 $this->controls = array_merge($this->controls, $controls);
1014 }
1015
1016 function setButtons($aButtons) //backward compatibility
1017 {
1018 $this->setControls($aButtons);
1019 }
1020
1022 {
1023 $this->width = $width;
1024 }
1025
1027 {
1028 $this->index = $index;
1029 }
1030
1031 function setRowMethod($class, $method)
1032 {
1033 $this->rowmethod = array($class, $method);
1034 }
1035
1036 function setIsScrollable($scrollable=true, $width='99%', $height='99%')
1037 {
1038 $this->scrollable = $scrollable;
1039 $this->scrollWidth = $width;
1040 $this->scrollHeight = $height;
1041 }
1042
1043 function setScrollWidth($width='99%')
1044 {
1045 $this->scrollWidth = $width;
1046 }
1047
1048 function setScrollHeight($height='99%')
1049 {
1050 $this->scrollHeight = $height;
1051 }
1052
1053 function headerLink($id, $label, $href)
1054 {
1055 $this->headerLinks[$id] = new MGridHeaderLink($id, $label, $href);
1056 }
1057
1058 function setColumnAttr($col, $attr, $value)
1059 {
1060 $this->columns[$col]->$attr = $value;
1061 }
1062
1063 function setData($data, $rowCount = null)
1064 {
1065 $this->data = $data;
1066 $this->rowCount = (strlen($rowCount) > 0) ? $rowCount : count($this->data);
1067
1068 // Verificações para não contabilizar a linha de totais, caso esteja configurado para exibí-la.
1069 if ( $this->gridMostraTotalNumeric && empty($this->rowCount) && ($this->rowCount >= $this->pageLength || $this->pageLength == 999999999) )
1070 {
1071 $this->rowCount --;
1072 }
1073 }
1074
1075 function getData()
1076 {
1077 return $this->data;
1078 }
1079
1080 function getDataValue($row, $col)
1081 {
1082 return $this->data[$row][$col];
1083 }
1084
1085 function getPage()
1086 {
1087 if ( count($this->data) )
1088 {
1089 $gridCount = $this->pn->gridCount;
1090 if ( $this->gridMostraTotalNumeric )
1091 {
1092 $gridCount ++;
1093 }
1094
1095 $offset = $this->pn->idxFirst >= count($this->data) ? 0 : $this->pn->idxFirst;
1096 return array_slice($this->data, $offset, $gridCount);
1097 }
1098 }
1099
1100 function getPageNumber()
1101 {
1102 return $this->pageNumber;
1103 }
1104
1105 function getPrevPage()
1106 {
1107 return $this->prevPage;
1108 }
1109
1111 {
1112 $this->select = new MGridActionSelect($this);
1113 }
1114
1115 function addActionIcon($alt, $icon, $href, $index = null)
1116 {
1117 // If temporário, retirar assim que o sbootstrap for padrão no sistema
1118 if (strpos(MIOLO::getInstance()->getTheme()->id, "sbootstrap") !== false)
1119 {
1120 $icon = str_replace(array('cal.gif'), array('calendario.png'), $icon);
1121 }
1122
1123 //if ($p = strpos($icon,'.')) $icon = substr($icon,0,$p);
1124 if (!is_null($index))
1125 {
1126 $this->actions[$index] = new MGridActionIcon($this, $icon, $href, $alt);
1127 }
1128 else
1129 {
1130 $this->actions[] = new MGridActionIcon($this, $icon, $href, $alt);
1131 }
1132 }
1133
1134 function addActionText($alt, $text, $href, $index = 0)
1135 {
1136 $this->actions[] = new MGridActionText($this, $text, $href);
1137 }
1138
1140 {
1141// $this->AddActionIcon('Editar', array('button_edit.png', 'button_noedit.png'), $href);
1142 $this->addActionIcon( _M('Edit'), 'edit', $href);
1143 }
1144
1145 function addActionDelete($href, $alt = 'Delete')
1146 {
1147// $this->AddActionIcon('Excluir', array('button_drop.png', 'button_noempty.png'), $href);
1148 $this->addActionIcon( _M($alt), 'delete', $href);
1149 }
1150
1151 function addFilterSelection($index, $label, $options, $value = '')
1152 {
1153 $f = new MGridFilterSelection($this, $label, $options, $index, $this->getFilter());
1154 $this->filters[$index] = $f;
1155 }
1156
1157 function addFilterText($index, $label, $value = '')
1158 {
1159 $f = new MGridFilterText($this, $label, $value, $index, $this->getFilter());
1160 $this->filters[$index] = $f;
1161 }
1162
1163 function addFilterControl($index, $control, $type = 'text')
1164 {
1165 $this->filters[$index] = new MGridFilterControl($this, $control, $type, $index, $this->getFilter());
1166 }
1167
1168 function getFilterValue($index)
1169 {
1170 return $this->filters[$index]->value;
1171 }
1172
1174 {
1175 return $this->filters[$index]->control;
1176 }
1177
1178 function setFiltered($value = false)
1179 {
1180 $this->filtered = $value;
1181 }
1182
1183 function getFiltered()
1184 {
1185 if ( ( $f = $this->page->Request('__filter') ) != '' )
1186 {
1187 $this->filtered = ($f == '1');
1188 }
1189
1190 return $this->filtered;
1191 }
1192
1193 function getFilter()
1194 {
1195 return $this->filter;
1196 }
1197
1198 function setFilter($status)
1199 {
1200 $this->filter = $status;
1201
1202 if ($this->filters)
1203 {
1204 foreach ($this->filters as $k => $f)
1205 {
1206 $this->filters[$k]->enabled = $status;
1207 }
1208 }
1209 }
1210
1211 function applyFilter()
1212 {
1213 if ($this->filters)
1214 {
1215 foreach ($this->filters as $f)
1216 {
1217 $value[$f->index] = $f->value;
1218 }
1219
1220 foreach ($this->data as $row)
1221 {
1222 $ok = true;
1223
1224 foreach ($value as $k => $v)
1225 {
1226 $n = strlen( trim($v) );
1227 $ok = $ok && ( ! strncasecmp($row[$k], $v, $n) );
1228 }
1229
1230 if ($ok)
1231 $data[] = $row;
1232 }
1233 $this->data = $data;
1234 $this->rowCount = count($this->data);
1235 }
1236 }
1237
1238 function applyOrder($column)
1239 {
1240 $p = $this->columns[$column]->index;
1241 $n = count($this->data[0]);
1242
1243 foreach ($this->data as $key => $row)
1244 {
1245 for ($i = 0; $i < $n; $i++)
1246 {
1247 $arr[$i][$key] = $row[$i];
1248 }
1249 }
1250
1251 $sortcols = "\$arr[$p]";
1252
1253 for ($i = 0; $i < $n; $i++)
1254 {
1255 if ($i != $p)
1256 {
1257 $sortcols .= ",\$arr[$i]";
1258 }
1259 }
1260
1261 // Se já foi ordenado na base de dados, não ordena no PHP
1262 if ( $this->orderByDatabase != true )
1263 {
1264 eval("array_multisort({$sortcols}, SORT_ASC);");
1265 }
1266
1267 $this->data = array();
1268
1269 for ($i = 0; $i < $n; $i++)
1270 {
1271 foreach ($arr[$i] as $key => $row)
1272 {
1273 $this->data[$key][$i] = $row;
1274 }
1275 }
1276 }
1277
1278 function addError($err)
1279 {
1280 if ($err)
1281 {
1282 if ( is_array($err) )
1283 {
1284 if ($this->errors)
1285 {
1286 $this->errors = array_merge($this->errors, $err);
1287 }
1288 else
1289 {
1290 $this->errors = $err;
1291 }
1292 }
1293 else
1294 {
1295 $this->errors[] = $err;
1296 }
1297 }
1298 }
1299
1300 function showID($state)
1301 {
1302 $this->showid = $state;
1303 }
1304
1306 {
1307 $this->box->setClose($action);
1308 }
1309
1310 function setSelecteds($s)
1311 {
1312 global $state;
1313 $selecteds = $state->get('selecteds', $this->name);
1315 $state->set('selecteds',$selecteds, $this->name);
1316 $state->set('useselecteds', true, $this->name);
1317 }
1318
1319 function setUseSelecteds($opt)
1320 {
1321 global $state;
1322 $state->set('useselecteds', $opt, $this->name);
1323 }
1324
1326 {
1327 global $state;
1328
1329 $selecteds = $state->get('selecteds', $this->name);
1330 $useSelecteds = $state->get('useselecteds', $this->name);
1331
1332 if ( urldecode( $this->page->request('gridName') ) == $this->name )
1333 {
1334 $state->set('pn_page', $this->page->request('pn_page'), $this->name);
1335 }
1336 $state->set('gridName', $this->name); //para gravar o nome do grid na sessão
1337 $this->pageNumber = MUtil::NVL($state->get('pn_page', $this->name),1);
1338 $this->prevPage = MUtil::NVL($state->get('grid_page', $this->name),1);
1339
1340 $this->selecteds = array();
1341
1342 if ($useSelecteds)
1343 {
1344 $selecteds[$this->prevPage] = array();
1345
1346 if ($select = $this->page->request('select'.$this->name))
1347 {
1348 foreach( $select as $k=>$v )
1349 {
1351 }
1352 }
1353 if ( is_array($selecteds[$this->pageNumber]) )
1354 {
1355 $this->selecteds = $selecteds[$this->pageNumber];
1356 }
1357 $this->allSelecteds = $selecteds;
1358 }
1359
1360 $state->set('grid_page', $this->pageNumber, $this->name);
1361
1362 $state->set('useselecteds', $useSelecteds, $this->name);
1363 $state->set('selecteds',$selecteds, $this->name);
1364 }
1365
1366 function generateTitle()
1367 {
1368 if ( $this->caption != '' )
1369 {
1370 $this->box->SetCaption($this->caption);
1371
1372 return $this->box->boxTitle->generate();
1373 }
1374 }
1375
1377 {
1378 if ( ! $this->pn )
1379 {
1380 return null;
1381 }
1382
1383 $links = $this->pn->getPageLinks();
1384
1385 foreach ( $links as $link )
1386 {
1387 $link->float = 'left';
1388 }
1389
1390 $d['pages'] = new MDiv('', $links);
1391 $d['pages']->addStyle('float', 'left');
1392 $array[0] = $this->pn->getPageFirst();
1393 $array[1] = $this->pn->getPagePrev();
1394 $array[2] = $this->pn->getPageRange();
1395 $array[3] = $this->pn->getPageNext();
1396 $array[4] = $this->pn->getPageLast();
1397
1398 if ( !is_null($this->showExportAsCSV) )
1399 {
1400 $this->showExport = $this->showExportAsCSV;
1401 }
1402
1403 if ( $this->showExport )
1404 {
1405 $pn_page = !is_null($_GET['pn_page']) ? "&pn_page=" . $_GET['pn_page'] : "";
1406 if ($this->manager->theme->id == 'smodern')
1407 {
1408 // CSV export
1410 $url = "{$this->pn->action}&gridName=". urlencode($this->name) . $pn_page;
1411 $img = $MIOLO->getUI()->getImage(NULL, 'csv.png');
1412
1413 $export = new MLinkButton('exportGridAsCSV', _M('Export as CSV (Excel)'), $url);
1414 $export->generateLink();
1415 $export = new MImageLink('exportGridAsCSV', _M('Export as CSV (Excel)'), $export->href . 'stopShowLoading();', $img);
1416 $d['export'] = new MDiv('exportButtonDiv', array($export), 'm-grid-export-div');
1417
1418
1419 // HTML export
1421 $url = "{$this->pn->action}&gridName=". urlencode($this->name) . $pn_page;
1422 $img = $MIOLO->getUI()->getImage(NULL, 'html.png');
1423
1424 $export = new MLinkButton('exportGridAsHTML', _M('Export as HTML'), $url);
1425 $export->target = '_blank';
1426 $export->generateLink();
1427 $export = new MImageLink('exportGridAsHTML', _M('Export as HTML'), $export->href . 'stopShowLoading();', $img);
1428 $d['exportHTML'] = new MDiv('exportButtonDiv', array($export), 'm-grid-export-div');
1429
1430
1431 // PDF export
1433 $url = "{$this->pn->action}&gridName=". urlencode($this->name) . $pn_page;
1434 $img = $MIOLO->getUI()->getImage(NULL, 'pdf.png');
1435
1436 $export = new MLinkButton('exportGridAsPDF', _M('Export as PDF'), $url);
1437 $export->generateLink();
1438 $export = new MImageLink('exportGridAsPDF', _M('Export as PDF'), $export->href . 'stopShowLoading();', $img);
1439 $d['exportPDF'] = new MDiv('exportButtonDiv', array($export), 'm-grid-export-div');
1440
1441 // XLS export
1443 $url = "{$this->pn->action}&gridName=". urlencode($this->name) . $pn_page;
1444 $img = $MIOLO->getUI()->getImage(NULL, "xls.png");
1445
1446 $export = new MLinkButton("exportGridAsXLS", _M("Exportar como XLS"), $url . "&tipoDeExportacao=0");
1447 $export->generateLink();
1448 $export = new MImageLink("exportGridAsXLS", _M("Exportar como XLS"), $export->href . 'stopShowLoading();', $img);
1449 $d['exportXLS'] = new MDiv('exportButtonDiv', array($export), 'm-grid-export-div');
1450
1451 // JRXML export
1453 $url = "{$this->pn->action}&gridName=". urlencode($this->name) . $pn_page;
1454 $img = $MIOLO->getUI()->getImage(NULL, "jrxml.png");
1455
1456 $export = new MLinkButton("exportGridAsJRXML", _M("Gerar JRXML"), $url);
1457 $export->generateLink();
1458 $export = new MImageLink("exportGridAsJRXML", _M("Gerar JRXML"), $export->href . 'stopShowLoading();', $img);
1459 $d['exportJRXML'] = new MDiv('exportButtonDiv', array($export), 'm-grid-export-div');
1460 }
1461 else
1462 {
1463 $newExport = (version_compare(SAGU_VERSION, "3.74.05") >= 0);
1464 $exportsList = array('PDF', 'XLS', 'HTML', 'JRXML', 'CSV');
1465 foreach ($exportsList as $ex)
1466 {
1467 $url = "{$this->pn->action}&gridName=". urlencode($this->name) . $pn_page . "&typeExport=$ex";
1468 $export = new MLinkButton("exportGridAs$ex", _M(""), $url);
1469 $export->generateLink();
1470
1471 if ( $newExport )
1472 {
1473 $labelEx = _M("Exportar para $ex");
1474 $actionExportUrl = base64_encode($export->href . 'stopShowLoading();');
1475 $actionExport = "javascript:saguDoAjax('gerarModalExportacao','divExportsM',false,'&labelExport={$labelEx}&rowCount={$this->rowCount}&actionExport={$actionExportUrl}')";
1476
1477 $export = new MText("exportGridAs$ex", _M("Exportar para $ex"));
1478 $export->addAttribute('onclick', $actionExport);
1479 $export->addAttribute('style', 'cursor: pointer; text-decoration: none; font-size: 11px; font-weight: 500; font-style: normal; white-space: normal; text-align:left !important; min-height: 22px !important; padding-left: 18px;');
1480 $linksExport[] = $export;
1481 }
1482 else
1483 {
1484 $linksExport[] = new MLink('lnkExport$ex', _M("Exportar para $ex"), $export->href . 'stopShowLoading();', null);
1485 }
1486 }
1487
1488 $d['exportDrop'] = new MDropdownMenu('', ' ', $linksExport, $this->manager->getUI()->getImageTheme($this->manager->theme->id, 'export-20x20.png'));
1489 $d['exportDrop']->setClass('exportIcon');
1490 $d['exportDrop']->addAttribute('title', 'Exportar');
1491 $this->page->onLoad('
1492 $(".exportIcon ul").css("left", $(".exportIcon").prev().width()+"px");
1493 $(".exportIcon").prop("title", "Visualizar exportações disponíveis");
1494 ');
1495 }
1496 }
1497
1498 $d['nav'] = new MDiv('', $array);
1499 $d['nav']->addStyle('float', 'right');
1500
1501 $d = new MDiv('', $d, 'm-grid-navigation');
1502
1503 return $d;
1504 }
1505
1507 {
1508 if ( ! $this->pn )
1509 {
1510 return null;
1511 }
1512
1513 $links = $this->pn->getPageLinks();
1514
1515 foreach ($links as $link)
1516 {
1517 $link->float = 'left';
1518 }
1519
1520 $d1 = new MDiv('', $links);
1521 $d1->addStyle('float', 'left');
1522 $array[0] = $this->pn->getPageFirst();
1523 $array[1] = $this->pn->getPagePrev();
1524 $array[2] = $this->pn->getPageRange();
1525 $array[3] = $this->pn->getPageNext();
1526 $array[4] = $this->pn->getPageLast();
1527
1528 $d2 = new MDiv('', $array);
1529 $d2->addStyle('float', 'right');
1530
1531 $d = new MDiv('', array($d1, $d2), 'm-grid-navigation m-grid-navigation-bottom');
1532
1533 return $d;
1534 }
1535
1536 function generateLinks()
1537 {
1538 if ( ! count($this->headerLinks) )
1539 {
1540 return NULL;
1541 }
1542
1543 foreach ($this->headerLinks as $link)
1544 {
1545 $link->float = 'left';
1546 }
1547
1548 $div = new MDiv('', $this->headerLinks, 'm-grid-header-link');
1549
1550 return $div;
1551 }
1552
1554 {
1555 if ( ! count($this->controls) )
1556 {
1557 return NULL;
1558 }
1559
1560 $i = 0;
1561
1562 foreach ($this->controls as $c)
1563 {
1564 $array[$i++] = $c->generate();
1565 $array[$i++] = '&nbsp;&nbsp;';
1566 }
1567
1568 return new MDiv('', $array, 'm-grid-controls');
1569 }
1570
1572 {
1573 if ( ! $this->filter )
1574 {
1575 return null;
1576 }
1577
1578 foreach ($this->filters as $k => $f)
1579 {
1580 $array[] = $f->generate();
1581 }
1582
1583 $button = new MButton('', _M('Filter'), 'submit', 'images/button_select.png');
1584 $array[] = $button->generate();
1585
1586 return new MDiv('', $array, 'm-grid-filter');
1587 }
1588
1589 function hasErrors()
1590 {
1591 return count($this->errors);
1592 }
1593
1595 {
1596 global $MIOLO;
1597
1598 $caption = ( _M('Errors') );
1599
1600 $t = new MSimpleTable('');
1601 $t->setAttributes("class=\"m-prompt-box-error\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"100%\" border=\"0\"");
1602 $t->attributes['cell'][0][0] = "colspan=\"2\" class=\"m-prompt-box-error-title\"";
1603 $t->cell[0][0] = $caption;
1604 $t->attributes['cell'][1][0] = "valign=\"top\" width=\"60\"";
1605 $t->cell[1][0] = new ImageForm('', '', 'images/error.gif');
1606 $t->attributes['cell'][1][1] = "class=\"m-prompt-box-error-text\"";
1607 $leftmargin = '&nbsp;&nbsp;&nbsp;&nbsp;';
1608
1609 foreach ($this->errors as $e)
1610 {
1611 $msg .= $leftmargin . "-&nbsp;$e<br/>";
1612 }
1613
1614 $t->cell[1][1] = $msg;
1615 return $t;
1616 }
1617
1619 {
1620 $header[] = $this->generateFilter();
1621
1622 if ($this->data)
1623 {
1624 $header[] = $this->generateNavigationHeader();
1625 }
1626
1627 $header[] = $this->generateLinks();
1628
1629 return $header;
1630 }
1631
1633 {
1634 $tbl->attributes['row'][0] = "class=\"m-grid-row-heading\"";
1635 $p = 0;
1636
1637 if ( count($this->actions) )
1638 {
1639 $tbl->attributes['cell'][0][$p] = "width=\"16\" align=\"left\" class=\"m-grid-column-heading\"";
1640 $tbl->cell[0][$p++] = $this->actionColumnName;
1641 }
1642
1643 if ( $this->select != NULL )
1644 {
1645 $rowCount = count($this->data);
1646 $this->page->onLoad( "gridChkEachRow($rowCount,'".$this->name."');" );
1647 $tbl->attributes['cell'][0][$p] = "width=\"16\" align=\"center\" class=\"m-grid-column-heading\"";
1648 $tbl->cell[0][$p] = new CheckBox("chkAll", 'chkAction', '');
1649 $tbl->cell[0][$p++]->AddAttribute('onclick', "javascript:gridChkAll(this,$rowCount,'".$this->name."');");
1650 }
1651
1652 // generate column headings
1653 foreach ($this->columns as $k => $col)
1654 {
1655 if ( (!$col->visible) || (!$col->title) || ($col->hidden) )
1656 {
1657 continue;
1658 }
1659
1660 if ($col->order)
1661 {
1662 $this->orderby = $k;
1663 $colTitle = new MLinkButton('', $col->title, $this->getURL($this->filtered, true) );
1664 $colTitle->setClass('m-grid-column-order');
1665 $colTitle->setGenerateLinkButton( !$this->colSortingCleanURL );
1666 }
1667 else
1668 {
1669 $colTitle = $col->title;
1670 }
1671
1672 if ($col->width)
1673 {
1674 $attr = " width=\"$col->width\"";
1675 }
1676 else
1677 {
1678 // scrollable tables need col width
1679 if( $this->scrollable )
1680 {
1681 $this->manager->logMessage( _M("[WARNING] Using scrollable table, it's necessary to inform column width. ") );
1682 }
1683 }
1684
1685 $tbl->attributes['cell'][0][$p] = "class=\"m-grid-column-heading\" " . ( isset($attr) ? $attr : '');
1686 $tbl->cell[0][$p++] = $colTitle;
1687 }
1688 }
1689
1690 // This method corrects a problem when using scrollable table having
1691 // only one or few records. Adds a colspaned row.
1693 {
1694 if ( count($this->actions) )
1695 {
1696 $tbl->attributes['cell'][0][0] = "width=\"15\" align=\"left\" ";
1697 $tbl->cell[0][0] = '';
1698 }
1699 }
1700
1701 function generateActions(&$tbl)
1702 {
1703 $i = $this->currentRow + 1;
1704
1705 // Max of one column for actions
1706 $n = count($this->actions) ? 1 : 0;
1707
1708 if ( $this->gridMostraTotalNumeric && !empty($this->pn->gridCount) && $this->pn->gridCount < $i && ($n || $this->select != null) )
1709 {
1710 $tbl->attributes['cell'][$i][] = "align=\"center\" width=\"0\"";
1711 $tbl->cell[$i][] = new MDiv("{$this->id}_gridActions", "<span class='m-label'><b>TOTAL DA PÁGINA</b></span>", 'm-grid-actions');
1712 return;
1713 }
1714
1715 if ( $n )
1716 {
1717 $actions = '';
1718
1719 // generate action links
1720 foreach ( $this->actions as $k => $action )
1721 {
1722 $action->attributes();
1723 $a = $action->generate();
1724
1725 if ( is_object($a) )
1726 {
1727 $a = $a->generate();
1728 }
1729
1730 $actions .= "<td>$a</td>";
1731 }
1732
1733 /*
1734 * Inner table to align actions horizontally. IE7 does not support
1735 * "display: table-cell" and "float: left" does not force column to
1736 * align stuff horizontally.
1737 */
1738 $innerTable = "<table><tr>$actions</tr></table>";
1739
1740 if ( $this->gerarQuebraDeLinhaActions )
1741 {
1742 $innerTable = $this->gerarActions();
1743 }
1744
1745 $tbl->attributes['cell'][$i][] = "align=\"center\" width=\"0\"";
1746 $tbl->cell[$i][] = new MDiv("{$this->id}_gridActions", $innerTable, 'm-grid-actions');
1747 }
1748
1749 if ( $this->select != NULL )
1750 {
1751 $tbl->attributes['row'][$i] .= " id=\"row".$this->name."[{$this->currentRow}]\" ";
1752 $tbl->attributes['cell'][$i][$n] = "align=\"center\"";
1753 $select = $this->select->generate();
1754 $select->checked = ( array_search($i-1, $this->selecteds) !== false );
1755 $select->readonly = $this->selectsreadonly[$i-1];
1756 $tbl->cell[$i][$n] = $select;
1757 }
1758 }
1759
1763 function gerarActions()
1764 {
1765 }
1766
1768 {
1769 foreach ( $this->columns as $k => $col )
1770 {
1771 if ( $col instanceof MGridColumn )
1772 {
1773 $col->generate();
1774 }
1775 }
1776 }
1777
1784 function generateAlignColumn(&$column, $value)
1785 {
1786 }
1787
1788 function generateColumns($tbl, $row = null, $i = null)
1789 {
1790 $i = $this->currentRow + 1;
1791
1792 // Max of one column for actions
1793 $p = count($this->actions) ? 1 : 0;
1794
1795 if ( $this->select != NULL )
1796 {
1797 $p++;
1798 }
1799
1800 $firstVisible = 0;
1801
1802 foreach ( $this->columns as $k => $col )
1803 {
1804 if ( $this->gridMostraTotalNumeric && $k == $firstVisible && !empty($this->pn->gridCount) && $this->pn->gridCount == $this->currentRow && count($this->actions) == 0 && !$this->select )
1805 {
1806 if ( $col->visible ) {
1807 $col->control[$this->currentRow]->value = "<b>TOTAL DA PÁGINA</b>";
1808 }
1809 else
1810 {
1811 $firstVisible ++;
1812 }
1813 }
1814
1815 if (( ! $col->title ) || ( ! $col->visible ))
1816 {
1817 continue;
1818 }
1819
1820 // Store the controls on hidden columns to generate them later.
1821 if ( $col->hidden )
1822 {
1823 $this->hiddenControls[] = $col->control[$this->currentRow];
1824 continue;
1825 }
1826
1827 $control = $col->control[$this->currentRow];
1828 $attr = "";
1829
1830 $this->generateAlignColumn($col, $control->value);
1831
1832 if ( $col->nowrap )
1833 {
1834 $attr .= " nowrap ";
1835 }
1836
1837 if ( $col->width )
1838 {
1839 $attr .= " width=\"$col->width\"";
1840 }
1841
1842 if ( $col->align )
1843 {
1844 $attr .= " align=\"$col->align\"";
1845 }
1846
1847 $class = $col->getClass();
1848 $tbl->attributes['cell'][$i][$p] = "$attr class=\"$class\"";
1849 $tbl->cell[$i][$p++] = $control;
1850 }
1851 }
1852
1854 {
1855 $div = new MDiv('', $this->emptyMsg, 'gridAttention');
1856 return $div;
1857 }
1858
1859 function generateData()
1860 {
1861 global $state;
1862
1863 if ( ! $this->data || $this->generateDataCalled )
1864 {
1865 return;
1866 }
1867
1868 $this->generateDataCalled = true;
1869
1870 $this->orderby = $this->page->request('orderby');
1871 $isAssociativeGrid = !isset($this->columns[0]);
1872
1873 if ( $this->ordered = isset($this->orderby) && !$isAssociativeGrid )
1874 {
1875 $this->applyOrder( $this->orderby );
1876 $this->page->state->set('orderby', $this->orderby, $this->name);
1877 }
1878
1879 if ( $this->getFiltered() )
1880 {
1881 $this->applyFilter();
1882 }
1883
1884 if ( $this->pageLength )
1885 {
1886 $this->pn = new MGridNavigator( $this->pageLength, $this->rowCount,
1887 $this->getURL( $this->filtered, $this->ordered ),
1888 $this
1889 );
1890
1891 if ( $this->offset == NULL )
1892 {
1893 $this->data = $this->getPage();
1894 }
1895 }
1896 else
1897 {
1898 $this->pn = null;
1899 }
1900 }
1901
1902 function callRowMethod()
1903 {
1904 if ( isset($this->rowmethod) )
1905 {
1906 $i = $this->currentRow;
1907 $row = $this->data[$i];
1908
1909 $myRowClass = is_object($this->rowmethod[0]) ? get_class($this->rowmethod[0]) : $this->rowmethod[0];
1910 $myRowFunction = $this->rowmethod[1];
1911
1912 if (get_class($this) == $myRowClass)
1913 {
1914 $this->$myRowFunction($i, $row, $this->actions, $this->columns, $this);
1915 }
1916 else
1917 {
1918 // A grid é refletida para poder fazer o uses dela (necessário PHP7.0+)
1919 $reflectedGrid = new ReflectionClass($this);
1920 include_once ($reflectedGrid->getFileName());
1921
1922 $gridClass = new $myRowClass();
1923 $gridClass->$myRowFunction($i, $row, $this->actions, $this->columns, $this);
1924 }
1925
1926 }
1927 }
1928
1929 function generateBody($data = null)
1930 {
1931 global $MIOLO, $SCRIPT_NAME;
1932
1933 if ( $this->hasErrors() )
1934 {
1935 $this->generateErrors();
1936 }
1937
1938 $tblData = new MSimpleTable( 'tbody' . $this->id, "cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\" class=\"m-grid-body\"");
1939
1940 $tbodyId = 'tbody' . $this->id;
1941 $bodyId = 'body' . $this->id;
1942
1943 $this->page->onLoad(
1944 "if (typeof $('#{$tbodyId}').stickyTableHeaders == 'function' ) $('#{$tbodyId}').stickyTableHeaders();".
1945 "$('#{$bodyId}').on('scroll', function(){\$('#{$tbodyId}').stickyTableHeaders();});"
1946 );
1947
1948 $this->generateColumnsHeading($tblData);
1949
1950 if ($this->data)
1951 {
1952 // generate data rows
1953 $i = 0;
1954
1955 foreach ($this->data as $row)
1956 {
1957 $this->currentRow = $i;
1958 $rowId = ($i % 2) + 1;
1959 $rowClass = "m-grid-row-$rowId";
1960 $i++;
1961 $tblData->attributes['row'][$i] = "class=\"$rowClass\"";
1962 $this->generateColumnsControls();
1963 $this->callRowMethod();
1964 $this->generateActions($tblData);
1965 $this->generateColumns($tblData);
1966 } // foreach row
1967 } // if
1968 $tblData->setRowAttribute(0, "id", 'tbody'.$this->id.'first');
1969
1970 if( $this->scrollable )
1971 {
1972 $bodyHeader = new MDiv('head'.$this->id, null, 'm-grid-head', 'style="'.
1973 'width:'.$this->scrollWidth.';'.
1974 'overflow-x:hidden;"');
1975 $body = new MDiv('body'.$this->id, $tblData,'m-grid-body','style="'.
1976 'width:'.$this->scrollWidth.';'.
1977 'height:'.$this->scrollHeight.';'.
1978 'overflow:auto;" '
1979 );
1980 $body = new MDiv('', array($bodyHeader, $body) );
1981 }
1982 else
1983 {
1984 $body = $tblData;
1985 }
1986
1987 return $body;
1988 }
1989
1991 {
1992 $footer = is_array($this->footer) ? $this->footer : array($this->footer);
1993
1994 if ( ! $this->data )
1995 {
1996 $footer[] = $this->generateEmptyMsg();
1997 }
1998
1999 if ( $this->data )
2000 {
2001 $footer[] = $this->generateNavigationFooter();
2002 }
2003
2004 $footer[] = $this->generateControls();
2005
2006 return $footer;
2007 }
2008
2009 function getImage($src)
2010 {
2011 $url = $this->icons[$src];
2012 if ( ! $url )
2013 {
2014 if ( substr($src, 0, 1) == '/' ||
2015 substr($src, 0, 5) == 'http:' ||
2016 substr($src, 0, 6) == 'https:')
2017 {
2018 $url = $src;
2019 }
2020 else
2021 {
2022 $file = $this->manager->getConf('home.themes') . '/' . $this->manager->getConf('theme.main') . '/images/' . $src;
2023
2024 if ( file_exists($file) )
2025 {
2026 $url = $this->manager->getUI()->getImageTheme( $this->manager->getConf('theme.main'), $src );
2027 }
2028 else
2029 {
2030 $url = $this->manager->getUI()->getImage('', $src);
2031 }
2032 }
2033
2034 $this->icons[$src] = $url;
2035 }
2036
2037 return $url;
2038 }
2039
2040 public function generate()
2041 {
2042 $this->generateData();
2043 $header = $this->painter->generateToString($this->generateHeader());
2044 $title = $this->painter->generateToString($this->generateTitle());
2045 $body = $this->painter->generateToString($this->generateBody());
2046 $footer = $this->painter->generateToString($this->generateFooter());
2047
2048 $f = new MDiv('', array( $title, $header, $body, $footer, $this->hiddenControls ), 'm-grid-box');
2049
2050 if ( $this->width != '' )
2051 {
2052 $f->addStyle('width', $this->width);
2053 }
2054
2055 return $f->generate();
2056 }
2057
2061 public function hasOffset()
2062 {
2063 return $this->offset != NULL;
2064 }
2065
2066 public function getOffset()
2067 {
2068 return $this->offset;
2069 }
2070
2071 public function setOffset($offset)
2072 {
2073 $this->offset = $offset;
2074 }
2075
2080 public function ajustarFormatacaoGrid()
2081 {
2082 }
2083
2089 public function getQuery()
2090 {
2091 return $this->query;
2092 }
2093
2102 public function setQuery($sql = NULL, $dbconf = NULL, $rowCount = NULL, $returnAllData = false, $asAssociative = false, $consultaExportacao = false)
2103 {
2104 global $state;
2105
2106 if ( $sql == '' )
2107 {
2108 return;
2109 }
2110
2112 $db = $MIOLO->getDatabase($dbconf);
2113 $queryBackup = $sql;
2114 $sql = $this->normalizaConsulta($sql, $dbconf, $this->gridMostraTotalNumeric, ($consultaExportacao ? $this->columns : null));
2115
2116 // Seta o order by
2117 $orderBy = MIOLO::_REQUEST('orderby');
2118 if ( strlen($orderBy) > 0 )
2119 {
2120 $msql = new MSQL();
2121 $msql->setDb($MIOLO->GetDatabase());
2122 $msql->createFrom($sql);
2123 $msql->clearOrderBy();
2124
2125 // Adiciona o novo orderby
2126 ! is_numeric($orderBy) ? : $orderBy += 1;
2127 if (is_numeric($orderBy)) {
2128 $msql->setOrderBy($orderBy . ' ' . MIOLO::_REQUEST('ordermode'));
2129 }
2130 else
2131 {
2132 $msql->setOrderBy('"' . $orderBy . '" ' . MIOLO::_REQUEST('ordermode'));
2133 }
2134
2135 // Adicionado para alternar order mode entre asc e desc.
2136 $_REQUEST['ordermode'] == 'asc' ? $_REQUEST['ordermode'] = 'desc' : $_REQUEST['ordermode'] = 'asc';
2137 $sql = $msql->select();
2138
2139 // Avisa o php que o order by j? foi feito na base de dados
2140 $this->orderByDatabase = true;
2141 }
2142
2143 // Calculate the current offset
2144 $this->offset = ($this->pageNumber - 1) * $this->pageLength;
2146 if ( empty($query) )
2147 {
2148 $this->query = $query = "SELECT *, COUNT(*) OVER () AS rowCount FROM ({$sql}) AS MGRIDTABLE";
2149 $queryBackup = "SELECT *, COUNT(*) OVER () AS rowCount FROM ({$queryBackup}) AS MGRIDTABLE";
2150 }
2151
2152 $sql = $query;
2153 if ( !$returnAllData )
2154 {
2155 if( !strlen(strstr($query, ' LIMIT ')) > 0 && !strlen(strstr($query, ' OFFSET ')) > 0 )
2156 {
2157 $sqlWithLimit = "{$query} LIMIT $this->pageLength OFFSET $this->offset";
2158 }
2159 else
2160 {
2161 $sqlWithLimit = $query;
2162 }
2163
2164 $sql = $sqlWithLimit;
2165 if ( $this->gridMostraTotalNumeric )
2166 {
2167 $sql = $this->obterConsultaComSomatorios($sqlWithLimit);
2168 }
2169 }
2170
2171 try
2172 {
2173
2174 $data = $db->query($sql);
2175 $rowCount = $data[0][count($data[0]) - 1];
2176
2177 // Caso deva retornar os dados como array associativa, executa novamente a consulta
2178 // com LIMIT 1, para obter os nomes das colunas.
2179 if ( $asAssociative )
2180 {
2181 $sqlColumns = $this->obterConsultaComNomesDasColunas($query);
2182 $columns = $db->query($sqlColumns);
2183 $associativeData = array();
2184 foreach ( $data as $record )
2185 {
2186 $associativeValue = array();
2187 foreach ( $columns as $key => $column )
2188 {
2189 $associativeValue[$column[0]] = $record[$key];
2190 }
2191 $associativeData[] = $associativeValue;
2192 }
2193 $data = $associativeData;
2194 }
2195 }
2196 catch ( Exception $err )
2197 {
2198 // Caso por algum motivo tenham ocorrido erros ao tentar obter os totalizadores,
2199 // Executa a consulta original.
2200 $data = $db->query($queryBackup);
2201 $rowCount = $data[0][count($data[0]) - 1];
2202 }
2203
2204 // Converte datas do formato Y-m-d para o formato d/m/Y para exibição na grid
2205 // é feito aqui pois assim o sistema já terá ordenado os dados da grid. Ao tentar ordenar as datas vindas da
2206 // base já formatadas como string estava ficando fora de ordem.
2207 foreach ($data as $rowKey => $rowInfo)
2208 {
2209 foreach ($rowInfo as $columnKey => $columnInfo)
2210 {
2211 if ( SAGU::isDate($columnInfo) )
2212 {
2213 $data[$rowKey][$columnKey] = SAGU::convertDateToUser($columnInfo);
2214 }
2215 }
2216 }
2217
2218 $this->data = $data;
2219 $this->idResult = $db->getIdResult();
2220 $this->rowCount = $rowCount ?? $this->data[0][count($this->data[0]) - 1];
2221 $this->ajustarFormatacaoGrid();
2222
2223 return $this->data;
2224 }
2225
2233 public static function obterConsultaComSomatorios($query)
2234 {
2235 $randConsulta = rand();
2236 $sql = "
2237 CREATE TEMP TABLE consulta_{$randConsulta} ON COMMIT DROP AS (
2238 {$query}
2239 );
2240 SELECT *
2241 FROM consulta_{$randConsulta}
2242 UNION ALL
2243 SELECT *
2244 FROM somatorioDeValoresDaTabela(NULL::consulta_{$randConsulta})
2245 ";
2246
2247 return $sql;
2248 }
2249
2260 {
2261 $randConsulta = rand();
2262 $sql = "
2263 CREATE TEMP TABLE consulta_{$randConsulta} ON COMMIT DROP AS (
2264 {$query} LIMIT 1
2265 );
2266 SELECT column_name
2267 FROM information_schema.columns
2268 WHERE table_name = 'consulta_{$randConsulta}' ORDER BY ordinal_position
2269 ";
2270
2271 return $sql;
2272 }
2273
2282 public static function normalizaConsulta($sql, $dbconf, $gridMostraTotalNumeric = false, $columnsGrid = array())
2283 {
2284 if ( $gridMostraTotalNumeric )
2285 {
2287 $db = $MIOLO->getDatabase($dbconf);
2288
2289 $msql = new MSQL();
2290 $msql->considerarTabelasSubSelects = true;
2291 $msql->setDb($MIOLO->GetDatabase());
2292 $msql->createFrom($sql);
2293 $columns = array();
2294 $count = 1;
2295
2296 // Seta alias para colunas sem alias
2297 foreach ($msql->getColumns() as $key => $column)
2298 {
2299 // Remove do sql as colunas que não são exibidas
2300 if ( count($columnsGrid) > 0 )
2301 {
2302 $columnVisible = false;
2303 foreach ( $columnsGrid as $keyAux => $columnAux )
2304 {
2305 // trata as chaves compostas
2306 if ( !is_int($keyAux) )
2307 {
2308 if ( stripos($key, $keyAux) !== false )
2309 {
2310 $columnVisible = true;
2311 if ($columnAux->hidden || !$columnAux->visible || !($columnAux->title))
2312 {
2313 $columnVisible = false;
2314 }
2315 break;
2316 }
2317 }
2318 else
2319 {
2320 $valueKeyColumn = array_search($key, array_values($msql->getColumns()));
2321 if ( $keyAux == $valueKeyColumn )
2322 {
2323 $columnVisible = true;
2324 if ( $columnAux->hidden || !$columnAux->visible || !($columnAux->title) )
2325 {
2326 $columnVisible = false;
2327 break;
2328 }
2329 }
2330 }
2331 }
2332
2333 if ( !$columnVisible )
2334 {
2335 continue;
2336 }
2337 }
2338
2339 // Controles para não ocorrerm erros de tipagem.
2340 $auxColumn = ($column == 'null' || $column == 'NULL') ? 'NULL::TEXT' : $column;
2341 $column = str_replace('null as', 'NULL::TEXT AS', $auxColumn);
2342 $column = str_replace('NULL AS', 'NULL::TEXT AS', $column);
2343 $column = str_replace('null AS', 'NULL::TEXT AS', $column);
2344 $column = str_replace('NULL as', 'NULL::TEXT AS', $column);
2345
2346 $columns[$key . '_' . $count] = $column;
2347 $explodeColumn = explode(" as ", strtolower($column));
2348 if (count($explodeColumn) < 2 && $column != '*')
2349 {
2350 $columns[$key . '_' . $count] = $column . " AS coluna_" . $count;
2351 }
2352
2353 $count++;
2354 }
2355
2356 $msql->clearColumns();
2357 $msql->setColumns($columns);
2358 $sql = $msql->select();
2359 }
2360
2361 return $sql;
2362 }
2363
2364 public function hideColumn($column)
2365 {
2366 $this->page->addStyleCode("table#tbody$this->id td:nth-child($column) {display:none;}");
2367 }
2368
2372 public function getIdResult()
2373 {
2374 return $this->idResult;
2375 }
2376
2380 public function setIdResult($idResult)
2381 {
2382 $this->idResult = $idResult;
2383 }
2384
2386 {
2387 return $this->gridMostraTotalNumeric;
2388 }
2389
2390 public function setGridMostraTotalNumeric($gridMostraTotalNumeric)
2391 {
2392 $this->gridMostraTotalNumeric = $gridMostraTotalNumeric;
2393 }
2394}
2395
2396?>
const COLOR_GREEN
const COLOR_RED
attributes( $mergeDuplicates=false)
Definição mcontrol.class:486
setClass( $cssClass, $add=true)
Definição mcontrol.class:398
addStyleFile( $styleFile)
Definição mcontrol.class:412
__construct($grid, $value, $href, $alt=NULL)
__construct($grid, $index=0)
__construct($grid, $value, $href)
setTarget($target)
__construct($grid, $type, $alt, $value, $href, $enabled=true, $index=null)
setOrder($order)
__construct($title='', $align='left', $nowrap=false, $width=0, $visible=true, $options=null, $order=false, $replace=NULL, $numberFormat=false, $colorOptions=array())
setControl($control, $pos=0)
setGrid(MGrid $grid)
setBasecontrol($basecontrol)
setAlign($align)
setValue($value)
setReplace($replace)
setOptions($options)
setTitle($title)
generateColoredLabels($valueOfColumn)
setHidden($hidden)
setNowrap($nowrap)
formatSpecificColumnValues()
setFooter($footer)
setWidth($width)
setIndex($index)
__construct($control, $title='', $align='left', $nowrap=false, $width=0, $visible=true)
__construct($grid, &$control, $type='text', $index=0, $enabled=false)
__construct($grid, $label, $options=array(), $index=0, $enabled=false)
__construct($grid, $label, $value='', $index=0, $enabled=false)
__construct($grid, $type, $label, $value, $index, $enabled=false)
generateNavigationFooter()
setUseSelecteds($opt)
correctActionColSpan($tbl)
setSelecteds($s)
generateColumnsHeading($tbl)
setScrollHeight($height='99%')
getFilterControl($index)
addFilterControl($index, $control, $type='text')
addActionIcon($alt, $icon, $href, $index=null)
addActionDelete($href, $alt='Delete')
getURL($filter=false, $order=false, $item='')
headerLink($id, $label, $href)
handlerSelecteds()
setFilter($status)
applyOrder($column)
setColumnAttr($col, $attr, $value)
setPageLength($pageLength)
ajustarFormatacaoGrid()
setGridMostraTotalNumeric($gridMostraTotalNumeric)
getFilterValue($index)
setControls($controls)
setScrollWidth($width='99%')
showID($state)
generateColumns($tbl, $row=null, $i=null)
isGridMostraTotalNumeric()
addActionText($alt, $text, $href, $index=0)
static obterConsultaComSomatorios($query)
addActionUpdate($href)
setShowHeaders( $show=true)
static obterConsultaComNomesDasColunas($query)
setOffset($offset)
setLinkType($linktype)
setTitle($title)
hideColumn($column)
setCurrentPage($pageNumber)
generateNavigationHeader()
setColumns($columns)
getDataValue($row, $col)
setClose($action)
setFiltered($value=false)
setData($data, $rowCount=null)
static normalizaConsulta($sql, $dbconf, $gridMostraTotalNumeric=false, $columnsGrid=array())
$gerarQuebraDeLinhaActions
generateColumnsControls()
generateControls()
setIdResult($idResult)
setQuery($sql=NULL, $dbconf=NULL, $rowCount=NULL, $returnAllData=false, $asAssociative=false, $consultaExportacao=false)
generateEmptyMsg()
setFooter($footer)
setWidth($width)
generateBody($data=null)
generateActions(&$tbl)
setIndex($index)
addFilterSelection($index, $label, $options, $value='')
getImage($src)
generateAlignColumn(&$column, $value)
addFilterText($index, $label, $value='')
setRowMethod($class, $method)
__construct($data, $columns, $href, $pageLength=15, $index=0, $name='', $useSelecteds=TRUE, $useNavigator=TRUE, $showExport=FALSE, $gridMostraTotalNumeric=false, $fixedTableHeader=true)
setButtons($aButtons)
setIsScrollable($scrollable=true, $width='99%', $height='99%')
addError($err)
static _REQUEST( $vars, $from='ALL')
Definição miolo.class:1109
static getInstance()
Definição miolo.class:134
Definição msql.class:8
static NVL($value1, $value2)
Definição mutil.class:38
static getBooleanValue($value)
Definição mutil.class:100
$action
Definição base.php:4
$url
Definição base.php:2