Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
17.97% covered (danger)
17.97%
23 / 128
CRAP
13.40% covered (danger)
13.40%
168 / 1254
TGrid
0.00% covered (danger)
0.00%
0 / 1
17.97% covered (danger)
17.97%
23 / 128
197256.62
13.26% covered (danger)
13.26%
166 / 1252
 __construct
0.00% covered (danger)
0.00%
0 / 1
11.06
92.00% covered (success)
92.00%
46 / 50
 getRealTotalRowsSqlPaginator
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
1 / 1
 setRealTotalRowsSqlPaginator
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 getQtdColumns
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setQtdColumns
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 show
0.00% covered (danger)
0.00%
0 / 1
18090
0.00% covered (danger)
0.00%
0 / 380
 showEditAutoComplete
0.00% covered (danger)
0.00%
0 / 1
90
0.00% covered (danger)
0.00%
0 / 24
 includeHiddenField
0.00% covered (danger)
0.00%
0 / 1
42
0.00% covered (danger)
0.00%
0 / 14
 backgroundColorRowGrid
0.00% covered (danger)
0.00%
0 / 1
20
0.00% covered (danger)
0.00%
0 / 6
 getTdValueByType
0.00% covered (danger)
0.00%
0 / 1
20
0.00% covered (danger)
0.00%
0 / 7
 getTdValue
0.00% covered (danger)
0.00%
0 / 1
20
0.00% covered (danger)
0.00%
0 / 11
 showNoRowsFound
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 9
 showColumnActionGrid
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 7
 showTitle
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 3
 showColumn
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 3
 showGridProperty
0.00% covered (danger)
0.00%
0 / 1
12
0.00% covered (danger)
0.00%
0 / 17
 showButonsUpdateDelete
0.00% covered (danger)
0.00%
0 / 1
30
0.00% covered (danger)
0.00%
0 / 11
 showValidateDraws
0.00% covered (danger)
0.00%
0 / 1
132
0.00% covered (danger)
0.00%
0 / 11
 validateMaxRowsWithoutUrl
0.00% covered (danger)
0.00%
0 / 1
12
0.00% covered (danger)
0.00%
0 / 3
 sortDataByColum
100.00% covered (success)
100.00%
1 / 1
2
100.00% covered (success)
100.00%
3 / 3
 generateFileExcel
0.00% covered (danger)
0.00%
0 / 1
20
0.00% covered (danger)
0.00%
0 / 24
 getColumns
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 getColumn
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 4
 getColumnCount
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 3
 addColumn
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
5 / 5
 addColumnCompact
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 5
 addHiddenField
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 3
 getHiddenField
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 addActionColumn
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 setTitle
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 getTitle
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
1 / 1
 setData
0.00% covered (danger)
0.00%
0 / 1
3.04
83.33% covered (success)
83.33%
5 / 6
 getData
0.00% covered (danger)
0.00%
0 / 1
150.56
28.57% covered (danger)
28.57%
10 / 35
 addKeyField
0.00% covered (danger)
0.00%
0 / 1
6.40
77.78% covered (success)
77.78%
7 / 9
 getKeyField
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
1 / 1
 addButton
0.00% covered (danger)
0.00%
0 / 1
20
0.00% covered (danger)
0.00%
0 / 7
 addButtonAjax
0.00% covered (danger)
0.00%
0 / 1
20
0.00% covered (danger)
0.00%
0 / 7
 getButtons
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setOnDrawRow
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 getOnDrawRow
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setOnDrawCell
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 getOnDrawCell
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setOnDrawHeaderCell
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 getOnDrawHeaderCell
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setOnDrawActionButton
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 getOnDrawActionButton
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setUpdateFields
0.00% covered (danger)
0.00%
0 / 1
8.10
88.24% covered (success)
88.24%
15 / 17
 getUpdateFields
0.00% covered (danger)
0.00%
0 / 1
30
0.00% covered (danger)
0.00%
0 / 8
 clearUpdateFields
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getWidth
0.00% covered (danger)
0.00%
0 / 1
20
0.00% covered (danger)
0.00%
0 / 7
 getHeight
0.00% covered (danger)
0.00%
0 / 1
20
0.00% covered (danger)
0.00%
0 / 7
 setWidth
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 setHeight
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 setActionColumnTitle
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getActionColumnTitle
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 3
 getRowData
0.00% covered (danger)
0.00%
0 / 1
12
0.00% covered (danger)
0.00%
0 / 5
 setZebrarColors
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
4 / 4
 getZebrarColors
0.00% covered (danger)
0.00%
0 / 1
30
0.00% covered (danger)
0.00%
0 / 3
 addTextColumn
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 4
 addAutoCompleteColumn
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 4
 addDateColumn
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 3
 addNumberColumn
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 3
 addCheckColumn
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 5
 addRadioColumn
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 5
 addSelectColumn
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 3
 addMemoColumn
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 3
 addRowNumColumn
0.00% covered (danger)
0.00%
0 / 1
20
0.00% covered (danger)
0.00%
0 / 6
 getRowNumWithPaginator
100.00% covered (success)
100.00%
1 / 1
2
100.00% covered (success)
100.00%
4 / 4
 getRowCount
100.00% covered (success)
100.00%
1 / 1
3
100.00% covered (success)
100.00%
8 / 8
 setReadOnly
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 3
 getReadOnly
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setMaxRows
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 getMaxRows
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setNavButtons
0.00% covered (danger)
0.00%
0 / 1
210
0.00% covered (danger)
0.00%
0 / 54
 setBvars
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getBvars
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setCache
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getCache
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 getCreateDefaultButtons
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 1
 enableDefaultButtons
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 2
 setUseDefaultImages
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getUseDefaultImages
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 1
 setExportExcel
100.00% covered (success)
100.00%
1 / 1
2
100.00% covered (success)
100.00%
2 / 2
 getExportExcel
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 autoCreateColumns
0.00% covered (danger)
0.00%
0 / 1
12
0.00% covered (danger)
0.00%
0 / 8
 setForm
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 5
 getForm
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setUrl
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getUrl
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 configOffLine
0.00% covered (danger)
0.00%
0 / 1
9312
0.00% covered (danger)
0.00%
0 / 226
 setNewRecordColor
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getNewRecordColor
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 1
 setEditedRecordColor
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getEditedRecordColor
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 1
 setSavedRecordColor
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getSavedRecordColor
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 1
 getDeletedRecordColor
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 1
 setOnGetAutocompleteParameters
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getOnGetAutocompleteParameters
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 getFooter
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 addFooter
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 3
 setFooter
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 3
 setSortable
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 getSortable
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 addExcelHeadField
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getExcelHeadField
0.00% covered (danger)
0.00%
0 / 1
20
0.00% covered (danger)
0.00%
0 / 6
 getTitleCell
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setShowCollapsed
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 2
 getShowCollapsed
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 3
 getData2Excel
0.00% covered (danger)
0.00%
0 / 1
132
0.00% covered (danger)
0.00%
0 / 18
 setCreateDefaultEditButton
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 getCreateDefaultEditButton
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 1
 setCreateDefaultDeleteButton
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 getCreateDefaultDeleteButton
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 1
 setShowAdicionarButton
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 getShowAdicionarButton
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 1
 setNoWrap
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getNoWrap
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 1
 setNoDataMessage
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 getNoDataMessage
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 sortArray
0.00% covered (danger)
0.00%
0 / 1
26.51
70.27% covered (success)
70.27%
26 / 37
 setDisabledButtonImage
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getDisabledButtonImage
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setExportFullData
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getExportFullData
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 extractFormFields
0.00% covered (danger)
0.00%
0 / 1
56
0.00% covered (danger)
0.00%
0 / 13
 addColumnConfig
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 2
 getColumnConfig
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 1
1<?php
2/*
3 * Formdin Framework
4 * Copyright (C) 2012 Ministério do Planejamento
5 * Criado por Luís Eugênio Barbosa
6 * Essa versão é um Fork https://github.com/bjverde/formDin
7 *
8 * ----------------------------------------------------------------------------
9 * This file is part of Formdin Framework.
10 *
11 * Formdin Framework is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public License version 3
13 * as published by the Free Software Foundation.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public License version 3
21 * along with this program; if not,  see <http://www.gnu.org/licenses/>
22 * or write to the Free Software Foundation, Inc., 51 Franklin Street,
23 * Fifth Floor, Boston, MA  02110-1301, USA.
24 * ----------------------------------------------------------------------------
25 * Este arquivo é parte do Framework Formdin.
26 *
27 * O Framework Formdin é um software livre; você pode redistribuí-lo e/ou
28 * modificá-lo dentro dos termos da GNU LGPL versão 3 como publicada pela Fundação
29 * do Software Livre (FSF).
30 *
31 * Este programa é distribuído na esperança que possa ser útil, mas SEM NENHUMA
32 * GARANTIA; sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou
33 * APLICAÇÃO EM PARTICULAR. Veja a Licença Pública Geral GNU/LGPL em português
34 * para maiores detalhes.
35 *
36 * Você deve ter recebido uma cópia da GNU LGPL versão 3, sob o título
37 * "LICENCA.txt", junto com esse programa. Se não, acesse <http://www.gnu.org/licenses/>
38 * ou escreva para a Fundação do Software Livre (FSF) Inc.,
39 * 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA.
40 */
41
42if(!defined('ENCODINGS')){ define('ENCODINGS','UTF-8'); }
43
44/**
45 * @todo    - possibilitar exibir ou não o botão editar e excluir do grid-offline
46 * @todo    - definir o foco para o primeiro campo do formulario do grid-ofline se não tiver sido informado pelo usuario
47 */
48include_once( 'autoload_formdin.php');
49class TGrid extends TTable
50{
51    private $width;
52    private $height;
53    private $columns;
54    private $title;
55    private $titleCell;
56    private $bodyCell;
57    private $footerCell;
58    private $data;
59    private $keyField;
60    private $updateFields; // campos que serão atualizados no formulario antes de executar a ação
61    private $buttons;
62    private $onDrawRow;
63    private $onDrawCell;
64    private $onDrawHeaderCell;
65    private $onDrawActionButton;
66    private $onGetAutocompleteParameters;
67    private $actionColumnTitle;
68    private $zebrarColors;
69    private $hiddenField;
70    private $readOnly;
71    private $maxRows;
72    private $realTotalRowsSqlPaginator;
73    private $url;
74    private $bvars;
75    private $cache;
76    private $createDefaultButtons;
77    private $createDefaultImages;
78    private $exportExcel;
79    private $excelHeadFields;
80    private $noWrap;
81    private $noDataMessage;
82    
83    // dados do grid offline
84    private $form;
85    private $newRecordColor;
86    private $editedRecordColor;
87    private $savedRecordColor;
88    private $deletedRecordColor;
89    private $sortable;
90    private $showCollapsed;
91    
92    private $autocomplete;
93    private $javaScript;
94    
95    protected $numPages;
96    protected $currentPage;
97    
98    private $createDefaultEditButton;
99    private $createDefaultDeleteButton;
100    private $createDefaultAdicionarButton;
101    private $showAdicionarButton; // botão do grid offline
102    private $disableButtonImage=null;
103    private $exportFullData;
104    private $columnConfig;
105    
106    private $qtdColumns;
107    private $tbody;
108    
109    
110    /**
111     * Classe para criação de grides
112     *
113     * Parametros do evento onDrawHeaderCell
114     *     1) $th            - objeto TElement
115     *     2) $objColumn     - objeto TGridColum
116     *     3) $objHeader     - objeto TElement
117     *
118     * Parametros do envento onDrawRow
119     *     1) $row         - objeto TGridRow
120     *     2) $rowNum         - número da linha corrente
121     *     3) $aData        - o array de dados da linha ex: $res[''][n]
122     *
123     * Parametros do envento onDrawCell
124     *     1) $rowNum         - número da linha corrente
125     *     2) $cell        - objeto TTableCell
126     *     3) $objColumn    - objeto TGrideColum
127     *     4) $aData        - o array de dados da linha ex: $res[''][n]
128     *     5) $edit        - o objeto campo quando a coluna for um campo de edição
129     *   ex: function ondrawCell($rowNum=null,$cell=null,$objColumn=null,$aData=null,$edit=null)
130     *
131     * Parametros do evento onDrawActionButton
132     *     1) $rowNum         - número da linha corrente
133     *     2) $button         - objeto TButton
134     *     3) $objColumn    - objeto TGrideColum
135     *     4) $aData        - o array de dados da linha ex: $res[''][n]
136     *   Ex: function tratarBotoes($rowNum,$button,$objColumn,$aData);
137     *
138     * Parametros do evento onGetAutocompleteParameters
139     *     1) $ac             - classe TAutocomplete
140     *     2) $aData        - o array de dados da linha ex: $res[''][n]
141     *     3) $rowNum         - número da linha corrente
142     *     3) $cell        - objeto TTableCell
143     *     4) $objColumn    - objeto TGrideColum
144     *
145     *
146     * @param string $strName          - 1: ID do campo
147     * @param string $strTitle         - 2: Titulo do campo
148     * @param array $mixData           - 3: Array de dados
149     * @param mixed $strHeight         - 4: Altura 
150     * @param mixed $strWidth          - 5: Largura
151     * @param mixed $strKeyField       - 6: Chave primaria
152     * @param array $mixUpdateFields   - 7: Campos do form origem que serão atualizados ao selecionar o item desejado. Separados por virgulas seguindo o padrão <campo_tabela> | <campo_formulario> , <campo_tabela> | <campo_formulario>
153     * @param mixed $intMaxRows        - 8: Qtd Max de linhas
154     * @param mixed $strRequestUrl     - 9: Url request do form
155     * @param mixed $strOnDrawCell
156     * @param mixed $strOnDrawRow
157     * @param mixed $strOnDrawHeaderCell
158     * @param mixed $strOnDrawActionButton
159     * @return TGrid
160     */
161    public function __construct( $strName
162                               , $strTitle = null
163                               , $mixData = null
164                               , $strHeight = null
165                               , $strWidth = null
166                               , $strKeyField = null
167                               , $mixUpdateFields = null
168                               , $intMaxRows = null
169                               , $strRequestUrl = null
170                               , $strOnDrawCell = null
171                               , $strOnDrawRow = null
172                               , $strOnDrawHeaderCell = null
173                               , $strOnDrawActionButton = null )
174    {
175        parent::__construct( $strName );
176        parent::clearCss();
177        $this->setTitle( $strTitle );
178        $this->setData( $mixData );
179        $this->addKeyField( $strKeyField );
180        $this->setOnDrawRow( $strOnDrawRow );
181        $this->setOnDrawHeaderCell( $strOnDrawHeaderCell );
182        $this->setOnDrawCell( $strOnDrawCell );
183        $this->setOnDrawActionButton( $strOnDrawActionButton );
184        $this->setUpdateFields( is_null( $mixUpdateFields ) ? $strKeyField : $mixUpdateFields );
185        $this->setMaxRows( $intMaxRows );
186        if( isset( $_REQUEST[ 'modulo' ] ) )
187        {
188            $this->setUrl( ( is_null( $strRequestUrl ) ? $_REQUEST[ 'modulo' ] : $strRequestUrl ) );
189            
190        }
191        $this->setExportExcel( true );
192        $this->setSortable( true ); // permitir ordernar clicando no titulo da coluna
193        $this->setCreateDefaultDeleteButton( true );
194        $this->setCreateDefaultEditButton( true );
195        $this->setShowAdicionarButton( true );
196        $this->setNoDataMessage('Nenhum registro cadastrado!');
197        // css da table principal ( externa )
198        $this->setProperty( 'border', 0 );
199        $this->setProperty( 'cellspacing', 0 );
200        $this->setProperty( 'cellpadding', 0 );
201        $this->setCss( 'border', '1px solid silver' );
202        $this->setClass('tablesorter',false);
203        
204        // criar o titulo do gride
205        $trTitle = $this->addRow();
206        $this->titleCell = $trTitle->addCell();
207        $this->titleCell->setId( $this->getId() . '_title' );
208        $this->titleCell->setClass( 'fwGridTitle' );
209        $this->titleCell->setCss( 'text-align', 'center' );
210        
211        // criar o corpo do gride
212        $trBody = $this->addRow();
213        $this->bodyCell = $trBody->addCell();
214        $this->bodyCell->setId( $this->getId() . '_body' );
215        
216        // definir as medidas
217        $strWidth = is_null( $strWidth ) ? '100%' : $strWidth;
218        $this->setWidth( $strWidth );
219        $this->setHeight( $strHeight );
220        
221        // criar o rodape do gride
222        $trFooter = $this->addRow();
223        $this->footerCell = $trFooter->addCell();
224        $this->footerCell->setId( $this->getId() . '_footer' );
225        $this->footerCell->setClass( 'fwGridFooter' );
226        $this->footerCell->setCss( 'text-align', 'left' );
227        
228        // zebrar o gride
229        $this->setZebrarColors( '#ffffff', '#efefef' );
230        
231        // iniciar as variáveis de controle de paginação
232        $this->currentPage = 1;
233        $this->numPages = 0;
234        
235        if ( isset( $_REQUEST[ 'TGrid' ] ) && $_REQUEST[ 'TGrid' ] > 0 ) {
236            /**
237             * @todo alterar a chamada do gride para fwAjaxRequest e não mais pela json.onLoad();
238             */
239            $_REQUEST[ 'dataType' ] = 'text'; // evitar problema com a chamada pela fwAjaxRequest
240        }
241        
242        if ( isset( $_REQUEST[ 'page' ] ) && $_REQUEST[ 'page' ] > 0 ) {
243            // chamada via ajax
244            $this->currentPage = ( int ) $_REQUEST[ 'page' ];
245        }
246        else if( isset( $_REQUEST[ $this->getId() . '_jumpToPage' ] ) && $_REQUEST[ $this->getId() . '_jumpToPage' ] > 0 ) {
247            // chamada via post
248            $this->currentPage = ( int ) $_REQUEST[ $this->getId() . '_jumpToPage' ];
249        }
250    }
251    
252    //------------------------------------------------------------------------------------
253    /**
254     * Retorna o numero de regristros quando for usar uma pagina de banco e não apenas paginação de tela
255     *
256     * @return int
257     */
258    public function getRealTotalRowsSqlPaginator(){
259        return $this->realTotalRowsSqlPaginator;
260    }
261    
262    //------------------------------------------------------------------------------------
263    /**
264     * Numero real de registros, deve ser utilizando somento com paginação de banco
265     * está relacionado com setMaxRows
266     *
267     * @param int $realTotalRowsSqlPaginator
268     * @return void
269     */
270    public function setRealTotalRowsSqlPaginator($realTotalRowsSqlPaginator){
271        $this->realTotalRowsSqlPaginator = $realTotalRowsSqlPaginator;
272    }
273    
274    //------------------------------------------------------------------------------------
275    public function getQtdColumns(){
276        return $this->qtdColumns;
277    }
278    
279    //------------------------------------------------------------------------------------
280    public function setQtdColumns($qtdColumns){
281        $this->qtdColumns = $qtdColumns;
282    }
283        
284    //------------------------------------------------------------------------------------
285    public function show( $boolPrint = true ) {
286        // quando for requisição de paginação do gride, limpar o buffer de saida
287        if( isset($_REQUEST['page'] ) && isset( $_REQUEST['TGrid'] ) ) {
288            ob_clean();
289        }
290        
291        $this->showGridProperty();
292        
293        if ( $this->getColumnCount() == 0 ){
294            // nenhuma coluna adicionada
295            $row = $this->addRow();
296            $row->addCell( 'nenhuma coluna adicionada' );
297        }else{
298            $this->showButonsUpdateDelete();
299            // calcular a quantidade de colunas
300            $qtdColumns = $this->getColumnCount() + ( count( $this->getButtons() ) > 0 ? 1 : 0 );
301            $this->setQtdColumns($qtdColumns);
302            
303            // ajustar colspan do header e footer
304            $this->titleCell->setProperty( 'colspan',  $this->getQtdColumns() );
305            $this->footerCell->setProperty( 'colspan', $this->getQtdColumns() );
306            
307            // exibir o titulo do gride
308            $this->titleCell->add( $this->getTitle() );
309            
310            if ( $this->getCss( 'font-size' ) ) {
311                if ( !$this->titleCell->getCss( 'font-size' ) ) {
312                    $this->titleCell->setcss( 'font-size', $this->getCss( 'font-size' ) );
313                }
314            }
315            $this->bodyCell->setProperty( 'valign', 'top' );
316            $this->bodyCell->setProperty( 'bgcolor', 'transparent' );
317            
318            $this->bodyCell->add( $divScrollArea = new TElement( 'div' ) );
319            $divScrollArea->clearCss();
320            $divScrollArea->setClass( 'fwGridBody' );
321            $divScrollArea->setCss( 'width', $this->getWidth() );
322            $divScrollArea->setCss( 'height', $this->getHeight() );
323            
324            $divScrollArea->add( $tableGrid = new TTable( $this->getId() . '_table' ) );
325            $tableGrid->setProperty( 'border', '0' );
326            $tableGrid->setProperty( 'cellspacing', '0' );
327            $tableGrid->setProperty( 'cellpadding', '0' );
328            
329            $tableGrid->setCss( 'width', '100%' );
330            $tableGrid->setCss( 'border-left', '1px solid silver' );
331            $tableGrid->setCss( 'border-right', '1px solid silver' );
332            //$tableGrid->setCss('border-collapse','collapse');
333            //$tableGrid->setCss('height','auto');
334            
335            // thead e tbody
336            $tableGrid->add( $thead = new TElement( 'thead' ) );
337            $thead->clearCss();
338            $thead->setClass( 'fwHeaderBar' );
339            $thead->add( $row = new TTableRow() );
340            $row->clearCss();
341            $this->tbody = new TElement( 'tbody' );
342            $tableGrid->add( $this->tbody );
343            $this->tbody->clearCss();
344            
345            $this->showValidateDraws();
346            $this->showColumnActionGrid();
347            
348            // contador de colunas
349            $colIndex = 0;
350            $colSort  = null;
351            $headersSortable = '';
352            // criar as colunas titulo do gride
353            foreach( $this->getColumns() as $name => $objColumn ) {
354                // aplicar as configurações definidas pelo usuário
355                $objConfig = $this->getColumnConfig($colIndex);
356                
357                if( !is_null( $objConfig ) ) {
358                    if( $objConfig->width) {
359                        $objColumn->setWidth( $objConfig->width);
360                    }
361                    if( $objConfig->align ) {
362                        $objColumn->setTextAlign( $objConfig->align);
363                    }
364                    if( $objConfig->arrCss ){
365                        $objColumn->setCss( $objConfig->arrCss);
366                    }
367                    if( $objConfig->visible === false ) {
368                        $objColumn->setVisible( false );
369                    }
370                }
371                if( $objColumn->getVisible() ) {
372                    if ( ! $this->getSortable()  ) {
373                        $objColumn->setSortable( false );
374                    }
375                    if( ! $objColumn->getSortable() ) {
376                        $headersSortable .= ( ($headersSortable == '' ) ? '' :',' );
377                        $headersSortable .= $colIndex.': {sorter: false}';
378                    } else {
379                        if( is_null($colSort)) {
380                            $colSort = $colIndex;
381                        }
382                    }
383                    $objColumn->setGridId( $this->getId() );
384                    $objColumn->setColIndex( ++$colIndex );
385                    
386                    $th = new TElement( 'th' );
387                    $th->setId( $this->getid().'_th_' . $objColumn->getId() );
388                    
389                    $th->clearCss();
390                    $objColumn->setCss( 'width', $objColumn->getWidth() );
391                    $th->setClass( 'fwGridHeader' );
392                    $th->setCss( 'width', $objColumn->getWidth() );
393                    $th->setCss( 'text-align', $objColumn->getHeaderAlign() );
394                    $th->setAttribute('grid_id',$this->getId());
395                    $th->setAttribute('column_index',$objColumn->getColIndex());
396                    if( $objColumn->getId()=='col_action')
397                    {
398                        $th->setAttribute( 'column_name', $this->getId().'_action' );
399                    }
400                    else
401                    {
402                        $th->setAttribute( 'column_name', strtolower( $objColumn->getFieldName() ) );
403                    }
404                    
405                    if ( $objColumn->getHeader()->getCss( 'background-color' ) )
406                    {
407                        $th->setCss( 'background-color', $objColumn->getHeader()->getCss( 'background-color' ) );
408                    }
409                    $objHeader = $objColumn->getHeader();
410                    $objHeader->setId( $th->getId() . '_label' );
411                    
412                    if ( $this->getCss( 'font-size' ) )
413                    {
414                        if ( !$objHeader->getCss( 'font-size' ) )
415                        {
416                            $objHeader->setCss( 'font-size', $this->getCss( 'font-size' ) );
417                        }
418                    }
419                    $th->add( $objHeader );
420                    
421                    if ( $this->getOnDrawHeaderCell() && function_exists( $this->getOnDrawHeaderCell() ) ) {
422                        call_user_func( $this->onDrawHeaderCell, $objHeader, $objColumn, $th );
423                    }else{
424                        $th->add( $th->getValue() );
425                    }
426                    
427                    if ( $this->getReadOnly() ) {
428                        $objColumn->setReadOnly( true );
429                    }
430                    
431                    // colcocar checkbox no titulo se a coluna for do tipo checkbox
432                    if ( $objColumn->getDataType() == 'checkbox' ) {
433                        if ( $objColumn->getAllowCheckAll() )
434                        {
435                            $chk = new TElement( 'input' );
436                            $chk->setProperty( 'type', 'checkbox' );
437                            $chk->setProperty( 'value', '1' );
438                            $chk->setId( 'chk_' . $objColumn->getId() . '_header' );
439                            $chk->setCss( 'cursor', 'pointer' );
440                            $chk->setProperty( 'title', 'marcar/desmarcar todos' );
441                            $chk->addEvent( 'onclick', "fwGridCheckUncheckAll(this,'{$objColumn->getEditName()}',event)" );
442                            if ( $objColumn->getReadOnly() )
443                            {
444                                $chk->setProperty( 'disabled', 'true' );
445                            }
446                            
447                            if ( isset( $_POST[ $chk->getId()] ) && $_POST[ $chk->getId()] == 1 )
448                            {
449                                $chk->setProperty( 'checked', '' );
450                            }
451                            $divChk = new TElement('div');
452                            $divChk->setCss(array('padding-left'=>'1.5px','background-color'=>'transparent','display'=>'table-cell','vertical-align'=>'middle') );
453                            $divChk->add($chk);
454                            $divVal = new TElement('div');
455                            $divVal->setCss(array('background-color'=>'transparent','display'=>'table-cell','vertical-align'=>'middle' ) );
456                            $divVal->add($objHeader->getValue());
457                            $objHeader->setValue( $divChk->show(false).$divVal->show(false) );
458                        }
459                    }
460                    $row->add( $th );
461                }else{
462                    $colIndex++;
463                }
464            }
465            
466            $tableSorterCfg = '';
467            if( $headersSortable != '' ) {
468                $tableSorterCfg .= 'headers:{'.$headersSortable.'}';
469            }
470            $this->javaScript[] = 'jQuery("#'.$this->getId().'_table").tablesorter({textExtraction: fwTableSorter ,'.$tableSorterCfg.'});';
471            
472            $this->validateMaxRowsWithoutUrl();
473            
474            //Incluir linhas do gride
475            if ( !is_array( $this->getData() ) ) {
476                $this->showNoRowsFound();
477            }else{
478                $res = $this->getData();
479                
480                $res = $this->sortDataByColum ( $res );
481                
482                $rowNum = 0;
483                $rowStart = 0;
484                $totalRows = $this->getRowCount();
485                $rowEnd = $totalRows;
486                
487                if ( $this->getMaxRows() > 0 ) {
488                    $this->numPages = ceil( $rowEnd / $this->getMaxRows() );
489                    
490                    // controle de paginacao
491                    if ( $this->currentPage > 0 ) {
492                        $rowStart = ( $this->currentPage - 1 ) * $this->getMaxRows();
493                        $rowEnd = $rowStart + $this->getMaxRows();
494                    }
495                }
496                
497                
498                
499                $keys = array_keys($res);
500                foreach( $res[ $keys[0] ] as $k => $v ) {
501                    $rowNum = $this->getRowNumWithPaginator( $rowNum ,$rowStart ,$k );
502                    $rowNum++;
503                    
504                    if ( ( $rowNum - 1 ) < $rowStart ) {
505                        continue;
506                    }
507                    
508                    if ( ( $rowNum - 1 ) >= $rowEnd ) {
509                        break;
510                    }
511                    // adicionar uma linha na tabela ( tr )
512                    $this->tbody->add( $row = new TTableRow() );
513                    $row->setProperty( 'id', strtolower( $this->getId() . '_tr_' . $rowNum ) );
514                    $row->setProperty( 'grid_id', $this->getId() );
515                    $row->clearCss();
516                    $row->setClass( 'fwGridRow' );
517                    $row->getCss( $objColumn->getCss() );
518                    $row->setProperty( 'line_number', $rowNum );
519                    $row->setProperty( 'row_count', $totalRows );
520                    //$row->setProperty( 'num_rows', $totalRows );
521                    
522                    if ( $this->onDrawRow ) {
523                        call_user_func( $this->onDrawRow, $row, $rowNum, $this->getRowData( $k ) );
524                    }
525                    
526                    if ( !$row->getVisible() ) {
527                        continue;
528                    }
529                    $arrColunms = $this->getColumns();
530                    /*if( $rowNum == 1 )
531                     {
532                     print_r($arrColunms);
533                     }
534                     */
535                    
536                    // adicionar as colunas ( td )
537                    foreach( $arrColunms as $columnId => $objColumn ) {
538                        if( !$objColumn->getVisible() ) {
539                            continue;
540                        }
541                        $fieldName = $objColumn->getFieldName();
542                        
543                        $this->backgroundColorRowGrid ( $row, $rowNum );
544                        $cell = $row->addCell();
545                        $cell->setAttribute('column_index',$objColumn->getColIndex() );
546                        $cell->setAttribute('grid_id',$this->getId() );
547                        $cell->setProperty( 'id', strtolower( $this->getId() . '_td_' . $rowNum ) );
548                        //$cell->clearCss();
549                        $cell->setClass( 'fwGridCell', false );
550                        
551                        if ( $objColumn->getNoWrap() || ( is_null( $objColumn->getNoWrap() ) && $this->getNoWrap() === true ) ) {
552                            $cell->setProperty( 'nowrap', 'nowrap' );
553                        }
554                        $cell->setCss( $objColumn->getCss() );
555                        $cell->setCss( 'width', null ); // a largura é dada pelo titulo (head)
556                        
557                        if ( $objColumn->getTextAlign() ) {
558                            $cell->setCss( 'text-align', $objColumn->getTextAlign() );
559                        }
560                        
561                        // alterar o tamanho da fonte para o tamanho definido para o gride todo
562                        if ( $this->getCss( 'font-size' ) ) {
563                            if ( !$cell->getCss( 'font-size' ) ) {
564                                $cell->setcss( 'font-size', $this->getCss( 'font-size' ) );
565                            }
566                        }
567                        $cell->setProperty( 'line_number', $rowNum );
568                        //$cell->setProperty( 'num_rows', $totalRows );
569                        
570                        if ( $objColumn->getColumnType() == 'rownum' )
571                        {
572                            $cell->setProperty( 'id', strtolower( $this->getid() . '_' . $objColumn->getFieldName() . '_' . $rowNum ) );
573                            $cell->add( $rowNum );
574                            
575                            if ( $this->onDrawCell )
576                            {
577                                call_user_func( $this->onDrawCell, $rowNum, $cell, $objColumn, $this->getRowData( $k ), null );
578                            }
579                        }
580                        else if( $objColumn->getColumnType() == 'plain' or $objColumn->getColumnType() == 'columncompact')
581                        {
582                            $cell->setProperty( 'field_name', $objColumn->getFieldName() );
583                            $cell->setProperty( 'id', strtolower( $this->getid() . '_' . $objColumn->getFieldName() . '_' . $rowNum ) );
584                            $tdValue = '';
585                            
586                            // verificar o nome da coluna informado em caixa alta, baixa e normal
587                            $tdValue = $this->getTdValue($res, $fieldName, $k);                            
588
589                            if ($objColumn->getColumnType() == 'columncompact') {
590                                $len = StringHelper::strlen($tdValue);
591                                if ( $len>$objColumn->getMaxTextLength() ){
592                                    $cell->setProperty('title', $tdValue);
593                                    $tdValue = substr($tdValue, 0, $objColumn->getMaxTextLength()-3).' (...)';
594                                }
595                            }
596                            //$tdValue = isset($res[strtoupper($fieldName)][$k]) && $res[strtoupper($fieldName)][$k] ? $res[strtoupper($fieldName)][$k]: '<center>---</center>';
597                            //$tdValue = ( $objColumn->getConvertHtml() ) ? htmlentities($tdValue): $tdValue;
598                            $tdValue = ( $tdValue == '' ) ? '&nbsp;' : $tdValue;
599                            $cell->setValue( $tdValue );
600                            $tdValue = null;
601                            
602                            if ( $this->onDrawCell )
603                            {
604                                call_user_func( $this->onDrawCell, $rowNum, $cell, $objColumn, $this->getRowData( $k ), null );
605                            }
606                            
607                            if ( $this->getForm() )
608                            {
609                                // colocar as cores dos estatus na primeira coluna do gride
610                                if ( strtoupper( $columnId ) == strtoupper( $this->getId() . '_AEI' ) )
611                                {
612                                    $data = $this->getRowData( $k );
613                                    
614                                    if ( $data[ strtoupper( $this->getId() . '_AEI' )] == 'A' )
615                                    {
616                                        $cell->clearChildren();
617                                        $cell->add( '<center><div style="width:10px;height:10px;background-color:' . $this->getEditedRecordColor() . ';"></div></center>' );
618                                    }
619                                    else if( $data[ strtoupper( $this->getId() . '_AEI' )] == 'E' )
620                                    {
621                                        $cell->clearChildren();
622                                        $cell->add( '<center><div style="width:10px;height:10px;background-color:' . $this->getDeletedRecordColor() . ';"></div></center>' );
623                                    }
624                                    else if( $data[ strtoupper( $this->getId() . '_AEI' )] == 'I' )
625                                    {
626                                        $cell->clearChildren();
627                                        $cell->add( '<center><div style="width:10px;height:10px;background-color:' . $this->getNewRecordColor() . ';"></div></center>' );
628                                    }
629                                    else
630                                    {
631                                        $cell->clearChildren();
632                                        $cell->add( '<center><div style="width:10px;height:10px;background-color:' . $this->getSavedRecordColor() . ';"></div></center>' );
633                                    }
634                                }
635                            }
636                        }
637                        else if( $objColumn->getColumnType() == 'edit' )
638                        {
639                            
640                            $value = null;
641                            // primeiro ler o valor do post, se não existir, ler do $res
642                            if ( $objColumn->getFieldName() )
643                            {
644                                if ( isset( $res[ $objColumn->getFieldName()][ $k ] ) )
645                                {
646                                    $value = $res[ $objColumn->getFieldName()][ $k ];
647                                }
648                            }
649                            $keyValue = '';
650                            if ( $this->getKeyField() )
651                            {
652                                // chave composta
653                                foreach( $this->getKeyField() as $key => $fieldName )
654                                {
655                                    $keyValue .= trim($res[ $fieldName ][ $k ]);
656                                }
657                            }
658                            if( $keyValue == '')
659                            {
660                                $keyValue=$v;
661                            }
662                            $objColumn->setKeyValue( $keyValue );
663                            // configurar a coluna
664                            $objColumn->setRowNum( $rowNum );
665                            $objColumn->setValue( $value );
666                            $edit = $objColumn->getEdit();
667                            
668                            // definir o valor do campo chave para as colunas poderem gerar os edit
669                            if ( $this->getKeyField() )
670                            {
671                                foreach( $this->getKeyField() as $key => $fieldName )
672                                {
673                                    // Se o edit tiver algum evento definido, adicionar os campos
674                                    // chaves e seus valores como atributos para serem recuperados
675                                    // no evento se necesário
676                                    if ( is_array( $edit->getEvents() ) )
677                                    {
678                                        $edit->setAttribute( $fieldName, $res[ $fieldName ][ $k ] );
679                                    }
680                                }
681                            }
682                            // se a coluna checkbox tiver o campo descrição, adicionar a descrição na opção
683                            if ( $objColumn->getDataType() == 'select' )
684                            {
685                                if ( !$objColumn->getKeyValue() )
686                                {
687                                    $edit->setName( $edit->getId() . '[' . $rowNum . ']' );
688                                    $edit->setId( $edit->getId() . '_' . $rowNum );
689                                }
690                                if( $objColumn->getFieldName() && isset( $res[ $objColumn->getFieldName()][$k] ) )
691                                {
692                                    $edit->setOptions( $res[ $objColumn->getFieldName()][$k] );
693                                    if( $objColumn->getInitialValueField() && isset($res[ $objColumn->getInitialValueField()][$k]) )
694                                    {
695                                        // o valor do post deve prevaler sobre o valor inicial
696                                        if( ! isset( $_REQUEST[ $edit->getAttribute('fwName') ] ) )
697                                        {
698                                            $edit->setvalue( $res[ $objColumn->getInitialValueField()][$k] );
699                                        }
700                                    }
701                                    
702                                }
703                                //$edit->setOptions('1=Um,2=Dois');
704                            }
705                            else if( $objColumn->getDataType() == 'checkbox' || $objColumn->getDataType() == 'radio' )
706                            {
707                                $cell->setProperty( 'nowrap', '' );
708                                
709                                if ( $objColumn->getDescField() )
710                                {
711                                    $desc = '';
712                                    
713                                    if ( isset( $res[ $objColumn->getDescField()][ $k ] ) ) $desc = $res[ $objColumn->getDescField()][ $k ];
714                                    
715                                    else if( isset( $res[ strtoupper( $objColumn->getDescField() )][ $k ] ) ) $desc = $res[ strtoupper( $objColumn->getDescField() )][ $k ];
716                                    
717                                    else if( isset( $res[ strtolower( $objColumn->getDescField() )][ $k ] ) ) $desc = $res[ strtolower( $objColumn->getDescField() )][ $k ];
718                                    $objColumn->setDescValue( $desc );
719                                    //$edit->setOptions(array($value=>$desc));
720                                    $edit = $objColumn->getEdit();
721                                }
722                            }
723                            //$edit = $objColumn->getEdit();
724                            
725                            if ( $edit->getEvents() )
726                            {
727                                foreach( $edit->getEvents() as $eventName => $eventFunction )
728                                {
729                                    if ( FormDinHelper::pregMatch( '/\(\)/', $eventFunction ) == 1 )
730                                    {
731                                        $eventFunction = preg_replace( '/\(\)/', '(this,' . $rowNum . ')', $eventFunction );
732                                        $edit->setEvent( $eventName, $eventFunction );
733                                    }
734                                }
735                            }
736                            
737                            //desabilitar o campo se a coluna for readonly
738                            if ( $objColumn->getReadOnly() )
739                            {
740                                // o campo check nao tem setEnabled
741                                if ( method_exists( $edit, 'setReadOnly' ) )
742                                {
743                                    $edit->setReadOnly( true );
744                                }
745                                else if( method_exists( $edit, 'setEnabled' ) )
746                                {
747                                    $edit->setEnabled( false );
748                                }
749                            }
750                            
751                            $this->showEditAutoComplete($edit,$rowNum, $cell, $keyValue, $objColumn);
752                            
753                            if ( $this->onDrawCell ){
754                                call_user_func( $this->onDrawCell, $rowNum, $cell, $objColumn, $this->getRowData( $k ), $edit );
755                            }
756                            
757                            // deaabilitar todos os edits se o grid for readonly
758                            if ( $this->getReadOnly() ){
759                                if ( method_exists( $edit, 'setEnabled' ) ){
760                                    $edit->setEnabled( false );
761                                }
762                            }
763                        }
764                        else if( $objColumn->getColumnType() == 'action' )
765                        {
766                            //----------------------------------------------------
767                            $cell->setClass( 'fwGridCellAction', false );
768                            $cell->setProperty( 'nowrap', 'true' );
769                            if ( is_array( $this->getButtons() ) )
770                            {
771                                foreach( $this->getButtons() as $buttonName => $objButton )
772                                {
773                                    if( $this->getDisabledButtonImage() && FormDinHelper::pregMatch('/fwblank/',$objButton->getImageDisabled() ) )
774                                    {
775                                        $objButton->setImageDisabled( $this->getDisabledButtonImage() ) ;
776                                    }
777                                    $ajax = false;
778                                    // criar novo botão para não acumular o evento onClick
779                                    if( $objButton instanceof TButtonAjax )
780                                    {
781                                        $ajax=true;
782                                        $newButton = new TButtonAjax( $objButton->getName()
783                                            , $objButton->getValue()
784                                            , $objButton->getAction()
785                                            , $objButton->getCallback()
786                                            , $objButton->getReturnDataType()
787                                            , $objButton->getBeforeSend()
788                                            , $objButton->getAsync()
789                                            , $objButton->getMessageLoading()
790                                            , $objButton->getUrl()
791                                            , $objButton->getContainerId()
792                                            , $objButton->getConfirmMessage()
793                                            , $objButton->getImage()
794                                            , $objButton->getImageDisabled()
795                                            , $objButton->getHint()
796                                            , $objButton->getData()
797                                            );
798                                    }
799                                    else
800                                    {
801                                        // criar novo botão para não acumular o evento onClick
802                                        $newButton = new TButton( $objButton->getName(), $objButton->getValue(), $objButton->getAction(), $objButton->getOnClick(), $objButton->getConfirmMessage(), $objButton->getImage(), $objButton->getImageDisabled(), $objButton->getHint(), $objButton->getSubmitAction() );
803                                    }
804                                    
805                                    $newButton->setClass( $objButton->getClass() );
806                                    $newButton->setCss($objButton->getCss());
807                                    $newButton->setCss( 'width', "auto" );
808                                    $newButton->setCss( 'height', "auto" );
809                                    $newButton->setVisible( $objButton->getVisible() );
810                                    $newButton->setEnabled( $objButton->getEnabled() );
811                                    
812                                    // criar a função de atualizar os campos do formulário ao clicar no botão
813                                    if ( is_array( $this->getUpdateFields() ) )
814                                    {
815                                        $strFields = null;
816                                        $strValues = null;
817                                        $strJquery = null; // para grids offline
818                                        
819                                        foreach( $this->getUpdateFields() as $field => $formField )
820                                        {
821                                            $strFields .= is_null( $strFields ) ? '' : '|';
822                                            $strFields .= $formField;
823                                            $strValues .= is_null( $strValues ) ? '' : '|';
824                                            $strJquery .= is_null( $strJquery ) ? '' : ',';
825                                            $aKeyFields = $this->getKeyField();
826                                            
827                                            if ( is_array($aKeyFields) && in_array( $field, $aKeyFields ) )
828                                            {
829                                                $newButton->setProperty( $field, $res[ $field ][ $k ] );
830                                            }
831                                            
832                                            if ( array_key_exists( $field, $res ) )
833                                            {
834                                                if ( isset( $res[ $field ][ $k ] ) )
835                                                {
836                                                    $valeu  = $res[ $field ][ $k ];
837                                                    if ( is_array($valeu) ){
838                                                        $valeu  = 'PHP Array';
839                                                        $strValues .= preg_replace('/'.chr(13).'/','', preg_replace('/'.chr(10).'/','\r',addcslashes($valeu,"'")) );
840                                                        $strJquery .= '"' . strtolower( $field ) . '":"' . addcslashes($valeu,"'") . '"';
841                                                    } else if ( is_object($valeu) ){
842                                                        $valeu  = 'PHP Object';
843                                                        $strValues .= preg_replace('/'.chr(13).'/','', preg_replace('/'.chr(10).'/','\r',addcslashes($valeu,"'")) );
844                                                        $strJquery .= '"' . strtolower( $field ) . '":"' . addcslashes($valeu,"'") . '"';
845                                                    }else {
846                                                        $strValues .= preg_replace('/'.chr(13).'/','', preg_replace('/'.chr(10).'/','\r',addcslashes($valeu,"'")) );
847                                                        $strJquery .= '"' . strtolower( $field ) . '":"' . addcslashes($valeu,"'") . '"';
848                                                    }
849                                                }
850                                                else
851                                                {
852                                                    $strValues .= '';
853                                                    $strJquery .= '"' . strtolower( $field ) . '":""';
854                                                }
855                                            }
856                                        }
857                                        if( !$ajax )
858                                        {
859                                            if ( $newButton->getOnClick() )
860                                            {
861                                                // deixar somente o nome da função sem os parametros
862                                                $jsFunction = $objButton->getOnClick();
863                                                if( substr($strJquery,0,1) != ',' )
864                                                {
865                                                    $strJquery = ','.$strJquery;
866                                                }
867                                                $pos = strpos( $jsFunction, '(' );
868                                                
869                                                if ( $pos > 0 )
870                                                {
871                                                    $jsFunction = substr( $jsFunction, 0, $pos );
872                                                }
873                                                
874                                                if ( !$this->getForm() ) {
875                                                    $jsFunction .= '("' . $strFields . '","' . $strValues . '","' . $this->getId() . '","' . $rowNum . '")';
876                                                }else {
877                                                    $postParentField = PostHelper::get('parent_field');
878                                                    $jsFunction = 'jQuery("#' . $postParentField . '").load(app_url+app_index_file,{"ajax":0,"gridOffline":"1","modulo":"' . $this->getUrl() . '","parent_field":"' . $postParentField . '","subform":1,"' . $this->getId() . 'Width":"' . $this->getWidth() . '","action":"' . $newButton->getAction() . '"' . $strJquery . '} );';
879                                                }
880                                            }
881                                            else
882                                            {
883                                                $strFields = 'fwAtualizarCampos("' . $strFields . '","' . $strValues . '");';
884                                                $jsFunction = $strFields;
885                                                if ( $newButton->getSubmitAction() )
886                                                {
887                                                    $jsFunction .= 'fwFazerAcao("' . $newButton->getAction() . '")';
888                                                }
889                                            }
890                                            $newButton->setOnClick( $jsFunction );
891                                            // retirar a acao do botão para valer o evento onclick;
892                                            $newButton->setAction( null );
893                                        }
894                                        else
895                                        {
896                                            $params=null;
897                                            if( $strFields )
898                                            {
899                                                $aFields = explode('|',$strFields);
900                                                $aValues = explode('|',$strValues);
901                                                $params=array();
902                                                foreach($aFields as $k1=>$v1)
903                                                {
904                                                    $params[$v1] = $aValues[$k1];
905                                                }
906                                                // ajax button
907                                                $data = $newButton->getData();
908                                                //$data['fields']=$strFields;
909                                                //$data['values']=$strValues;
910                                                if( ! isset( $params['gdRownum'] ) )
911                                                {
912                                                    $params['gdRownum'] = $rowNum;
913                                                }
914                                                if( ! isset( $params['gdId'] ) )
915                                                {
916                                                    $params['gdId'] = $this->getId();
917                                                }
918                                                $data['grid'] = $params;
919                                            }
920                                            $newButton->setData( $data );
921                                        }
922                                    }
923                                    
924                                    $cell->add( $newButton );
925                                    
926                                    if ( $this->onDrawActionButton )
927                                    {
928                                        call_user_func( $this->onDrawActionButton, $rowNum, $newButton, $objColumn, $this->getRowData( $k ), $row );
929                                    }
930                                    
931                                    // se o botão estiver invisível, trocar para uma imagem transparente para manter o epaçamento dos outros botões
932                                    if ( !$newButton->getVisible() )
933                                    {
934                                        $newButton->setEnabled( false );
935                                        $newButton->setVisible( true );
936                                        $newButton->setImageDisabled( 'fwDisabled.png' );
937                                    }
938                                    
939                                    // alterar o rotulo do botão excluir para recuperar quando o registro tiver excluido
940                                    if ( $this->getForm() )
941                                    {
942                                        if ( strtolower( $newButton->getId() ) == strtolower( 'btn' . $this->getId() . '_edit' ) )
943                                        {
944                                            $data = $this->getRowData( $k );
945                                            
946                                            if ( $data[ strtoupper( $this->getId() . '_AEI' )] == 'E' )
947                                            {
948                                                $newButton->setEnabled( false );
949                                            }
950                                        }
951                                        else if( strtolower( $newButton->getId() ) == strtolower( 'btn' . $this->getId() . '_delete' ) )
952                                        {
953                                            $data = $this->getRowData( $k );
954                                            
955                                            if ( $data[ strtoupper( $this->getId() . '_AEI' )] == 'E' )
956                                            {
957                                                $newButton->setValue( 'Recuperar' );
958                                                $newButton->setHint( 'Recuperar' );
959                                                // alterar a confirm message.
960                                                //$newButton->setImage('lixeira_cancelar.gif');
961                                                $newButton->setImage( 'undo16.gif' );
962                                                $newButton->setConfirmMessage( 'Confirma a recuperação do registro ?' );
963                                            }
964                                        }
965                                    }
966                                    
967                                    if ( $this->getReadOnly() )
968                                    {
969                                        $newButton->setEnabled( false );
970                                    }
971                                }
972                            }
973                        }
974                    }
975                    
976                    $this->includeHiddenField($row, $res, $rowNum, $k);
977                }
978                
979                // adicionar a imagem do excel no rodapé
980                if ( $this->getExportExcel() ) {
981                    $this->generateFileExcel ();
982                }
983                //$btnExcel = new TButton('btnExcel','Excel',null,'alert("excel")',null,'excel.gif',null,'Exportar dados para o excel');
984                // adicionar a barra de navegação no fim do gride
985                if ( $this->getMaxRows() ) {
986                    //$this->setNavButtons($tbody,$qtdColumns);
987                    $this->setNavButtons( $this->footerCell, $this->getQtdColumns() );
988                }
989            }
990        }
991        
992        if ( isset( $_REQUEST[ 'ajax' ] ) && $_REQUEST[ 'ajax' ] && isset( $_REQUEST[ 'page' ] ) && $_REQUEST[ 'page' ] && $_REQUEST[ 'page' ] > 0 )
993        {
994            $this->tbody->show( true );
995            return;
996        }
997        if ( $this->javaScript ) {
998            $js = str_replace( ';;', ';', implode( ';', $this->javaScript ) );
999            $this->tbody->add( '<script>jQuery(document).ready(function() {' . $js . '});</script>' );
1000        }
1001        return parent::show( $boolPrint );
1002    }
1003    
1004
1005    /**
1006     * Show Gried Field AutoComplete
1007     * @param string $edit
1008     * @param int $rowNum
1009     * @param string $cell
1010     * @param string $keyValue
1011     * @param object $objColumn
1012     */
1013    private function showEditAutoComplete($edit,$rowNum, $cell, $keyValue, $objColumn)
1014    {
1015        if ( $edit ){
1016            $fieldName = strtolower($objColumn->getFieldName());
1017            if( is_array($this->autocomplete) ){ //Test to PHP 7.4
1018                $ac = $this->autocomplete[$fieldName];
1019                if ( is_object($ac) ) {
1020                    // transformar os campos de update para array
1021                    $up = $ac->getUpdateFields();
1022                    $ac->setUpdateFields( null );
1023                    
1024                    if ( $up ) {
1025                        if ( is_string( $up ) ) {
1026                            $up = explode( ',', $up );
1027                        }
1028                        $upFields = '';
1029                        
1030                        foreach( $up as $key => $value ) {
1031                            $value = explode( '%', $value );
1032                            $upFields .= $upFields == '' ? '' : ',';
1033                            $upFields .= $value[ 0 ] . '%' . $objColumn->getRowNum();
1034                        }
1035                        $ac->setUpdateFields( $upFields );
1036                    }
1037                    $ac->setFieldName( $edit->getId() );
1038                    // parametros defaul
1039                    $ac->setCallBackParameters( "'" . $keyValue . "'," . $objColumn->getRowNum() . ',' . $this->getRowCount() );
1040                    
1041                    // verificar se o usuário quer redefinir os parametros
1042                    if ( $this->getOnGetAutocompleteParameters() ){
1043                        call_user_func( $this->onGetAutocompleteParameters, $ac, $this->getRowData( $k ), $rowNum, $cell, $objColumn );
1044                    }
1045                    $edit->setHint( $ac->getHint() );
1046                    $this->javaScript[] = $ac->getJs() . "\n";
1047                }
1048            }
1049            $cell->add( $edit );
1050        }
1051    }
1052
1053    
1054    /**
1055     * Include Hidden Fields on Grid
1056     * @param row
1057     * @param res
1058     * @param fieldName
1059     * @param k
1060     */
1061     private function includeHiddenField($row, $res, $rowNum, $k)
1062    {
1063        // adicionar os campos ocultos na linha ( tr )
1064        if ( $this->getHiddenField() )
1065        {
1066            foreach( $this->getHiddenField() as $fieldName => $id )
1067            {
1068                $value = '';
1069                
1070                if ( isset( $_POST[ strtolower( $id )][ $k ] ) )
1071                {
1072                    $value = $_POST[ strtolower( $id )][ $k ];
1073                }
1074                else if( isset( $res[ $fieldName ][ $k ] ) )
1075                {
1076                    $value = $res[ $fieldName ][ $k ];
1077                }
1078                else if( isset( $res[ strtoupper( $fieldName )][ $k ] ) )
1079                {
1080                    $value = $res[ strtoupper( $fieldName )][ $k ];
1081                }
1082                $hidden = new THidden( strtolower( $id ) . '[' . $k . ']' );
1083                $hidden->setId( strtolower( $id ) . '_' . $rowNum );
1084                $hidden->setValue( $value );
1085                $row->add( $hidden );
1086            }
1087        }
1088     }
1089
1090    /**
1091     * @param row
1092     * @param rowNum
1093     */
1094    public function backgroundColorRowGrid($row, $rowNum) {
1095        // zebrar o gride se nao existir a funcao ondrawrow definida pelo usuario
1096        if ( $this->getZebrarColors( 0 ) ) {
1097            // não sobrepor se o background color estiver definido
1098            if ( !$row->getCss( 'background-color' ) ) {
1099                if ( $rowNum % 2 != 0 ) {
1100                    $row->setCss( 'background-color', $this->getZebrarColors( 0 ) );
1101                }else {
1102                    $row->setCss( 'background-color', $this->getZebrarColors( 1 ) );
1103                }
1104            }
1105        }
1106    }
1107    
1108    private function getTdValueByType($value) {
1109        $tdValue = '';
1110        
1111        if ( is_array($value) ){
1112            $tdValue = 'PHP Array';
1113        } else if ( is_object ($value) ){
1114            $tdValue = 'PHP Object';
1115        } else {
1116            $tdValue = ( ( (string) $value  <> '' ) ? $value : '' );
1117        }
1118        return $tdValue;
1119    }    
1120
1121    /***
1122     *  Return value of TD in the grid 
1123     * @param array $res
1124     * @param string $fieldName
1125     * @param number $k
1126     * @return mixed
1127     */
1128    private function getTdValue($res,$fieldName,$k) {
1129        $tdValue = '';
1130        
1131        if ( isset( $res[ $fieldName ][ $k ] ) )
1132        {
1133            $value = $res[ $fieldName ][ $k ];
1134            $tdValue = $this->getTdValueByType($value);
1135        }
1136        else if( isset( $res[ strtolower( $fieldName )][ $k ] ) )
1137        {
1138            $value = $res[ strtolower( $fieldName )][ $k ];
1139            $tdValue = $this->getTdValueByType($value);
1140        }
1141        else if( isset( $res[ strtoupper( $fieldName )][ $k ] ) )
1142        {
1143            $value = $res[ strtoupper( $fieldName )][ $k ];
1144            $tdValue = $this->getTdValueByType($value);
1145        }
1146        return $tdValue;
1147    }
1148    
1149    /**
1150     * @param cell
1151     */
1152    private function showNoRowsFound() {
1153        // nenhum registro encontrado
1154        $this->tbody->add( $row = new TTableRow() );
1155        $row->clearCss();
1156        $cell = $row->addCell( '<center>'.$this->getNoDataMessage().'</center>' );
1157        $cell->clearCss();
1158        $cell->setClass( 'fwGridCell' );
1159        $cell->setCss( 'color', '#ff0000' );
1160        $cell->setCss( 'width', 'auto' );
1161        $cell->setProperty( 'colspan', $this->getQtdColumns() );
1162    }
1163    
1164    /**
1165     * @param colAction
1166     */
1167    protected function showColumnActionGrid() {
1168        // adicionar a coluna de ações do gride se tiver botoes adicionados
1169        if ( $this->getButtons() ) {
1170            $colAction = $this->addColumn( null, $this->getActionColumnTitle(), 'auto' );
1171            $colAction->setId('col_action');
1172            $colAction->setColumnType( 'action' );
1173            $colAction->setCss( 'text-align', 'center' );
1174            // distãncia entre a borda e os botões
1175            $colAction->setCss( 'padding', '2.5px' );
1176        }
1177    }
1178    
1179    /***
1180     * esconder o titulo se o titulo do gride for null
1181     */
1182    protected function showTitle() {
1183        if ( is_null( $this->getTitle() ) ){
1184            $this->titleCell->setCss( 'display', 'none' );
1185        }
1186    }
1187    
1188    /**
1189     * tentar criar as colunas automaticamente utilizando o array de dados
1190     */
1191    protected function showColumn() {
1192        if ( $this->getColumnCount() == 0 ){
1193            $this->autoCreateColumns();
1194        }
1195    }
1196    
1197    protected function showGridProperty() {
1198        // se o grid for offline, criar as colunas e configurar o form
1199        if ( $this->getForm() ) {
1200            $this->configOffLine();
1201        }
1202        
1203        if( $this->getWidth() == '100px' ){
1204            $this->setProperty('fullwidth','true');
1205        }
1206        // definir as medidas do gride
1207        $this->setProperty( 'width', $this->getWidth() );
1208        $this->setProperty( 'height', $this->getHeight() );
1209        $this->setProperty( 'row_count', $this->getRowCount() );
1210        $this->setProperty('fieldtype','grid' );
1211        
1212        $fldSortedColumn      = new THidden( $this->getId() . '_sorted_column' );
1213        $fldSortedColumnOrder = new THidden( $this->getId() . '_sorted_column_order' );
1214        $fldCollapsed           = new THidden( $this->getId() . '_collapsed' );
1215        //$this->add('<input id="'.$this->getId().'_sorted_column" type="hidden" value="">');
1216        $this->add($fldSortedColumn);
1217        $this->add($fldSortedColumnOrder);
1218        $this->add($fldCollapsed);
1219        
1220        $this->showTitle();
1221        $this->showColumn();
1222    }
1223    
1224    protected function showButonsUpdateDelete() {
1225        // adicionar os botões Alterar e Excluir
1226        if ( $this->getCreateDefaultButtons() ) {
1227            $imgEdit = null;
1228            $imgDeleter = null;
1229            
1230            if ( $this->getUseDefaultImages() ) {
1231                $imgEdit = 'alterar.gif';
1232                $imgDelete = 'lixeira.gif';
1233            }
1234            
1235            if ( $this->getCreateDefaultEditButton() ) {
1236                $this->addbutton( 'Alterar', $this->getId() . '_alterar', null, null, null, $imgEdit, null, 'Alterar' );
1237            }
1238            
1239            if ( $this->getCreateDefaultDeleteButton() ) {
1240                //$this->addButton('Excluir',$this->getId().'_excluir',null,null,'Confirma exclusão ?',$imgDelete,null,'Excluir');
1241                $this->addButton( 'Excluir', $this->getId() . '_excluir', null, 'fwGridConfirmDelete()', null, $imgDelete, null, 'Excluir' );
1242            }
1243        }
1244    }
1245    
1246    protected function showValidateDraws() {
1247        // se a funcao ondrawRow estiver definia e nao existir, retirar o evento
1248        if ( $this->getOnDrawRow() && !function_exists( $this->getOnDrawRow() ) ) {
1249            $this->setOnDrawRow( null );
1250        }
1251        
1252        // se a funcao ondrawcell estiver definia e nao existir, retirar o evento
1253        if ( $this->getOnDrawCell() && !function_exists( $this->getOnDrawCell() ) ) {
1254            $this->setOnDrawCell( null );
1255        }
1256        
1257        // se a funcao ondrawcell estiver definia e nao existir, retirar o evento
1258        if ( $this->getOnDrawHeaderCell() && !function_exists( $this->getOnDrawHeaderCell() ) ) {
1259            $this->setOnDrawHeaderCell( null );
1260        }
1261        
1262        // se a funcao ondrawActionButton estiver definia e nao existir, retirar o evento
1263        if ( $this->getOnDrawActionButton() && !function_exists( $this->getOnDrawActionButton() ) ){
1264            $this->setOnDrawActionButton( null );
1265        }
1266        
1267        // se a funcao onGetAutocompleteCallBackParameters estiver definia e nao existir, retirar o evento
1268        if ( $this->getOnGetAutocompleteCallBackParameters && !function_exists( $this->getOnGetAutocompleteCallBackParameters() ) ) {
1269            $this->setOnGetAutocompleteCallBackParameters( null );
1270        }
1271    }
1272    
1273    
1274    /***
1275     * avisar erro se tiver passado o parametro maxRows e não tiver informado a url
1276     */
1277    private function validateMaxRowsWithoutUrl() {
1278        if ( $this->getMaxRows() && !$this->url ) {
1279            $this->footerCell->add( '<blink><span style="color:red;font-weight:bold;">Para utilizar o recurso de paginação, o parametro strRequestUrl, tambem dever ser informado</span></blink>' );
1280        }
1281    }
1282    
1283    /**
1284     * sort Data Gride by colum
1285     */
1286    public function sortDataByColum($res) {
1287        if( isset($_REQUEST[$this->getId().'_sorted_column'] ) ) {
1288            $res = $this->sortArray($res,$_REQUEST[$this->getId().'_sorted_column'],$_REQUEST[$this->getId().'_sorted_column_order']);
1289        }
1290        return $res;
1291    }
1292    
1293    /**
1294     * Generate File Excel
1295     */
1296    public function generateFileExcel() {
1297        //$_SESSION['fwGrid'][$this->getId()] = $this->getData2Excel();
1298        //$_SESSION['fwGrid'][$this->getId()]['titulo'] =$this->getTitle();
1299        $excel = new TElement( 'a' );
1300        $excel->setProperty( 'href', 'javascript: void(0)' );
1301        $arrParams = null;
1302        $arrParams[ 'id' ]         = $this->getId();
1303        $arrParams[ 'head' ]     = $this->getExcelHeadField('utf8');
1304        $arrParams[ 'title' ]     = $this->getTitle();
1305        $excel->addEvent( 'onclick', 'fwExportGrid2Excel(' . json_encode( $arrParams ) . ')' );
1306        $img = new TElement( 'img' );
1307        $img->setProperty( 'src', $this->getBase() . 'imagens/planilha.png' );
1308        $img->setCss( 'border', 'none' );
1309        $img->setCss( 'width', '16' );
1310        $img->setCss( 'height', '13' );
1311        $excel->setProperty( 'title', 'Exportar planilha' );
1312        $excel->add( $img );
1313        $excel->setCss( 'float', 'right' );
1314        $this->footerCell->add( $excel );
1315        
1316        // salvar o array em disco
1317        $tmpName = $excel->getBase().'tmp/tmp_'.$this->getId().'_'.session_id().'.go';
1318        if( !file_exists( $excel->getBase().'tmp' ) ) {
1319            mkdir( $excel->getBase().'tmp' );
1320        }
1321        if( file_exists( $tmpName ) ) {
1322            @unlink($tmpName);
1323        }
1324        if( !file_put_contents( $tmpName, serialize( $this->getData2Excel() ) ) ) {
1325            $excel->setAttribute('title',htmlentities('Erro ao salvar os dados para exportação',null,ENCODINGS));
1326        }
1327    }
1328    
1329    //------------------------------------------------------------------------------------
1330    public function getColumns()
1331    {
1332        return $this->columns;
1333    }
1334    
1335    //------------------------------------------------------------------------------------
1336    public function getColumn( $strColumnName )
1337    {
1338        $strColumnName = strtolower( $strColumnName );
1339        
1340        if ( isset( $this->columns[ $strColumnName ] ) )
1341        {
1342            return $this->columns[ $strColumnName ];
1343        }
1344        return null;
1345    }
1346    
1347    //------------------------------------------------------------------------------------
1348    public function getColumnCount()
1349    {
1350        if ( is_array( $this->getColumns() ) )
1351        {
1352            return ( int ) count( $this->columns );
1353        }
1354        return 0;
1355    }
1356    
1357    //------------------------------------------------------------------------------------
1358    /**
1359     * Coluna normal para o grid
1360     * @param string $strFieldName 1: ID da coluna = Nome da coluna da tabela
1361     * @param string $strValue     2: Nome do Label que irá aparecer 
1362     * @param integer $strWidth    3: tamanho da coluna
1363     * @param string $strTextAlign 4: Alinhamento do texto left|right|center|justify
1364     * @return TGridColumn
1365     */
1366    public function addColumn( $strFieldName, $strValue = null, $strWidth = null, $strTextAlign = null )
1367    {
1368        $col = new TGridColumn( $strFieldName, $strValue, $strWidth, $strTextAlign );
1369        $col->clearCss();
1370        $col->setGridId($this->getId());
1371        $this->columns[ $col->getId()] = $col;
1372        return $col;
1373    }
1374    //------------------------------------------------------------------------------------
1375    /**
1376     * Coluna com texto reduzido, deve ser usado quando o texto é longo. Depois do ponto de corte irá aparece ...
1377     * @param string $strFieldName     1: ID da coluna = Nome da coluna da tabela
1378     * @param string $strValue         2: Nome do Label que irá aparecer
1379     * @param integer $strWidth        3: tamanho da coluna
1380     * @param string $strTextAlign     4: Alinhamento do texto left|right|center|justify
1381     * @param number $strMaxTextLength 5: tamanho do texto antes do corte
1382     * @return TGridColumnCompact
1383     */
1384    public function addColumnCompact( $strFieldName, $strValue = null, $strWidth = null, $strTextAlign = null, $strMaxTextLength = 40  )
1385    {
1386        $col = new TGridColumnCompact( $strFieldName, $strValue, $strWidth, $strTextAlign, null,null,null,$strMaxTextLength);
1387        $col->clearCss();
1388        $col->setGridId($this->getId());
1389        $this->columns[ $col->getId()] = $col;
1390        return $col;
1391    }
1392    //------------------------------------------------------------------------------------
1393    /**
1394     * Use esse campo quando vc precisa pegar alguma informação sobre o regristro porém não pode mostrar a coluna
1395     * @param string $strFieldName Nome do campo na tabela
1396     * @param string $strId Nome do campo que será usado
1397     */
1398    public function addHiddenField( $strFieldName, $strId = null )
1399    {
1400        $strId = is_null( $strId ) ? strtolower( $strFieldName ) : $strId;
1401        $this->hiddenField[ $strFieldName ] = $strId;
1402    }
1403    
1404    //------------------------------------------------------------------------------------
1405    public function getHiddenField()
1406    {
1407        return $this->hiddenField;
1408    }
1409    
1410    //------------------------------------------------------------------------------------
1411    protected function addActionColumn( $strTitle = null )
1412    {
1413        $this->columns[ $strTitle ] = new TActionColumn( $strTitle );
1414    }
1415    
1416    //------------------------------------------------------------------------------------
1417    public function setTitle( $strValue = null )
1418    {
1419        $this->title = $strValue;
1420    }
1421    
1422    public function getTitle()
1423    {
1424        return $this->title;
1425    }
1426    
1427    //------------------------------------------------------------------------------------
1428    public function setData( $mixValue = null ){
1429        if ( is_array( $mixValue ) ) {
1430            $keys = array_keys($mixValue);
1431            if ( empty($keys) ) {
1432                $mixValue = null;
1433            }
1434        }
1435        $this->data = $mixValue;
1436    }
1437    
1438    //---------------------------------------------------------------------------------------
1439    /**
1440     * Retorna o array de dados do gride
1441     */
1442    public function getData() {
1443        $res = null;
1444        
1445        if ( is_array( $this->data ) ) {
1446            $keys = array_keys( $this->data );
1447            if( ! is_array($this->data[$keys[0]] ) || isset($this->data[$keys[0]][0] ) ) {
1448                return $this->data;
1449            }
1450            return $this->data;
1451        }
1452        else if( isset($this->data) && (strpos( StringHelper::strtolower( $this->data ), 'select ' ) !== false) ) {
1453            
1454            $bvars = null;
1455            $bvars = $this->getBvars();
1456            
1457            if ( function_exists( 'recuperarPacote' ) )
1458            {
1459                $cache = $this->getCache();
1460                print_r( $GLOBALS[ 'conexao' ]->executar_recuperar( $this->data, $bvars, $res, $cache ) );
1461            }
1462            else if( !class_exists( 'TPDOConnection' ) || !TPDOConnection::getInstance() )
1463            {
1464                $res = TPDOConnection::executeSql( $this->data );
1465            }
1466        }
1467        //else if( strpos(strtolower($this->data),'pk_') !== false || strpos(strtolower($this->data),'pkg_') !== false )
1468        else if( FormDinHelper::pregMatch( '/\.PK\a?/i', $this->data ) > 0 )
1469        {
1470            $bvars = $this->getBvars();
1471            $cache = $this->getCache();
1472            print_r( recuperarPacote( $this->data, $bvars, $res, $cache ) );
1473        }
1474        else if( !is_null( $this->data ) )
1475        {
1476            $where = '';
1477            
1478            if ( is_array( $this->getBvars() ) )
1479            {
1480                foreach( $this->getBvars() as $k => $v )
1481                {
1482                    $where .= $where == '' ? '' : ' and ';
1483                    $where .= "($k='$v')";
1484                }
1485                $where = $where == '' ? '' : ' where ' . $where;
1486            }
1487            $sql = "SELECT * FROM {$this->data} {$where}";
1488            $cache = $this->getCache();
1489            $bvars = null;
1490            
1491            if ( function_exists( 'recuperarPacote' ) )
1492            {
1493                print_r( $GLOBALS[ 'conexao' ]->executar_recuperar( $sql, $bvars, $res, $cache ) );
1494            }
1495            else if( !class_exists( 'TPDOConnection' ) || !TPDOConnection::getInstance() )
1496            {
1497                $res = TPDOConnection::executeSql( $sql );
1498            }
1499        }
1500        
1501        if ( $res ) {
1502            $this->setData( $res );
1503        }
1504        return $res;
1505    }
1506    
1507    //------------------------------------------------------------------------------------
1508    public function addKeyField( $strNewValue = null )
1509    {
1510        if ( $strNewValue )
1511        {
1512            if ( is_array( $this->getKeyField() ) )
1513            {
1514                if ( array_search( $strNewValue, ( array ) $this->getKeyField() ) === false )
1515                {
1516                    $this->keyField[] = $strNewValue;
1517                }
1518            }
1519            else
1520            {
1521                $aTemp = explode( ',', $strNewValue );
1522                
1523                if ( is_array( $aTemp ) )
1524                {
1525                    foreach( $aTemp as $v )
1526                    {
1527                        $this->keyField[] = $v;
1528                    }
1529                }
1530                //$this->keyField[] = $strNewValue;
1531            }
1532        }
1533    }
1534    
1535    //------------------------------------------------------------------------------------
1536    public function getKeyField()
1537    {
1538        return $this->keyField;
1539    }
1540    
1541    //------------------------------------------------------------------------------------
1542    /**
1543     * Adicionar botão na linha do gride
1544     *
1545     * $boolSubmitAction = adicionar/remover a função fwFazerAcao(). Padrão=true
1546     *
1547     * @param string $strRotulo         - 1: Nome do Label do Botão ou Hint que irá aparecer na imagem se o Hint estiver em branco
1548     * @param string $strAction         - 2: Nome da ação capitura no formDinAcao
1549     * @param string $strName           - 3: Nome
1550     * @param string $strOnClick        - 4: JavaScript que será chamado no evento OnClick
1551     * @param string $strConfirmMessage - 5: Mensagem com caixa de confirmação
1552     * @param string $strImage          - 6: Imagem que irá aparecer
1553     * @param string $strImageDisabled  - 7: Imagem quado desabilitado
1554     * @param string $strHint
1555     * @param boolean $boolSubmitAction
1556     * @return object> TButton
1557     */
1558    public function addButton( $strRotulo
1559        , $strAction = null
1560        , $strName = null
1561        , $strOnClick = null
1562        , $strConfirmMessage = null
1563        , $strImage = null
1564        , $strImageDisabled = null
1565        , $strHint = null
1566        , $boolSubmitAction = null
1567        ){
1568            if ( is_null( $strName ) ){
1569                $strName = $this->getId() . ucwords( $this->removeIllegalChars( $strRotulo ) );
1570            }
1571            if ( is_null( $strAction ) && is_null( $strOnClick ) ){
1572                $strAction = strtolower( $this->getId() . '_' . $strRotulo );
1573            }
1574            $this->buttons[ $strName ] = new TButton( $strName, $strRotulo, $strAction, $strOnClick, $strConfirmMessage, $strImage, $strImageDisabled, $strHint, $boolSubmitAction );
1575            // se o usuário adicionar um botão, cancelar a criação dos botões padrão de alterar e excluir
1576            $this->enableDefaultButtons( false );
1577            return $this->buttons[ $strName ];
1578    }
1579    
1580    //---------------------------------------------------------------------------------------
1581    public function addButtonAjax($strRotulo,$strAction,$strImage=null,$strImageDisabled=null,$strName=null,$strConfirmMessage=null,$jsBeforeSendFnc=null,$jsCallbackFnc=null,$strReturnType=null,$strMsgLoading=null,$strModuleName=null,$boolAsync=null,$strContainerId=null,$strHint=null,$arrData=null)
1582    {
1583        $strReturnType  = ( $strReturnType == 'text' ? 'text' : 'json' );
1584        $strMsgLoading  = is_null( $strMsgLoading ) ? 'Processando. Aguarde...': $strMsgLoading;
1585        $boolAsync      = ( $boolAsync===true ? true : false );
1586        $button = new TButtonAjax($strName,$strRotulo,$strAction,$jsCallbackFnc,$strReturnType,$jsBeforeSendFnc,$boolAsync,$strMsgLoading,$strModuleName,$strContainerId,$strConfirmMessage,$strImage,$strImageDisabled,$strHint,$arrData);
1587        $this->enableDefaultButtons( false );
1588        $this->buttons[$strName] = $button;
1589        return $this->buttons[$strName];
1590    }
1591    
1592    //---------------------------------------------------------------------------------------
1593    public function getButtons()
1594    {
1595        return ( array ) $this->buttons;
1596    }
1597    
1598    //------------------------------------------------------------------------------------
1599    /**
1600     * Seta o nome de uma função que será usada para desenhar as linha da tabela.
1601     * 
1602     * Parametros do envento onDrawRow
1603     *     1) $row         - objeto TGridRow
1604     *     2) $rowNum         - número da linha corrente
1605     *     3) $aData        - o array de dados da linha ex: $res[''][n]
1606     * @param string $newValue
1607     */
1608    public function setOnDrawRow( $newValue = null )
1609    {
1610        $this->onDrawRow = $newValue;
1611    }
1612    
1613    //------------------------------------------------------------------------------------
1614    public function getOnDrawRow()
1615    {
1616        return $this->onDrawRow;
1617    }
1618    
1619    //------------------------------------------------------------------------------------
1620    /**
1621     * Seta o nome de uma função que será usada para desenhar as celula da tabela.
1622     * 
1623     * Parametros do envento onDrawCell
1624     *     1) $rowNum         - número da linha corrente
1625     *     2) $cell        - objeto TTableCell
1626     *     3) $objColumn    - objeto TGrideColum
1627     *     4) $aData        - o array de dados da linha ex: $res[''][n]
1628     *     5) $edit        - o objeto campo quando a coluna for um campo de edição
1629     *   ex: function ondrawCell($rowNum=null,$cell=null,$objColumn=null,$aData=null,$edit=null)
1630     * 
1631     * @param string $newValue
1632     */
1633    public function setOnDrawCell( $newValue = null )
1634    {
1635        $this->onDrawCell = $newValue;
1636    }
1637    
1638    //------------------------------------------------------------------------------------
1639    public function getOnDrawCell()
1640    {
1641        return $this->onDrawCell;
1642    }    
1643    //------------------------------------------------------------------------------------
1644    /**
1645     * Seta o nome de uma função que será usada para desenhar o Header do Grid
1646     * Um exemplo tipo é modificar o texto por uma imagem
1647     * 
1648     * Parametros do evento onDrawHeaderCell
1649     *     1) $th            - objeto TElement
1650     *     2) $objColumn     - objeto TGridColum
1651     *     3) $objHeader     - objeto TElement
1652     * @param string $newValue
1653     */
1654    public function setOnDrawHeaderCell( $newValue = null )
1655    {
1656        $this->onDrawHeaderCell = $newValue;
1657    }
1658    //------------------------------------------------------------------------------------
1659    /***
1660     * Verifica se foi informada alguma função 
1661     * @return string
1662     */
1663    public function getOnDrawHeaderCell()
1664    {
1665        return $this->onDrawHeaderCell;
1666    }
1667    
1668    //------------------------------------------------------------------------------------
1669    /**
1670     * Seta o nome de uma função que será usada para desenhar os botões de uma linha da gride.
1671     * Um exemplo tipico é desabilitar determinado botão se o Registro estiver no estado X
1672     * 
1673     * Parametros do evento onDrawActionButton
1674     *     1) $rowNum         - número da linha corrente
1675     *     2) $button         - objeto TButton
1676     *     3) $objColumn    - objeto TGrideColum
1677     *     4) $aData        - o array de dados da linha ex: $res[''][n]
1678     *   Ex: function tratarBotoes($rowNum,$button,$objColumn,$aData);
1679     * 
1680     * @param string $newValue
1681     */
1682    public function setOnDrawActionButton( $newValue = null )
1683    {
1684        $this->onDrawActionButton = $newValue;
1685    }
1686    
1687    //------------------------------------------------------------------------------------
1688    public function getOnDrawActionButton()
1689    {
1690        return $this->onDrawActionButton;
1691    }
1692    
1693    //------------------------------------------------------------------------------------
1694    /**
1695     * Campos do form origem que serão atualizados ao selecionar o item desejado. Separados por virgulas seguindo o padrão <campo_tabela> | <campo_formulario> , <campo_tabela> | <campo_formulario>
1696     * @param string $mixUpdateFields
1697     */
1698    public function setUpdateFields( $mixUpdateFields = null )
1699    {
1700        if ( $mixUpdateFields )
1701        {
1702            if ( is_array( $mixUpdateFields ) )
1703            {
1704                foreach( $mixUpdateFields as $k => $v )
1705                {
1706                    if ( is_numeric( $k ) )
1707                    {
1708                        $k = $v;
1709                        $v = strtolower( $v );
1710                    }
1711                    $this->setUpdateFields( $k . '|' . $v );
1712                }
1713            }
1714            else if( strpos( $mixUpdateFields, ',' ) !== false )
1715            {
1716                $a = explode( ',', $mixUpdateFields );
1717                $this->setUpdateFields( $a );
1718            }
1719            else
1720            {
1721                $aFields = explode( '|', $mixUpdateFields );
1722                
1723                if ( !isset( $aFields[ 1 ] ) )
1724                {
1725                    $aFields[ 0 ] = strtoupper( $aFields[ 0 ] );
1726                    $aFields[ 1 ] = strtolower( $aFields[ 0 ] );
1727                }
1728                
1729                if ( $aFields[ 0 ] != '' )
1730                {
1731                    $this->updateFields[ $aFields[ 0 ] ] = $aFields[ 1 ];
1732                }
1733            }
1734        }
1735    }
1736    
1737    //------------------------------------------------------------------------------------
1738    public function getUpdateFields()
1739    {
1740        $arrResult = $this->updateFields;
1741        
1742        if ( $arrResult )
1743        {
1744            // adicionar o campo chave na lista de campos a serem atualizados
1745            if ( $this->getKeyField() )
1746            {
1747                $keyValue = '';
1748                
1749                foreach( $this->getKeyField() as $key => $fieldName )
1750                {
1751                    if ( !in_array( $fieldName, $arrResult ) )
1752                    {
1753                        $this->setUpdateFields( $fieldName );
1754                    }
1755                }
1756            }
1757        }
1758        return $arrResult;
1759    }
1760    
1761    //------------------------------------------------------------------------------------
1762    public function clearUpdateFields()
1763    {
1764        $this->updateFields = null;
1765    }
1766    
1767    //------------------------------------------------------------------------------------
1768    public function getWidth()
1769    {
1770        if ( is_null( $this->width ) )
1771        {
1772            return 'auto';
1773        }
1774        else
1775        {
1776            if ( strpos( $this->width, '%' ) === false )
1777            {
1778                $w = preg_replace( '/[^0-9]/', '', $this->width ) . 'px';
1779                $w = $w == 'px' ? 'auto' : $w;
1780            }
1781            else
1782            {
1783                return $this->width;
1784            }
1785        }
1786        return $w;
1787    }
1788    
1789    //---------------------------------------------------------------------------------------
1790    public function getHeight()
1791    {
1792        if ( is_null( $this->height ) )
1793        {
1794            return 'auto';
1795        }
1796        else
1797        {
1798            if ( strpos( $this->height, '%' ) === false )
1799            {
1800                $w = preg_replace( '/[^0-9]/', '', $this->height ) . 'px';
1801                $w = $w == 'px' ? 'auto' : $w;
1802            }
1803            else
1804            {
1805                return $this->height;
1806            }
1807        }
1808        return $w;
1809    }
1810    
1811    //------------------------------------------------------------------------------------
1812    public function setWidth( $strNewValue = null )
1813    {
1814        $this->width = $strNewValue;
1815    }
1816    
1817    //------------------------------------------------------------------------------------
1818    public function setHeight( $strNewValue = null )
1819    {
1820        $this->height = $strNewValue;
1821    }
1822    
1823    //------------------------------------------------------------------------------------
1824    public function setActionColumnTitle( $strNewValue = null )
1825    {
1826        $this->actionColumnTitle = $strNewValue;
1827    }
1828    
1829    //------------------------------------------------------------------------------------
1830    public function getActionColumnTitle( $strNewValue = null )
1831    {
1832        if ( is_null( $this->actionColumnTitle ) ){
1833            return htmlentities( 'Ação',ENT_COMPAT, ENCODINGS );
1834        }
1835        return htmlentities( $this->actionColumnTitle,null, ENCODINGS );
1836    }
1837    
1838    //---------------------------------------------------------------------------------------
1839    public function getRowData( $intRow = null )
1840    {
1841        $aData = array();
1842        
1843        if ( !is_null( $intRow ) )
1844        {
1845            foreach( $this->data as $k => $v )
1846            {
1847                $aData[ $k ] = $this->data[ $k ][ $intRow ];
1848            }
1849        }
1850        return $aData;
1851    }
1852    
1853    //---------------------------------------------------------------------------------------
1854    /**
1855     * Seta as cores para Zebrar um Grid, informe valores em Hexadecimal
1856     * como #efefef ou #ffffff
1857     *
1858     * @param string $strColor1
1859     * @param string $strColor2
1860     * @return void
1861     */
1862    function setZebrarColors( $strColor1 = null, $strColor2 = null )
1863    {
1864        HtmlHelper::validateHtmlColorHexa($strColor1);
1865        HtmlHelper::validateHtmlColorHexa($strColor2);
1866        $this->zebrarColors = array( $strColor1, $strColor2 );
1867    }
1868    
1869    //---------------------------------------------------------------------------------------
1870    function getZebrarColors( $intColor = null )
1871    {
1872        if ( $intColor == 0 || $intColor == 1 )
1873        {
1874            return isset( $this->zebrarColors[ $intColor ] ) ? $this->zebrarColors[ $intColor ] : ( ( $intColor == 0 ) ? '#efefef' : '#ffffff' );
1875        }
1876        return $this->zebrarColors;
1877    }
1878    
1879    //---------------------------------------------------------------------------------------
1880    /***
1881     * Adciona um campo do tipo texto livre, equivalente ao addTextField
1882     * @param string $strName      - id do campo
1883     * @param string $strTitle     - Titulo da coluna
1884     * @param string $strFieldName - id do array que veio do banco
1885     * @param string $strSize      - tamanho do campos
1886     * @param int    $intMaxLength - tamanho maximo
1887     * @param string $strMask
1888     * @param string $strWidth
1889     * @param string $strAlign     - alinhamento
1890     * @param bool $boolReadOnly   - somente leitura ou não
1891     * @return TGridEditColumn
1892     */
1893    public function addTextColumn( $strName, $strTitle = null
1894        , $strFieldName = null
1895        , $strSize = null
1896        , $intMaxLength = null
1897        , $strMask = null
1898        , $strWidth = null
1899        , $strAlign = null
1900        , $boolReadOnly = null ){
1901            $col = new TGridEditColumn( $strName
1902                                      , $strTitle
1903                                      , $strFieldName
1904                                      , 'text'
1905                                      , $strSize
1906                                      , $intMaxLength
1907                                      , $strMask
1908                                      , $strWidth
1909                                      , $strAlign
1910                                      , $boolReadOnly );
1911            $this->columns[ strtolower( $strName )] = $col;
1912            return $col;
1913    }
1914    
1915    //------------------------------------------------------------------------------------
1916    public function addAutoCompleteColumn( string $strName
1917                                         , string $strTitle = null
1918                                         , string $strFieldName = null
1919                                         , string $strSize = null
1920                                         , int $intMaxLength = null
1921                                         , string $strTablePackage
1922                                         , string $strSearchField
1923                                         , int $intMinChars = null
1924                                         , $mixUpdateFields = null
1925                                         , $strWidth = null
1926                                         , $strAlign = null
1927                                         , $boolReadOnly = null )
1928    {
1929        $this->autocomplete[ $strName ] = new TAutoComplete( $strFieldName, $strTablePackage, $strSearchField, $mixUpdateFields, null, null, 'callBack', $intMinChars );
1930        $tgridColumn = $this->addTextColumn( $strName
1931                                            , $strTitle
1932                                            , $strFieldName
1933                                            , $strSize
1934                                            , $intMaxLength
1935                                            , null
1936                                            , $strWidth
1937                                            , $strAlign
1938                                            , $boolReadOnly );
1939        return $tgridColumn;
1940    }
1941    
1942    //---------------------------------------------------------------------------------------
1943    /**
1944     * Adicionar coluna para entrada de datas no gride
1945     *
1946     * @param mixed $strName
1947     * @param mixed $strTitle
1948     * @param mixed $strFieldName
1949     * @param mixed $maskType
1950     * @param mixed $strWidth
1951     * @param mixed $strAlign
1952     * @param mixed $boolReadOnly
1953     * @return TGridDateColumn
1954     */
1955    public function addDateColumn( $strName, $strTitle = null
1956        , $strFieldName = null, $maskType = null
1957        , $strWidth = null, $strAlign = null
1958        , $boolReadOnly = null )
1959    {
1960        $col = new TGridDateColumn( $strName, $strTitle, $strFieldName, $maskType, $strWidth, $strAlign, $boolReadOnly );
1961        $this->columns[ strtolower( $strName )] = $col;
1962        return $col;
1963    }
1964    
1965    //---------------------------------------------------------------------------------------
1966
1967    /**
1968     *  Adciona uma coluna do tipo numerico para form no grid
1969     *
1970     * @param string $strName           -1: id do campo
1971     * @param [type] $strTitle          -2: Titulo da coluna que vai aparcer para o usuário
1972     * @param [type] $strFieldName      -3: id do array que veio do banco
1973     * @param [type] $intSize           -4: tamanho do número
1974     * @param [type] $intDecimalPlaces  -5: quantidade de casas decimais
1975     * @param [type] $boolFormatInteger -6:
1976     * @param [type] $strWidth
1977     * @param [type] $strAlign
1978     * @param [type] $boolReadOnly
1979     * @return void
1980     */
1981    public function addNumberColumn( $strName, $strTitle = null, $strFieldName = null, $intSize = null, $intDecimalPlaces = null, $boolFormatInteger = null, $strWidth = null, $strAlign = null, $boolReadOnly = null )
1982    {
1983        $col = new TGridNumberColumn( $strName, $strTitle, $strFieldName, $intSize, $intDecimalPlaces, $boolFormatInteger, $strWidth, $strAlign, $boolReadOnly );
1984        $this->columns[ strtolower( $strName )] = $col;
1985        return $col;
1986    }
1987    
1988    //---------------------------------------------------------------------------------------
1989    /**
1990     * coluna tipo checkbox. Irá criar no gride uma coluno do tipo checkbox. Quando é feito o POST
1991     * será criado uma nova variavel com valor de strName
1992     *
1993     *
1994     * @param string $strName       - Nome do variavel no POST
1995     * @param string $strTitle      - Titulo que aparece no grid
1996     * @param string $strKeyField   - Valor que será passado no POST
1997     * @param string $strDescField  - Descrição do campo, valor que irá aparecer o gride
1998     * @param boolean $boolReadOnly
1999     * @param boolean $boolAllowCheckAll  - TRUE = pode selecionar todos , FALSE = não permite multiplas seleções
2000     * @return TGridCheckColumn
2001     */
2002    public function addCheckColumn( string $strName
2003        , string $strTitle = null
2004        , $strKeyField
2005        , $strDescField = null
2006        , $boolReadOnly = null
2007        , $boolAllowCheckAll = null )
2008    {
2009        if ( !$strKeyField )
2010        {
2011            $strKeyField = strtoupper( $strName );
2012        }
2013        $col = new TGridCheckColumn( $strName, $strTitle, $strKeyField, $strDescField, $boolReadOnly, $boolAllowCheckAll );
2014        $this->columns[ strtolower( $strName )] = $col;
2015        return $col;
2016    }
2017    /**
2018     * coluna tipo radioButton     
2019     *
2020     * @param string $strName       - Nome do variavel no POST
2021     * @param string $strTitle      - Titulo que aparece no grid
2022     * @param string $strKeyField   - Valor que será passado no POST
2023     * @param string $strDescField  - Descrição do campo, valor que irá aparecer o gride
2024     * @param boolean $boolReadOnly
2025     * @return TGridRadioColumn
2026     */
2027    public function addRadioColumn( string $strName, string $strTitle = null, $strKeyField, $strDescField = null, $boolReadOnly = null )
2028    {
2029        if ( !$strKeyField )
2030        {
2031            $strKeyField = strtoupper( $strName );
2032        }
2033        $col = new TGridRadioColumn( $strName, $strTitle, $strKeyField, $strDescField, $boolReadOnly );
2034        $this->columns[ strtolower( $strName )] = $col;
2035        return $col;
2036    }
2037    
2038    /*****
2039     * Coluna do tipo select
2040     *
2041     * @param string $strName         - 1: ID do campos
2042     * @param string $strTitle        - 2: Titulo que irá aparecer para o usuário no grid
2043     * @param string $strFieldName    - 3: ID do campo na origem dos dados do grid
2044     * @param mixed $mixOptions       - 4: Opções caso o Campo do gride não seja um array
2045     * @param mixed $strWidth         - 5: largura do campos em pixel
2046     * @param boolean $boolReadOnly   - 6: Somente Leitura
2047     * @param string $strFirstOptionText  - 7: Label do Primeiro elemento
2048     * @param string $strFirstOptionValue - 8: Valor do Primeiro elemento. Para o valor DEFAULT informe o ID do $mixOptions e $strFirstOptionText = '' não pode ser null  
2049     * @param string $strKeyField         - 9: 
2050     * @param string $strDisplayField     - 10:
2051     * @param string $strInitialValueField -11: Default Valeu
2052     * @return TGridSelectColumn
2053     */
2054    public function addSelectColumn( $strName
2055        , $strTitle = null
2056        , $strFieldName = null
2057        , $mixOptions = null
2058        , $strWidth = null
2059        , $boolReadOnly = null
2060        , $strFirstOptionText = null
2061        , $strFirstOptionValue = null
2062        , $strKeyField = null
2063        , $strDisplayField = null
2064        , $strInitialValueField=null
2065        ){
2066            $col = new TGridSelectColumn( $strName
2067                , $strTitle
2068                , $strFieldName
2069                , $mixOptions
2070                , $strWidth
2071                , $boolReadOnly
2072                , $strFirstOptionText
2073                , $strFirstOptionValue
2074                , $strKeyField
2075                , $strDisplayField
2076                , $strInitialValueField );
2077            $this->columns[ strtolower( $strName )] = $col;
2078            return $col;
2079    }
2080    
2081    //---------------------------------------------------------------------------------------
2082    /**
2083     * 
2084     * @param string $strName         - 1: ID do campos
2085     * @param string $strTitle        - 2: Titulo que irá aparecer no grid
2086     * @param string $strFieldName    - 3: Nome do campo do gride
2087     * @param int $intMaxLength       - 4: Tamanho maximo do campo
2088     * @param int $intColumns         - 5: Qtd colunas
2089     * @param int $intRows            - 6: Qtd de linhas
2090     * @param boolean $boolReadOnly   - 7: mostra ou não o contador. Default = TRUE
2091     * @param boolean $boolShowCounter  8: mostra ou não o contador. Default = TRUE
2092     * @return TGridMemoColumn
2093     */
2094    public function addMemoColumn( $strName, $strTitle = null, $strFieldName = null, $intMaxLength = null, $intColumns = null, $intRows = null, $boolReadOnly = null, $boolShowCounter = null )
2095    {
2096        $col = new TGridMemoColumn( $strName, $strTitle, $strFieldName, $intMaxLength, $intColumns, $intRows, $boolReadOnly, $boolShowCounter );
2097        $this->columns[ strtolower( $strName )] = $col;
2098        return $col;
2099    }
2100    
2101    //---------------------------------------------------------------------------------------
2102    public function addRowNumColumn( $strName = null, $strTitle = null, $strWidth = null, $strAlign = null )
2103    {
2104        $strName = is_null( $strName ) ? 'grid_rownum' : $strName;
2105        $strTitle = is_null( $strTitle ) ? 'Nº' : $strTitle;
2106        $strAlign = is_null( $strAlign ) ? 'center' : $strAlign;
2107        $col = new TGridRowNumColumn( $strName, $strTitle, $strWidth, $strAlign );
2108        $this->columns[ strtolower( $strName )] = $col;
2109        return $col;
2110    }
2111    
2112    //---------------------------------------------------------------------------------------
2113    public function getRowNumWithPaginator($rowNum,$rowStart, $index){
2114        if( !empty($this->getRealTotalRowsSqlPaginator()) ){
2115            $result = $rowStart+$index;
2116        }else {
2117            $result = $rowNum;
2118        }
2119        return $result;
2120    }
2121    
2122    //---------------------------------------------------------------------------------------
2123    public function getRowCount() {
2124        $result = 0;
2125        if( !empty($this->getRealTotalRowsSqlPaginator()) ){
2126            $result = $this->getRealTotalRowsSqlPaginator();
2127        }else{
2128            $res = $this->getData();
2129            if ( $res ) {
2130                $keys = array_keys($res);
2131                $result = count( $res[ $keys[0] ] );
2132            }
2133        }
2134        return $result;
2135    }
2136    
2137    //---------------------------------------------------------------------------------------
2138    public function setReadOnly( $boolNewValue = null )
2139    {
2140        $boolNewValue = $boolNewValue === true ? true : false;
2141        $this->readOnly = $boolNewValue;
2142    }
2143    
2144    //---------------------------------------------------------------------------------------
2145    public function getReadOnly()
2146    {
2147        return $this->readOnly;
2148    }
2149    
2150    //---------------------------------------------------------------------------------------
2151    /**
2152     * Qtd Max de linhas
2153     *
2154     * @param int $intNewValue
2155     * @return void
2156     */
2157    public function setMaxRows( $intNewValue = null ) {
2158        $this->maxRows = $intNewValue;
2159    }
2160    
2161    //---------------------------------------------------------------------------------------
2162    public function getMaxRows() {
2163        return ( int ) $this->maxRows;
2164    }
2165    
2166    //---------------------------------------------------------------------------------------
2167    protected function setNavButtons( $tbody, $qtdColumns ) {
2168        if ( !$this->url || !$this->getMaxRows() || $this->numPages == 1 ) {
2169            return;
2170        }
2171        /*
2172         Desabilitei os botoes next, prior etc.. porque quando o clica no titulo
2173         da coluna para ordenar, os botões estavam sendo ordenados tambem, ficando
2174         na parte superior do gride.
2175         */
2176        /*
2177         $prev                 = $this->currentPage -1;
2178         $next                 = $this->currentPage +1;
2179         //$jsOnClick             = 'jQuery("#'.$this->getId().'_loading").show();jQuery("#'.$this->getId().'_jumpToPage").attr("disable",true);jQuery("#'.$this->getId().'_first_page").attr("disable",true);jQuery("#'.$this->getId().'_prev_page").attr("disable",true);jQuery("#'.$this->getId().'_next_page").attr("disable",true);jQuery("#'.$this->getId().'_last_page").attr("disable",true);';
2180         //sleep(3);
2181         $jsOnClick             = 'jQuery("#'.$this->getId().'_loading").show();jQuery("#'.$this->getId().'_jumpToPage").hide();jQuery("#'.$this->getId().'_first_page").hide();jQuery("#'.$this->getId().'_prev_page").hide();jQuery("#'.$this->getId().'_next_page").hide();jQuery("#'.$this->getId().'_last_page").hide();';
2182         // se o proprio modulo fizer include da classe banco, config etc, não precisa ser chamado pelo index da aplicacao
2183         if( defined( APLICATIVO ) )
2184         {
2185         $urlFirst            = $jsOnClick.'jQuery("#'.$this->getId().'_table > tbody").load("'.$this->url.' tbody>tr",{ "ajax":1,"page":1});';
2186         $urlPrev            = $jsOnClick.'jQuery("#'.$this->getId().'_table > tbody").load("'.$this->url.' tbody>tr",{ "ajax":1,"page":'.$prev.'});';
2187         $urlNext             = $jsOnClick.'jQuery("#'.$this->getId().'_table > tbody").load("'.$this->url.' tbody>tr",{ "ajax":1,"page":'.$next.'});';
2188         $urlLast            = $jsOnClick.'jQuery("#'.$this->getId().'_table > tbody").load("'.$this->url.' tbody>tr",{ "ajax":1,"page":'.$this->numPages.'});';
2189         }
2190         else
2191         {
2192         $urlFirst            = $jsOnClick.'jQuery("#'.$this->getId().'_table > tbody").load(app_url+app_index_file+" tbody>tr",{ "ajax":1,"page":1,"modulo":"'.$this->url.'"});';
2193         $urlPrev            = $jsOnClick.'jQuery("#'.$this->getId().'_table > tbody").load(app_url+app_index_file+" tbody>tr",{ "ajax":1,"page":'.$prev.',"modulo":"'.$this->url.'"});';
2194         $urlNext             = $jsOnClick.'jQuery("#'.$this->getId().'_table > tbody").load(app_url+app_index_file+" tbody>tr",{ "ajax":1,"page":'.$next.',"modulo":"'.$this->url.'"});';
2195         $urlLast            = $jsOnClick.'jQuery("#'.$this->getId().'_table > tbody").load(app_url+app_index_file+" tbody>tr",{ "ajax":1,"page":'.$this->numPages.',"modulo":"'.$this->url.'"});';
2196         }
2197         $btnFirst             = new TButton($this->getId().'_first_page','<<'    ,null,$urlFirst,null,'page-first.png','page-first_disabled.png','Primeira página');
2198         $btnPrev             = new TButton($this->getId().'_prev_page','<'    ,null,$urlPrev,null ,'page-prev.png' ,'page-prev_disabled.png','Página anterior');
2199         $btnNext             = new TButton($this->getId().'_next_page','>'    ,null,$urlNext,null ,'page-next.png' ,'page-next_disabled.png','Próxima página');
2200         $btnLast             = new TButton($this->getId().'_last_page','>>'    ,null,$urlLast,null ,'page-last.png' ,'page-last_disabled.png','Última página');
2201         
2202         if( $prev == 0 )
2203         {
2204         $btnPrev->setEnabled(false);
2205         $btnFirst->setEnabled(false);
2206         }
2207         if( $next == 0 )
2208         {
2209         $btnNext->setEnabled(false);
2210         }
2211         if( $this->currentPage == $this->numPages)
2212         {
2213         $btnNext->setEnabled(false);
2214         $btnLast->setEnabled(false);
2215         }
2216         */
2217        $select = null;
2218        
2219        if ( $this->numPages > 1 )
2220        {
2221            $aPages = array();
2222            
2223            for( $i = 1; $i <= $this->numPages; $i++ )
2224            {
2225                $aPages[ $i ] = $i;
2226            }
2227            $select = new TSelect( $this->getId() . '_jumpToPage', $aPages, null, true );
2228            $select->setcss( 'margin-left', '5px' );
2229            $select->setcss( 'margin-right', '5px' );
2230            $select->setProperty( 'noClear', 'true' ); // evitar que a função fwClearFields() limpe o seu vavalor
2231            $select->setValue( $this->currentPage );
2232            // estes parametros devem ser sempre passados na atualização da página do gride
2233            //$arrRequest = array( 'ajax' => 1, 'page' => 'this.value', 'TGrid' => 1 );
2234            $arrRequest = array( 'ajax' => 1, 'TGrid' => 1, 'gridId' => $this->getId() );
2235            foreach( $_REQUEST as $k => $v )
2236            {
2237                if ( $k != 'modulo' && $k != 'ajax' && $k != 'page' && $k != 'PHPSESSID' && $k != 'cookieauth' )
2238                {
2239                    $arrRequest[ $k ] =$v;
2240                }
2241            }
2242            $arrRequest[ 'gridId' ]=$this->getId();
2243            $jsOnClick = isset( $jsOnClick ) ? $jsOnClick : '';
2244            if ( defined( APLICATIVO ) ) // já fez o includes dos arquivos ncessários
2245            {
2246                $arrRequest['url'] = $this->url;
2247            }
2248            else
2249            {
2250                $arrRequest[ 'modulo' ] = $this->getUrl();
2251            }
2252            $select->setEvent( 'onChange', $jsOnClick . 'fwGridPageChange(this.value,'.json_encode($arrRequest).')');
2253            $select->setEvent( 'onKeyUp', 'var key = fwGetKey(event); if( key >= 33 && key <= 40) { this.onchange(); }' );
2254        }
2255        $div = new TElement( 'div' );
2256        $div->setId( $this->getId() . '_div_nav_buttons' );
2257        $div->setcss( 'text-align', 'left' );
2258        $div->setcss( 'border', '1px solid gray' );
2259        $div->setcss( 'padding-top', '2px' );
2260        $div->setcss( 'width', '100%' );
2261        $div->setcss( 'float', 'left' );
2262        $div->add( 'Página:' );
2263        $div->add( $select );
2264        
2265        $btnFirst             = new TButton($this->getId().'_first_page','<<'    ,null,'fwGridChangePage('. json_encode(array('id'=>$this->getId(),'action'=>'first') ).')',null,'page-first.png',null,'Primeira página');
2266        $div->add( $btnFirst,false );
2267        $btnPrev    = new TButton($this->getId().'_prev_page','<'    ,null,'fwGridChangePage('. json_encode(array('id'=>$this->getId(),'action'=>'prior') ).')',null ,'page-prev.png' ,null,'Página anterior');
2268        $div->add( $btnPrev,false );
2269        $btnNext     = new TButton($this->getId().'_next_page','>'    ,null,'fwGridChangePage('. json_encode(array('id'=>$this->getId(),'action'=>'next') ).')',null ,'page-next.png',null,'Próxima página');
2270        $div->add( $btnNext,false );
2271        $btnLast             = new TButton($this->getId().'_last_page','>>'    ,null,'fwGridChangePage('. json_encode(array('id'=>$this->getId(),'action'=>'last') ).')',null ,'page-last.png' ,null,'Última página');
2272        $div->add( $btnLast,false );
2273        
2274        $img = new TButton($this->getId().'_loading',null,null,null,null,'carregando.gif');
2275        $img->setCss('display','none');
2276        $div->add($img);
2277        /*
2278         $div->add($btnFirst);
2279         $div->add($btnPrev);
2280         $div->add($select);
2281         $div->add($btnNext);
2282         $div->add($btnLast);
2283         */
2284        
2285        // imagem processando durante as requisições ajax
2286        /*
2287         $img = new TElement('img');
2288         $img->setId($this->getId().'_loading');
2289         $img->setcss('display'    ,'none');
2290         $img->setcss('float'    ,'left');
2291         $img->setCss('height'    ,'20px');
2292         $img->setCss('width'    ,'135px');
2293         $img->setProperty('src','base/imagens/processando.gif');
2294         $div->add($img);
2295         */
2296        // criar uma linha <tr> no final do gride para mostrar os botões de paginação
2297        $tbody->add( $row = new TTableRow() );
2298        $row->setId( $this->getId() . '_tr_nav_buttons' );
2299        $row->clearCss();
2300        $cell = $row->addCell();
2301        $cell->setId( $this->getId() . '_td_nav_buttons' );
2302        $cell->clearCss();
2303        $cell->setClass( 'fwHeaderBar' );
2304        $cell->setCss( 'height', '26px' );
2305        $cell->setProperty( 'colspan', $qtdColumns );
2306        // adicionar a div no td
2307        $cell->add( $div );
2308    }
2309    
2310    //---------------------------------------------------------------------------------------
2311    public function setBvars( $arrBvars = null )
2312    {
2313        $this->bvars = $arrBvars;
2314    }
2315    
2316    //---------------------------------------------------------------------------------------
2317    public function getBvars()
2318    {
2319        return $this->bvars;
2320    }
2321    
2322    //---------------------------------------------------------------------------------------
2323    public function setCache( $intNewValue = null )
2324    {
2325        $this->cache = $intNewValue;
2326    }
2327    //---------------------------------------------------------------------------------------
2328    public function getCache()
2329    {
2330        return $this->cache;
2331    }
2332    //---------------------------------------------------------------------------------------
2333    public function getCreateDefaultButtons()
2334    {
2335        return is_null( $this->createDefaultButtons ) ? true : $this->createDefaultButtons;
2336    }
2337    /**
2338     * Define se os botoes Alterar e Excluir serão exibidos quando não for
2339     * adicionado nenhum botão
2340     *
2341     * @param mixed $boolNewValue
2342     */
2343    public function enableDefaultButtons( $boolNewValue = null )
2344    {
2345        $this->createDefaultButtons = is_null( $boolNewValue ) ? true : $boolNewValue;
2346    }
2347    
2348    //---------------------------------------------------------------------------------------
2349    /**
2350     * Define a utilização das imagens alterar.gif e lixeira.gif do diretorio base/imagens
2351     *
2352     * @param mixed $boolNewValue
2353     */
2354    public function setUseDefaultImages( $boolNewValue = null )
2355    {
2356        $this->useDefaultImages = $boolNewValue;
2357    }
2358    
2359    //---------------------------------------------------------------------------------------
2360    public function getUseDefaultImages()
2361    {
2362        return is_null( $this->useDefaultImages ) ? true : $this->useDefaultImages;
2363    }
2364    
2365    //---------------------------------------------------------------------------------------
2366    public function setExportExcel( $boolNewValue = null )
2367    {
2368        $this->exportExcel = is_null( $boolNewValue ) ? true : $boolNewValue;
2369    }
2370    
2371    public function getExportExcel() {
2372        return $this->exportExcel;
2373    }
2374    
2375    //---------------------------------------------------------------------------------------
2376    public function autoCreateColumns()
2377    {
2378        $res = $this->getData();
2379        
2380        if ( $res )
2381        {
2382            $keys = array_keys($res);
2383            $this->addKeyField( $keys[0] );
2384            $this->setUpdateFields( $keys[0] );
2385            
2386            foreach( $res as $k => $dados )
2387            {
2388                $this->addColumn( $k, $k );
2389            }
2390        }
2391    }
2392    
2393    //---------------------------------------------------------------------------------------
2394    /**
2395     * adicionar o formulário ao gride para criar o gride offline
2396     * @param TForm $frm
2397     * @param boolean $boolShowCollapsed
2398     */
2399    public function setForm( TForm $frm = null, $boolShowCollapsed = null )
2400    {
2401        $this->form = $frm;
2402        $this->setShowCollapsed( $boolShowCollapsed );
2403        if( $frm->getCss('background-color')=='#efefef')
2404        {
2405            $this->form->setCss('background-color','transparent');
2406        }
2407    }
2408    
2409    public function getForm()
2410    {
2411        return $this->form;
2412    }
2413    
2414    //---------------------------------------------------------------------------------------
2415    public function setUrl( $strNewValue = null )
2416    {
2417        $this->url = $strNewValue;
2418    }
2419    
2420    public function getUrl()
2421    {
2422        return $this->url;
2423    }
2424    
2425    //------------------------------------------------------------------------------------------------
2426    // Configurações do grid offline
2427    //-------------------------------------------------------------------------------------
2428    protected function configOffLine()
2429    {
2430        $frm = $this->getForm();
2431        if ( isset( $_REQUEST[ $this->getId() . 'Width' ] ) )
2432        {
2433            $frm->setWidth( $_REQUEST[ $this->getId() . 'Width' ] );
2434        }
2435        $frm->setFormGridOffLine(true);
2436        
2437        $frm->setId( $this->getId() . '_form' );
2438        $frm->setAttribute( 'idGridOffLine',$this->getId() );
2439        $frm->setName( $this->getId() . '_form' );
2440        $frm->setFlat( true );
2441        $frm->setFade( false );
2442        $frm->setAction( null );
2443        $frm->setShowCloseButton( false );
2444        $frm->setShowHeader( !$frm->getTitle() == "" );
2445        //$frm->showOnlyTagForm = true;
2446        $frm->setAutoIncludeJsCss( false );
2447        $frm->setOverflowY( 'hidden' );
2448        $frm->setCss( 'border', '0px' );
2449        $frm->body->setCss( 'border-bottom', '0px' );
2450        $frm->footer->setCss( 'border', '0px' );
2451        $frm->cssFiles = null;
2452        $frm->jsFiles = null;
2453        $frm->removeMessageArea();
2454        
2455        if ( $this->getShowCollapsed() )
2456        {
2457            $frm->addJavascript( 'jQuery("#' . $this->getId() . '_img_show_hide_form").click();' );
2458        }
2459        $this->columns = null;
2460        $strFirstKeyField = null;
2461        $noClearFields = null;
2462        
2463        // definir a chave primária do gride se não tiver sido passada
2464        if ( $keyField = $this->getKeyField() )
2465        {
2466            $strFirstKeyField = strtoupper( $keyField[ 0 ] );
2467            
2468            foreach( $keyField as $v )
2469            {
2470                $frm->addHiddenField( strtolower( $v ) );
2471            }
2472        }
2473        else
2474        {
2475            if ( $res = $this->getData() )
2476            {
2477                $keys = array_keys($res);
2478                $strFirstKeyField = strtoupper( $keys[0] );
2479                $frm->addHiddenField( strtolower( $strFirstKeyField ) );
2480            }
2481        }
2482        $this->keyField = null;
2483        // botão de esconder/exibir o formulário
2484        $this->titleCell->add( '<img id="' . $this->getId() . '_img_show_hide_form" onclick="if( jQuery(\'#' . $this->getId() . '_form_area\').is(\':visible\') ){this.src=this.src.replace(\'Collapse\',\'Expand\');jQuery(\'#' . $this->getId() . '_form_area\').hide(\'slow\');jQuery(\'#' . $this->getId() . '_collapsed\').val(1) } else { this.src=this.src.replace(\'Expand\',\'Collapse\');jQuery(\'#' . $this->getId() . '_form_area\').show(\'fast\');jQuery(\'#' . $this->getId() . '_collapsed\').val(0);}" src="' . $this->getBase() . 'imagens/groupCollapse.jpg" width="16px" height="16px" style="float:right;cursor:pointer;" title="Abrir/Fechar">' );
2485        
2486        // legenda do rodapé
2487        $this->footerCell->add( '<table border="0" style="float:left;border:none;" cellspacing="0" cellpadding="0">
2488        <tr>
2489        <td width="8" height="8" bgcolor="' . $this->getSavedRecordColor() . '"></td><td style="font-size:10px;">Salvo</td><td width="10px"></td>
2490        <td width="8" height="8" bgcolor="' . $this->getEditedRecordColor() . '"></td><td style="font-size:10px;">Alterado</td><td width="10px"></td>
2491        <td width="8" height="8" bgcolor="' . $this->getNewRecordColor() . '"></td><td style="font-size:10px;">Novo</td><td width="10px"></td>
2492        <td width="8" height="8" bgcolor="' . $this->getDeletedRecordColor() . '"></td><td style="font-size:10px;">Excluido</td>
2493        </tr>
2494        </table>' );
2495        // coluna de controle de registro incluido, alterado e excluído
2496        $controlAEI = strtoupper( $this->getId() . '_AEI' );
2497        
2498        if ( is_array( $frm->getDisplayControls() ) )
2499        {
2500            $strJquery = '';
2501            $aFieldNames = null;
2502            $col = $this->addColumn( $controlAEI, '' );
2503            $col->setSortable(false);
2504            
2505            $fields = $this->extractFormFields($frm);
2506            // criar as colunas do gride utilizando os campos do formulário
2507            foreach( $fields as $objField )
2508            {
2509                $field         = $objField->field;
2510                $label         = $objField->label;
2511                $fieldName     = $field->getId();
2512                
2513                $col=null;
2514                if( $field->getFieldType() == 'hidden'  )
2515                {
2516                    
2517                    if ( strtoupper( $fieldName ) != 'FW_BACK_TO' )
2518                    {
2519                        $field->setAttribute( 'gridOfflineField', 'true' );
2520                        
2521                        // se não for campo chave do grid, adicionar tag noClear para a função frm->clearFields() apos a edição não limpar os campos ocultos
2522                        if ( !preg_match( '/,' . $fieldName . ',/i', ',' . implode( ',', $keyField ) . ',' ) )
2523                        {
2524                            $field->setAttribute( 'noClear', 'true' );
2525                            $noClearFields[] = $fieldName;
2526                        }
2527                        else
2528                        {
2529                            $this->addKeyField( StringHelper::strtoupper( $fieldName ) );
2530                            $aFieldNames[] = $fieldName;
2531                        }
2532                        
2533                        // considerar o primeiro campo oculto como a chave do gride
2534                        if ( is_null( $strFirstKeyField ) ){
2535                            $strFirstKeyField = StringHelper::strtoupper( $fieldName );
2536                        }
2537                    }
2538                    else
2539                    {
2540                        $field->setAttribute( 'noClear', 'true' );
2541                    }
2542                }
2543                else if ( $field->getFieldType() == 'edit' || $field->getFieldType() == 'number' || $field->getFieldType() == 'date' || $field->getFieldType() == 'cpf' || $field->getFieldType() == 'cpfcnpj' || $field->getFieldType() == 'cnpj' || $field->getFieldType() == 'fone' || $field->getFieldType() == 'memo' || $field->getFieldType() == 'cep' )
2544                {
2545                    $field->setAttribute( 'gridOfflineField', 'true' );
2546                    $label = isset($label)?str_replace( ':', '', $label ):null;
2547                    
2548                    if ( $field->getFieldType() == 'number' && $field->getDecimalPlaces() > 0 ){
2549                        $align = 'right';
2550                    }
2551                    $align = $field->getAttribute( 'grid_algin' );
2552                    $fieldName = StringHelper::strtoupper( $fieldName );
2553                    $col = $this->addColumn( $fieldName, $label, null, $align );
2554                    $strJquery .= $strJquery == '' ? ' ' : ',';
2555                    $strJquery .= '"' . $fieldName . '":jQuery("#' . $fieldName . '").val()';
2556                    $aFieldNames[] = $fieldName;
2557                    
2558                    // definir o foco para o primeiro campo do formulário do grid-offline
2559                    if ( !$frm->getFocusField() )
2560                    {
2561                        $frm->setFocusField( $fieldName );
2562                    }
2563                }
2564                else if( $field->getFieldType() == 'select' )
2565                {
2566                    $field->setAttribute( 'gridOfflineField', 'true' );
2567                    $aFieldNames[] = $fieldName;
2568                    $label = str_replace( ':', '', $label );
2569                    
2570                    $c = $field->getAttribute('grid_column');
2571                    if( $c )
2572                    {
2573                        $this->addColumn( strtoupper($c) , $label );
2574                        $field->addEvent('onChange',"jQuery(\"#\"+this.id+\"_temp\").val( this.options[this.selectedIndex].text )");
2575                        $strJquery .= $strJquery == '' ? ' ' : ',';
2576                        $strJquery .= '"' . $fieldName . '":jQuery("#' . $fieldName . '").val()';
2577                    }
2578                    else
2579                    {
2580                        $col = $this->addColumn( strtoUpper( $fieldName . '_text' ), $label );
2581                        $strJquery .= $strJquery == '' ? ' ' : ',';
2582                        $strJquery .= '"' . $fieldName . '":jQuery("#' . $fieldName . '").val()';
2583                    }
2584                }
2585                else if( $field->getFieldType() == 'memo' )
2586                {
2587                    $field->setAttribute( 'gridOfflineField', 'true' );
2588                    $label = str_replace( ':', '', $label );
2589                    $col = $this->addMemoColumn( $fieldName, $label, strtoupper( $fieldName ), $field->getMaxLenght(), $field->getColumns(), $field->getRows(), true, false );
2590                    $strJquery .= $strJquery == '' ? ' ' : ',';
2591                    $strJquery .= '"' . $fieldName . '":jQuery("#' . $fieldName . '").val()';
2592                    $aFieldNames[] = $fieldName;
2593                }
2594                if( isset($col) && isset( $field ) && $field->getAttribute('grid_hidden') == 'true' )
2595                {
2596                    $col->setVisible(false);
2597                }
2598            }
2599            
2600            if ( is_null( $strFirstKeyField ) )
2601            {
2602                $strFirstKeyField = strtolower( $this->getId() . '_PK' );
2603                $this->addKeyField( strtoupper( $strFirstKeyField ) );
2604                $frm->addHiddenField( $strFirstKeyField );
2605                $aFieldNames[] = $strFirstKeyField;
2606            }
2607            
2608            // adicionar os campos chave no evento do botão Adicionar para enviar o seu valor
2609            if( is_array( $this->getKeyField() ))
2610            {
2611                foreach( $this->getKeyField() as $k => $v )
2612                {
2613                    if ( !$this->getUpdateFields() )
2614                    {
2615                        $this->setUpdateFields( strtoupper( $v ) );
2616                    }
2617                    $strJquery .= $strJquery == '' ? ' ' : ',';
2618                    $strJquery .= '"' . strtolower( $v ) . '":jQuery("#' . strtolower( $v ) . '").val()';
2619                }
2620            }
2621            
2622            // campos ocultos que devem ser sempre submetidos ao executar uma ação do grid offline
2623            if ( is_array( $noClearFields ) )
2624            {
2625                foreach( $noClearFields as $k => $v )
2626                {
2627                    $strJquery .= $strJquery == '' ? ' ' : ',';
2628                    $strJquery .= '"' . strtolower( $v ) . '":jQuery("#' . strtolower( $v ) . '").val()';
2629                }
2630            }
2631            
2632            if ( !$this->getUpdateFields() )
2633            {
2634                $frm->addMessage( 'Para o funcionamento do grid offline, é necessário definir um campo chave.\nAdicione um campo oculto no formulário anexado ao gride com o nome do campo chave.' );
2635            }
2636            
2637            if ( $this->getUrl() )
2638            {
2639                // postar sempre o width do grid
2640                $strJquery .= ',"' . $this->getId() . 'Width":"' . $frm->getWidth() . '"';
2641                // definir a largura do grid
2642                $this->setWidth( $frm->getWidth() );
2643                
2644                $requestAction = RequestHelper::get('action');
2645                $postParentField = PostHelper::get('parent_field');
2646                if ( $this->getShowAdicionarButton() ) {
2647                    $frm->addButton( ($requestAction =='edit'?"Salvar Alteração":"Adicionar"), null, 'btn' . $this->getId() . 'Save', 'jQuery("#' . $frm->getId() . '_footer").html(fw_img_processando2);jQuery("#' . $postParentField . '").load(app_url+app_index_file,{"ajax":0,"gridOffline":"1","modulo":"' . $this->getUrl() . '","parent_field":"' . $postParentField . '","action":"save","subform":1,' . $strJquery . '} );' );
2648                }
2649                $frm->addButton( ($requestAction=='edit'?"Cancelar Alteração":"Limpar"), null, 'btn' . $this->getId() . 'Clear', 'jQuery("#' . $frm->getId() . '_footer").html(fw_img_processando2);jQuery("#' . $postParentField . '").load(app_url+app_index_file,{"ajax":0,"gridOffline":"1","modulo":"' . $this->getUrl() . '","parent_field":"' . $postParentField . '","action":"clear","subform":1,' . $strJquery . '} );' );
2650                $frm->addButton( 'Desfazer', null, 'btn' . $this->getId() . 'ClearAll', 'jQuery("#' . $frm->getId() . '_footer").html(fw_img_processando2);jQuery("#' . $postParentField . '").load(app_url+app_index_file,{"ajax":0,"gridOffline":"1","modulo":"' . $this->getUrl() . '","parent_field":"' . $postParentField . '","action":"clearAll","subform":1,' . $strJquery . '} );', 'Esta ação cancela todas as operações de inclusão, alteração e exclusão\nrealizadas no gride antes da última gravação.\n\n Confirma ?\n', null, null, null, null, 'Desfazer todas as alterações/inclusões e voltar os dados para a situação original!' );
2651                $this->bodyCell->add( '<span id="' . $this->getId() . '_form_area">' );
2652                $this->bodyCell->add( $frm );
2653                $this->bodyCell->add( '</span>' );
2654                
2655                // adicionar os botões de alterar e excluir no gride
2656                if ( $this->getCreateDefaultEditButton() )
2657                {
2658                    $this->addButton( 'Alterar', 'edit', 'btn' . $this->getId() . '_edit', '()', null, 'editar.gif', 'alterar_bw.gif', 'Alterar' );
2659                    
2660                }
2661                
2662                if ( $this->getCreateDefaultDeleteButton() )
2663                {
2664                    $this->addButton( 'Excluir', 'delete', 'btn' . $this->getId() . '_delete', '()', 'Confirma exclusão ?', 'lixeira.gif', 'lixeira_bw.gif', 'Excluir' );
2665                }
2666            }
2667            else
2668            {
2669                //$frm->addMessage('Para o funcionamento do grid offline, é necessário definir o parametro $strRequestUrl da classe TGrid');
2670                print 'Para o funcionamento do grid offline,<br>é necessário definir o parametro $strRequestUrl da classe TGrid';
2671            }
2672            
2673            // recuperar da sessão os dados e definir como $res para o grid
2674            // fazer a inclusão, alteração e exclusão
2675            if ( isset( $_POST[ 'action' ] ) && $_POST[ 'action' ] == 'save' )
2676            {
2677                if ( $frm->validate() )
2678                {
2679                    if ( $_SESSION[ APLICATIVO ][ 'offline' ][ $this->getId()] )
2680                    {
2681                        $res = $_SESSION[ APLICATIVO ][ 'offline' ][ $this->getId()];
2682                    }
2683                    else
2684                    {
2685                        $res = array();
2686                    }
2687                    // o gride pode ter varias keyfields, assumir a primeira como chave e verificar se a primeira foi postada
2688                    $aKeys = $this->getKeyField();
2689                    $key = strtolower( $aKeys[ 0 ] );
2690                    $k = false;
2691                    
2692                    if ( isset( $res[ strtoupper( $key )] ) )
2693                    {
2694                        $k = array_search( $_POST[ $key ], $res[ strtoupper( $key )] );
2695                    }
2696                    
2697                    if ( $k === false )
2698                    {
2699                        // inclusão
2700                        //gravar na sessão os dados postados
2701                        $lower = 0;
2702                        
2703                        if ( isset( $res[ $aKeys[ 0 ] ] ) && is_array( $res[ $aKeys[ 0 ] ] ) )
2704                        {
2705                            foreach( $res[ $aKeys[ 0 ] ] as $key => $value )
2706                            {
2707                                if ( $value <= $lower )
2708                                {
2709                                    $lower = $value;
2710                                }
2711                            }
2712                        }
2713                        $_POST[ strtolower( $aKeys[ 0 ] )] = ( $lower - 1 );
2714                    }
2715                    
2716                    foreach( $aFieldNames as $key => $fieldName )
2717                    {
2718                        // inclusao
2719                        if ( $k === false ) {
2720                            $res[ strtoupper( $fieldName )][] =  $_POST[ $fieldName ];
2721                        }
2722                        // alteração
2723                        else {
2724                            $res[ strtoupper( $fieldName )][ $k ] = $_POST[ $fieldName ];
2725                        }
2726                        
2727                        $field = $frm->getField( $fieldName );
2728                        if ( $field->getFieldType() == 'select' )
2729                        {
2730                            $c = $field->getAttribute('grid_column');
2731                            if ( $k === false )
2732                            {
2733                                if( $c )
2734                                {
2735                                    if( $_POST[$fieldName] )
2736                                    {
2737                                        $res[strToUpper($c)][] = $_POST[$fieldName.'_temp'];
2738                                    } else {
2739                                        $res[strToUpper($c)][] = '';
2740                                    }
2741                                } else {
2742                                    $res[ strtoupper( $fieldName . '_text' )][] = $frm->getField( $fieldName )->getText();
2743                                }
2744                            } else {
2745                                if( $c )
2746                                {
2747                                    if( $_POST[$fieldName] )
2748                                    {
2749                                        $res[strToUpper($c)][$k] = $_POST[$fieldName.'_temp'];
2750                                    } else {
2751                                        $res[strToUpper($c)][$k] = '';
2752                                    }
2753                                } else {
2754                                    if( isset($_POST[$fieldName]) && $frm->getField( $fieldName )->getText()=='')
2755                                    {
2756                                        $res[ strtoupper( $fieldName . '_text' )][ $k ] = $this->decodeUtf8( $_POST[$fieldName] );
2757                                    } else {
2758                                        $res[ strtoupper( $fieldName . '_text' )][ $k ] = $frm->getField( $fieldName )->getText();
2759                                    }
2760                                }
2761                            }
2762                        }
2763                    }
2764                    
2765                    // adicionar / alterar a coluna de controle de Inc, Alt, Exc
2766                    if ( $k === false )
2767                    {
2768                        $res[ $controlAEI ][] = 'I';
2769                    }
2770                    else
2771                    {
2772                        // marcar como alterado somente registros que já existirem no banco de dados
2773                        if ( $res[ $strFirstKeyField ][ $k ] > 0 )
2774                        {
2775                            $res[ $controlAEI ][ $k ] = 'A';
2776                        }
2777                    }
2778                    $frm->clearFields();
2779                    $_SESSION[ APLICATIVO ][ 'offline' ][ $this->getId()] = $res;
2780                }
2781            }
2782            elseif( isset( $_POST[ 'action' ] ) && $_POST[ 'action' ] == 'edit' )
2783            {
2784                $aKeys = $this->getKeyField();
2785                $key = strtolower( $aKeys[ 0 ] );
2786                $res = $_SESSION[ APLICATIVO ][ 'offline' ][ $this->getId()];
2787                
2788                if ( is_array( $res[ strtoupper( $key )] ) )
2789                {
2790                    $k = array_search( $_POST[ $key ], $res[ strtoupper( $key )] );
2791                }
2792                
2793                foreach( $aFieldNames as $key => $fieldName )
2794                {
2795                    $frm->setValue( $fieldName, $res[ strtoupper( $fieldName )][ $k ] );
2796                }
2797            }
2798            elseif( isset( $_POST[ 'action' ] ) && $_POST[ 'action' ] == 'clear' )
2799            {
2800                $frm->clearFields();
2801            }
2802            elseif( isset( $_POST[ 'action' ] ) && $_POST[ 'action' ] == 'delete' )
2803            {
2804                $aKeys = $this->getKeyField();
2805                $key = strtolower( $aKeys[ 0 ] );
2806                $res = $_SESSION[ APLICATIVO ][ 'offline' ][ $this->getId()];
2807                $k = array_search( $_POST[ $key ], $res[ strtoupper( $key )] );
2808                
2809                // se ja estiver excluido, recuperar o registro
2810                if ( $res[ $controlAEI ][ $k ] == 'E' )
2811                {
2812                    $res[ $controlAEI ][ $k ] = 'A';
2813                    $_SESSION[ APLICATIVO ][ 'offline' ][ $this->getId()] = $res;
2814                    $frm->clearFields();
2815                }
2816                else
2817                {
2818                    if ( $k > -1 )
2819                    {
2820                        // se ainda não existir no banco de dados pode excluir do gride, senão só marca para exclusão quando o gride for processado
2821                        if ( $res[ strtoupper( $key )][ $k ] < 0 )
2822                        {
2823                            foreach( $res as $fieldName => $value )
2824                            {
2825                                $res[ $fieldName ][ $k ] = null;
2826                                unset( $res[ $fieldName ][ $k ] );
2827                            }
2828                            unset( $res[ $controlAEI ][ $k ] );
2829                        }
2830                        else
2831                        {
2832                            $res[ $controlAEI ][ $k ] = 'E';
2833                        }
2834                        
2835                        $_SESSION[ APLICATIVO ][ 'offline' ][ $this->getId()] = $res;
2836                        $frm->clearFields();
2837                    }
2838                }
2839            }
2840            elseif( isset( $_POST[ 'action' ] ) && $_POST[ 'action' ] == 'clearAll' )
2841            {
2842                $_SESSION[ APLICATIVO ][ 'offline' ][ $this->getId()] = null;
2843                $frm->clearFields();
2844            }
2845        }
2846        
2847        // se ainda não existir na sessão os dados offline, ler do banco os valores já gravados e adicionar na sessão
2848        if ( !isset( $_SESSION[ APLICATIVO ][ 'offline' ][ $this->getId()] ) || !$_SESSION[ APLICATIVO ][ 'offline' ][ $this->getId()] && $this->getData() )
2849        {
2850            
2851            $data = $this->getData();
2852            $res = null;
2853            
2854            if ( $data )
2855            {
2856                foreach( $data[ $strFirstKeyField ] as $k => $v )
2857                {
2858                    foreach( $aFieldNames as $key => $fieldName )
2859                    {
2860                        $field = $frm->getField( $fieldName );
2861                        if ( $field->getFieldType() == 'select' )
2862                        {
2863                            
2864                            $c = $field->getAttribute('grid_column');
2865                            if( $c )
2866                            {
2867                                $res[ strtoupper( $c ) ][] = $data[ strToUpper($c) ][ $k ];
2868                            }
2869                            else
2870                            {
2871                                //echo $fieldName.'='.$frm->getField( $fieldName )->getText( $data[ strtoupper( $fieldName )][ $k ]).'<br>';
2872                                $res[ strtoupper( $fieldName . '_text' )][] = $frm->getField( $fieldName )->getText( $data[ strtoupper( $fieldName )][ $k ] );
2873                            }
2874                        }
2875                        $res[ strtoupper( $fieldName )][] = $data[ strtoupper( $fieldName )][ $k ];
2876                    }
2877                    $res[ $controlAEI ][] = '';
2878                }
2879            }
2880            $_SESSION[ APLICATIVO ][ 'offline' ][ $this->getId()] = $res;
2881        }
2882        
2883        if ( isset( $_SESSION[ APLICATIVO ][ 'offline' ][ $this->getId()] ) )
2884        {
2885            $res = $_SESSION[ APLICATIVO ][ 'offline' ][ $this->getId()];
2886        }
2887        
2888        if ( isset( $res ) )
2889        {
2890            $this->setData( $res );
2891        }
2892        /*
2893         if ($res)
2894         {
2895         // evitar scroll do formulario
2896         if( $this->getHeight() == 'auto' || $this->getHeight() == '100%')
2897         {
2898         $this->setHeight('120px');
2899         }
2900         }
2901         */
2902    }
2903    
2904    //------------------------------------------------------------------------------------------------
2905    /**
2906     * Grid Off-line define a cor do novo regristro
2907     * @return string
2908     */    
2909    public function setNewRecordColor( $newColor = null )
2910    {
2911        $this->newRecordColor = $newColor;
2912    }
2913    /**
2914     * Grid Off-line define a cor do novo regristro
2915     * @return string
2916     */
2917    public function getNewRecordColor()
2918    {
2919        return is_null( $this->newRecordColor ) ? 'blue' : $this->newRecordColor;
2920    }
2921    
2922    /**
2923     * Grid Off-line define a cor do novo alterado
2924     * @return string
2925     */
2926    public function setEditedRecordColor( $strNewValue = null )
2927    {
2928        $this->editedRecordColor = $strNewValue;
2929    }
2930    
2931    /**
2932     * Grid Off-line define a cor do novo alterado
2933     * @return string
2934     */    
2935    public function getEditedRecordColor()
2936    {
2937        return is_null( $this->editedRecordColor ) ? '#FF9900' : $this->editedRecordColor;
2938    }
2939    
2940    /**
2941     * Grid Off-line define a cor do novo salvo
2942     * @return string
2943     */
2944    public function setSavedRecordColor( $strNewValue = null )
2945    {
2946        $this->savedRecordColor = $strNewValue;
2947    }
2948    
2949    /**
2950     * Grid Off-line define a cor do novo salvo
2951     * @return string
2952     */
2953    public function getSavedRecordColor( $strNewValue = null )
2954    {
2955        return is_null( $this->savedRecordColor ) ? '#009933' : $this->savedRecordColor;
2956    }
2957    
2958    /**
2959     * Grid Off-line define a cor do novo deletado
2960     * @return string
2961     */
2962    public function getDeletedRecordColor()
2963    {
2964        return is_null( $this->deletedRecordColor ) ? '#FF0000' : $this->deletedRecordColor;
2965    }
2966    //------------------------------------------------------------------------------------------------
2967    /**
2968     * Define o nome de uma função php que a classe TGrid irá executar passando a classe TAutocomplete, o array de dados ($res) referente a linha atual, o objeto celula e o objeto coluna
2969     *
2970     * @param mixed $strNewValue
2971     */
2972    public function setOnGetAutocompleteParameters( $strNewValue = null )
2973    {
2974        $this->onGetAutocompleteParameters = $strNewValue;
2975    }
2976    
2977    public function getOnGetAutocompleteParameters()
2978    {
2979        return $this->onGetAutocompleteParameters;
2980    }
2981    
2982    //------------------------------------------------------------------------------------------------
2983    public function getFooter()
2984    {
2985        return $this->footerCell;
2986    }
2987    
2988    //-------------------------------------------------------------------------------------------------
2989    public function addFooter( $strValor = null )
2990    {
2991        if ( !is_null( $strValor ) )
2992        {
2993            $this->footerCell->add( $strValor );
2994        }
2995    }
2996    
2997    //-------------------------------------------------------------------------------------------------
2998    public function setFooter( $strValor = null )
2999    {
3000        $this->footerCell->clearChildren();
3001        $this->addFooterCell( $strValor );
3002    }
3003    
3004    //------------------------------------------------------------------------------------------------
3005    public function setSortable( $boolNewValue = null )
3006    {
3007        $this->sortable = ( bool ) $boolNewValue;
3008    }
3009    
3010    //------------------------------------------------------------------------------------
3011    public function getSortable()
3012    {
3013        return $this->sortable;
3014    }
3015    
3016    //------------------------------------------------------------------------------------
3017    public function addExcelHeadField( $strLabel, $strFieldName )
3018    {
3019        $this->excelHeadFields[ $strLabel ] = $strFieldName;
3020    }
3021    
3022    //------------------------------------------------------------------------------------
3023    public function getExcelHeadField($boolUtf8=false)
3024    {
3025        if( $boolUtf8 && is_array($this->excelHeadFields ) )
3026        {
3027            $arrTemp = array();
3028            foreach($this->excelHeadFields as $k=>$v)
3029            {
3030                $arrTemp[utf8_encode($k)] = utf8_encode($v);
3031            }
3032            return $arrTemp;
3033        }
3034        return $this->excelHeadFields;
3035    }
3036    
3037    //-------------------------------------------------------------------------------------
3038    public function getTitleCell()
3039    {
3040        return $this->titleCell;
3041    }
3042    
3043    //------------------------------------------------------------------------------------
3044    public function setShowCollapsed( $boolNewValue = null )
3045    {
3046        $this->showCollapsed = ( $boolNewValue === true ) ? true : false;
3047    }
3048    
3049    //------------------------------------------------------------------------------------
3050    public function getShowCollapsed()
3051    {
3052        if ( isset( $_REQUEST[ $this->getId() . '_collapsed' ] ) )
3053        {
3054            $this->showCollapsed = ( $_REQUEST[ $this->getId() . '_collapsed' ] == '1' );
3055        }
3056        return $this->showCollapsed;
3057    }
3058    
3059    //------------------------------------------------------------------------------------
3060    public function getData2Excel() {
3061        $res = $this->getData();
3062        //return $res;
3063        
3064        if ( !is_array( $res ) ) {
3065            return null;
3066        }
3067        $result = null;
3068        if( $this->getExportFullData() ) {
3069            return $res;
3070        }
3071        $keys =  array_keys($res);
3072        
3073        /*if( $this->getId() =='idGride')
3074         {
3075         print_r($res);
3076         echo '<hr>';
3077         echo 'key e keys<br>';
3078         echo '$res[ key( $res )]<br>';
3079         echo 'Primeira chave =  '.key( $res ).'<br>';
3080         echo 'ou Primeira chave =  '.$keys[0].'<br>';
3081         echo '<hr>';
3082         }
3083         */
3084        foreach( $res[ $keys[0] ] as $k => $v )
3085        {
3086            foreach( $this->getColumns() as $name => $objColumn )
3087            {
3088                $getName = $objColumn->getFieldName();
3089                $colName = isset($getName)?strtoupper($getName):null;
3090                if ( isset( $res[ $colName ] ) ) {
3091                    if ( $objColumn->getColumnType() != 'hidden' && $objColumn->getVisible() ) {
3092                        $colTitle = $objColumn->getTitle() ? $objColumn->getTitle() : $colName;
3093                        if ( ENCODINGS == 'UTF-8'){
3094                            $result[ utf8_decode($colTitle) ][ $k ] = $res[ $colName ][ $k ];
3095                        } else {
3096                            $result[ utf8_encode($colTitle) ][ $k ] = $res[ $colName ][ $k ];
3097                        }
3098                    }
3099                }
3100            }
3101        }
3102        return $result;
3103    }
3104    
3105    //------------------------------------------------------------------------------------
3106    public function setCreateDefaultEditButton( $boolNewValue = null )
3107    {
3108        $this->createDefaultEditButton = $boolNewValue;
3109    }
3110    
3111    public function getCreateDefaultEditButton( $boolNewValue = null )
3112    {
3113        return is_null( $this->createDefaultEditButton ) ? true : $this->createDefaultEditButton;
3114    }
3115    
3116    //------------------------------------------------------------------------------------
3117    public function setCreateDefaultDeleteButton( $boolNewValue = null )
3118    {
3119        $this->createDefaultDeleteButton = $boolNewValue;
3120    }
3121    
3122    public function getCreateDefaultDeleteButton( $boolNewValue = null )
3123    {
3124        return is_null( $this->createDefaultDeleteButton ) ? true : $this->createDefaultDeleteButton;
3125    }
3126    
3127    //------------------------------------------------------------------------------------
3128    /**
3129     * No Grid off-line Mostra o Botão adicionar
3130     * @param boolean $boolNewValue
3131     */
3132    public function setShowAdicionarButton( $boolNewValue = null )
3133    {
3134        $this->showAdicionarButton = $boolNewValue;
3135    }
3136    
3137    function getShowAdicionarButton()
3138    {
3139        return ( $this->showAdicionarButton === false ? false : true );
3140    }
3141    
3142    //------------------------------------------------------------------------------------
3143    public function setNoWrap( $boolNewValue = null )
3144    {
3145        $this->noWrap = $boolNewValue;
3146    }
3147    
3148    public function getNoWrap()
3149    {
3150        return ( $this->noWrap === true ) ? true : $this->noWrap;
3151    }
3152    public function setNoDataMessage($strNewValue=null)
3153    {
3154        $this->noDataMessage = $strNewValue;
3155    }
3156    public function getNoDataMessage()
3157    {
3158        return $this->noDataMessage;
3159    }
3160    /**
3161     * Ordenar arrays
3162     * $order pode ser: up ou down
3163     *
3164     * @param array $array
3165     * @param string $coluna
3166     * @param string $order
3167     */
3168    public function sortArray($array=null,$coluna=null,$order=null) {
3169        if(!is_array($array) || is_null( $coluna ) || $coluna == '' ) {
3170            return $array;
3171        }
3172        if( !isset($array[$coluna]) ) {
3173            $coluna = strtoupper( $coluna );
3174            if( !isset($array[$coluna]) ) {
3175                return $array;
3176            }
3177        }
3178        $order = is_null($order) ? 'up': $order;
3179        
3180        if( count($array[$coluna])==1) {
3181            return $array;
3182        }
3183        
3184        $tipoString = isset($tipoString) ? $tipoString : null;
3185        if($tipoString || $tipoString === null)
3186            $tipo = 'SORT_STRING';
3187            else
3188                $tipo = 'SORT_NUMERIC';
3189                
3190                if($order == 'up' )
3191                    $ordem = 'SORT_DESC';
3192                    else
3193                        $ordem = 'SORT_ASC';
3194                        // tratamento para colunas tipo DATA
3195                        $aDataInvertida=null;
3196                        if( substr($array[$coluna][0],2,1).substr($array[$coluna][0],5,1) == '//') {
3197                            foreach ($array[$coluna] as $k=>$v){
3198                                $aDataInvertida[$coluna][$k] = substr($v,6,4).'/'.substr($v,3,2).'/'.substr($v,0,2).' '.substr($v,11,8);
3199                            }
3200                            $expressao= 'array_multisort($aDataInvertida["'.$coluna.'"], '.$tipo.', '.$ordem;
3201                            $coluna='';
3202                        } else if( preg_match('/^\s*[+-]?(\d+|[1-9]\d?(\.\d{3,3})*)(,\d+)?\s*$/',$array[$coluna][0])) {
3203                            $tipo = 'SORT_NUMERIC';
3204                            foreach ($array[$coluna] as $k=>$v){
3205                                $aNumeroPonto[$coluna][$k] = preg_replace('/,/','.',preg_replace('/\./','',$v));
3206                            }
3207                            $expressao= 'array_multisort($aNumeroPonto["'.$coluna.'"], '.$tipo.', '.$ordem;
3208                            $coluna='';
3209                        } else {
3210                            $expressao= 'array_multisort($array["'.$coluna.'"], '.$tipo.', '.$ordem;
3211                        }
3212                        foreach ($array as $k=>$col){
3213                            $array[$k][0] = $array[$k][0]; // para corrigir o bug de não alterar os dados da sessao
3214                            if( $k != $coluna ){
3215                                $expressao.=' ,$array["'.$k.'"]';
3216                            }
3217                        }
3218                        reset( $array);
3219                        $expressao.=');';
3220                        eval($expressao);
3221                        return $array;
3222    }
3223    /**
3224     * Definir a imagem que será exibida no lugar de um botão desabilitado quando
3225     * o próprio botão não tiver a sua imagem desabilitada definida
3226     *
3227     * ex: $g->setDisabledButtonImage('fwDisabled.png');
3228     *
3229     * @param string $strNewImage
3230     */
3231    public function setDisabledButtonImage($strNewImage=null)
3232    {
3233        $this->disableButtonImage = $strNewImage;
3234    }
3235    public function getDisabledButtonImage()
3236    {
3237        return $this->disableButtonImage;
3238    }
3239    public function setExportFullData($boolNewValue=null)
3240    {
3241        $this->exportFullData = $boolNewValue;
3242    }
3243    public function getExportFullData()
3244    {
3245        return $this->exportFullData;
3246    }
3247    /**
3248     * Retorna um array de objeto com os campos do formulário
3249     *
3250     * @param object $frm
3251     */
3252    public function extractFormFields($frm=null)
3253    {
3254        $fields=array();
3255        if( ! $frm )
3256        {
3257            return $fields;
3258        }
3259        //echo 'qdt fields:'.count($frm->getDisplayControls()).',';
3260        foreach( $frm->getDisplayControls() as $fieldName => $dc )
3261        {
3262            //echo $fieldName.'<br>';
3263            $field = $dc->getField();
3264            //echo $field->getFieldType().', ';
3265            if( $field->getFieldType() == 'group' )
3266            {
3267                $fields = array_merge($fields, (array) $this->extractFormFields($field) );
3268            }
3269            else if( preg_match('/edit|memo|hidden|select|number|date|cpf|cpfcnpj|cnpj/i',$field->getFieldType() ) )
3270            {
3271                $label=null;
3272                if( !empty($dc->getLabel()) && method_exists($dc->getLabel(),'getValue'))
3273                {
3274                    $label =$dc->getLabel()->getValue();
3275                }
3276                $fields[] = (object) array('field'=>$field,'label'=>$label);
3277            }
3278        }
3279        return $fields;
3280    }
3281    
3282    public function addColumnConfig($intColIndex, $intWidth=null,$strAlign=null,$arrCss=null,$boolVisible=null)
3283    {
3284        $this->columnConfig[$intColIndex] = (object) array('width'=>$intWidth,'align'=>$strAlign,'arrCss'=>$arrCss,'visible'=>($boolVisible===false?false:true) );
3285        return $this;
3286    }
3287    public function getColumnConfig( $intColIndex )
3288    {
3289        return isset( $this->columnConfig[$intColIndex] ) ? $this->columnConfig[$intColIndex] : null;
3290    }
3291    //xxx------------------------------------------------------------------------------------
3292}
3293?>