Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
21.88% covered (danger)
21.88%
7 / 32
CRAP
17.00% covered (danger)
17.00%
59 / 347
TOption
0.00% covered (danger)
0.00%
0 / 1
21.88% covered (danger)
21.88%
7 / 32
14796.22
17.00% covered (danger)
17.00%
59 / 347
 __construct
0.00% covered (danger)
0.00%
0 / 1
8.43
69.23% covered (warning)
69.23%
18 / 26
 checkedItemRadioOrCheck
0.00% covered (danger)
0.00%
0 / 1
4.84
62.50% covered (warning)
62.50%
5 / 8
 showRadioOrCheck
0.00% covered (danger)
0.00%
0 / 1
930
0.00% covered (danger)
0.00%
0 / 106
 show
0.00% covered (danger)
0.00%
0 / 1
306
0.00% covered (danger)
0.00%
0 / 38
 setSelectSize
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 getSelectSize
0.00% covered (danger)
0.00%
0 / 1
12
0.00% covered (danger)
0.00%
0 / 5
 setMultiSelect
0.00% covered (danger)
0.00%
0 / 1
5.39
75.00% covered (success)
75.00%
6 / 8
 getMultiSelect
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 addColumn
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getColumnCount
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 setValue
0.00% covered (danger)
0.00%
0 / 1
2.06
75.00% covered (success)
75.00%
3 / 4
 getValue
0.00% covered (danger)
0.00%
0 / 1
11.84
45.45% covered (warning)
45.45%
5 / 11
 setOptions
0.00% covered (danger)
0.00%
0 / 1
2152.03
8.08% covered (danger)
8.08%
8 / 99
 getOptions
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setRequired
100.00% covered (success)
100.00%
1 / 1
2
100.00% covered (success)
100.00%
2 / 2
 getRequired
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setQtdColumns
100.00% covered (success)
100.00%
1 / 1
2
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
 setPaddingItems
100.00% covered (success)
100.00%
1 / 1
2
100.00% covered (success)
100.00%
2 / 2
 getPaddingRight
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setKeyField
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 setDisplayField
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 getKeyField
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 getDisplayField
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 validate
0.00% covered (danger)
0.00%
0 / 1
56
0.00% covered (danger)
0.00%
0 / 8
 setShowMinimal
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 getShowMinimal
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 1
 setNowrapText
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
2 / 2
 getNowrapText
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 1
 getOptionsData
0.00% covered (danger)
0.00%
0 / 1
6
0.00% covered (danger)
0.00%
0 / 1
 setOptionsData
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
 setOptionData
0.00% covered (danger)
0.00%
0 / 1
2
0.00% covered (danger)
0.00%
0 / 2
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/**
42 * Classe base para construção de inputs tipo radio button, checkbox, combobox e multi select
43 */
44abstract class TOption extends TControl
45{
46    
47    const RADIO = 'radio';
48    const CHECK = 'check';
49    const SELECT = 'select';
50    
51    private $arrOptions;
52    private $arrValues;
53    //private $required;
54    private $qtdColunms;
55    private $columns;
56    private $paddingRight;
57    private $multiSelect;
58    private $selectSize;
59    private $keyField;
60    private $displayField;
61    private $showMinimal;
62    private $nowWrapText;
63    private $arrOptionsData;
64    /**
65     * Método construtor
66     *
67     * $strDisplayColumn = nome da coluna que será utilizada para preencher as opções que serão exibidas para o usuário
68     *
69     * @abstract
70     * @param string $strName          - 1:
71     * @param array $mixOptions        - 2: Array no formato "id=>value" ou nome do pacote oracle e da função a ser executada
72     * @param array $arrValues         - 3: Array no formato "key=>id" para identificar a(s) opção(ões) selecionada(s)
73     * @param boolean $boolRequired    - 4: Default FALSE = não obrigatori, TRUE = obrigatorio
74     * @param integer $intQtdColumns   - 5: Quantidade de colunas, valor DEFAULT = 1;
75     * @param integer $intWidth        - 6:
76     * @param integer $intHeight       - 7:
77     * @param integer $intPaddingItems - 8: numero inteiro para definir o espaço vertical entre as colunas de opções
78     * @param boolean $boolMultiSelect -09: Default FALSE = SingleSelect, TRUE = MultiSelect
79     * @param string $strInputType     -10: Define o tipo de input a ser gerado. Ex: select, radio ou check
80     * @param string $strKeyField      -11: Nome da coluna que será utilizada para preencher os valores das opções
81     * @param string $strDisplayField  -12: Nome da coluna que será utilizada para preencher as opções que serão exibidas para o usuário
82     * @param boolean $boolNowrapText  -13:
83     * @param string $strDataColumns   -14: informações extras do banco de dados que deverão ser adicionadas na tag option do campo select
84     * @return TOption
85     */
86    public function __construct( $strName
87                               , $mixOptions
88                               , $arrValues=null
89                               , $boolRequired=null
90                               , $intQtdColumns=null
91                               , $intWidth=null
92                               , $intHeight=null
93                               , $intPaddingItems=null
94                               , $boolMultiSelect=null
95                               , $strInputType=null
96                               , $strKeyField=null
97                               , $strDisplayField=null
98                               , $boolNowrapText=null
99                               , $strDataColumns=null 
100                               )
101    {
102        parent::__construct( 'div', $strName );
103        $this->setValue( $arrValues );
104        $this->setRequired( $boolRequired );
105        $this->setQtdColumns( $intQtdColumns );
106        $this->setPaddingItems( $intPaddingItems );
107        $this->setFieldType( ($strInputType == null) ? self::SELECT : $strInputType );
108        $this->setMultiSelect( $boolMultiSelect );
109        $this->setCss( 'border',  '1px solid #c0c0c0' ); //#176 relacionado com FormDin4.js
110        //$this->setClass('fwFieldBoarder');
111        $this->setCss( 'display', 'inline' );
112        $this->setWidth( $intWidth );
113        $this->setHeight( $intHeight );
114        $this->setKeyField( $strKeyField );
115        $this->setDisplayField( $strDisplayField );
116        $this->setOptions( $mixOptions, $strDisplayField, $strKeyField, null, $strDataColumns );
117        $this->setNowrapText($boolNowrapText);
118        // tratamento para campos selects postados das colunas tipo do TGrid onde os nomes são arrays
119        if( $this->getFieldType() == self::SELECT && strpos( $this->getName(), '[' ) !== false ) {
120              $name = $this->getName();
121           $arrTemp = explode('[',$name);
122           if( isset($_POST[$arrTemp[0] ] ) ){
123              $expr = '$v=$_POST["'.str_replace( '[', '"][', $name ).';';
124              if( !FormDinHelper::pregMatch('/\[\]/',$expr )){
125                   @eval( $expr );
126                   $this->setValue( $v );
127              }
128           }
129        }
130        //if(isset($_POST[$this->getId()]) && $_POST[$this->getId()] )
131        if( isset( $_POST[ $this->getId() ] ) )
132        {
133            $this->setValue( $_POST[ $this->getId() ] );
134        }
135    }
136    
137    public function checkedItemRadioOrCheck( $input,$span,$k ){
138        if( $this->getFieldType() == self::RADIO ){
139            if( $k == $this->getValue() )
140            {
141                $input->setProperty( 'checked', "true" );
142                $span->setCss( 'color', '#0000ff' );
143            }
144        }else{
145            if( ( string ) array_search( $k, $this->getValue() ) != '' )
146            {
147                $input->setProperty( 'checked', "true" );
148                $span->setCss( 'color', '#0000ff' );
149            }
150        }
151    }
152    
153    public function showRadioOrCheck( $boolPrint=true ){
154        $this->setCss( 'overflow', 'auto' );
155        $this->setCss( 'border',  '1px solid transparent' );
156        // é necessário pelo menos uma coluna
157        if( ( int ) $this->getColumnCount() == 0 && ( int ) $this->getQtdColumns() == 0 )
158        {
159            $this->setQtdColumns( 1 );
160        }
161        if( $this->getColumnCount() == 0 )
162        {
163            for( $i = 0; $i < $this->getQtdColumns(); $i++ )
164            {
165                $this->addColumn( 'auto' );
166            }
167        }
168        else
169        {
170            $this->setQtdColumns( $this->getColumnCount() );
171        }
172        
173        // o campo multi deve ser construido utilizando table para fazer o layout dos itens em colunas
174        $this->add( $table = new TTable( $this->getName() . '_table' ) );
175        $table->setCss( $this->getCss() );
176        $table->setCss('border','1px solid transparent');
177        $table->setCss('background-color','transparent');
178        $table->setCss( 'display', null );
179        $this->clearCss();
180        $this->setcss( 'overflow', 'auto' );
181        $this->setcss( 'width', $table->getCss( 'width' ) );
182        $this->setcss( 'height', $table->getCss( 'height' ) );
183        $table->setCss( 'width', null );
184        $table->setCss( 'height', null );
185        $table->setCss( 'overflow', null );
186        if( !$table->getCss('font-size'))
187        {
188            $table->setCss('font-size','11px');
189        }
190        
191        $table->setProperty( 'border', 0 );
192        $table->setProperty( 'cellspacing', 0 );
193        $table->setProperty( 'cellpadding', 0 );
194        //transferir a borda do elemento container para table interna
195        if( !$this->getEnabled() )
196        {
197            $table->setProperty( 'disabled', 'true' );
198            $table->setCss( 'color', '#52A100' );
199            //$this->setId($this->getId().'_disabled');
200        }
201        if( is_array( $this->getOptions() ) )
202        {
203            $col = 0;
204            $item = 1;
205            $linkHelpFile = null;
206            foreach( $this->getOptions() as $k=>$v )
207            {
208                if( $col == 0 )
209                {
210                    $row = $table->addRow();
211                    $row->clearCss();
212                }
213                $k=trim($k);
214                $v=trim($v);
215                $input = new TElement( 'input' );
216                $input->clearCss();
217                $input->setProperty('label',$this->getProperty('label'));
218                $input->setCss( 'vertical-align', 'middle' );
219                if( !$this->getEnabled() )
220                {
221                    $input->setProperty( 'disabled', 'true' );
222                }
223                
224                if( $this->getMultiSelect() )
225                {
226                    $input->setProperty( 'type', 'checkbox' );
227                    $input->setName( $this->getId() . '[]' );
228                    $input->setProperty( 'id', $this->getId() . '_' . $k );
229                }
230                else
231                {
232                    $input->setProperty( 'type', 'radio' );
233                    $input->setName( $this->getId() );
234                    $input->setProperty( 'id', $this->getId() . '_' . $k );
235                    
236                }
237                $input->setProperty( 'value', $k );
238                $input->setCss( 'border', 'none' );
239                $input->setCss( 'cursor', 'pointer' );
240                $input->setEvents( $this->getEvents() );
241                $span = new TElement( 'span' );
242                $span->clearCss();
243                $span->setId( $this->getId() . '_opcao_' . $item++ );
244                $tableLayout=null;
245                if( ( string ) $v != '' )
246                {
247                    $span->add($v);
248                    if( $this->getWidth() && ! $this->getNowrapText() )
249                    {
250                        $tableLayout=new TTable();
251                        $tableLayout->setAttribute('border','0');
252                        $tableLayout->setAttribute('cellspacing','0');
253                        $tableLayout->setAttribute('cellpadding','0');
254                        $r = $tableLayout->addRow();
255                        $r->addCell($input);
256                        $r->addCell($span);
257                    }
258                    else
259                    {
260                        $input->add( $span );
261                    }
262                    
263                }
264                if( $this->getFieldType() == 'check' && $this->getEnabled() == true )
265                {
266                    $span->setcss( 'cursor', 'pointer' );
267                    $input->addEvent( 'onclick', "fwFieldCheckBoxClick(this,'" . $span->getId() . "')" );
268                    $span->setEvent( 'onclick', "fwGetObj('" . $input->getId() . "').click();" );
269                }
270                else if( $this->getFieldType() == 'radio' && $this->getEnabled() == true )
271                {
272                    $span->setcss( 'cursor', 'pointer' );
273                    $input->addEvent( 'onclick', "fwFieldRadioClick(this,'" . $span->getId() . "')" );
274                    $span->setEvent( 'onclick', "fwGetObj('" . $input->getId() . "').click();" );
275                }
276                
277                $this->checkedItemRadioOrCheck($input,$span,$k);
278                
279                
280                if( $this->getRequired() )
281                {
282                    $input->setProperty( 'needed', 'true' );
283                }
284                if( $tableLayout )
285                    $cell = $row->addCell( $tableLayout );
286                    else
287                        $cell = $row->addCell( $input );
288                        /* if(is_null($linkHelpFile) && $this->getHelpFile())
289                         {
290                         $aHelpFile = $this->getHelpFile();
291                         $linkHelpFile = "&nbsp;&nbsp;<a href=\"{$aHelpFile[0]}\" title=\"{$aHelpFile[1]}\" rel=\"gb_page_center[{$aHelpFile[2]},{$aHelpFile[3]}]\"><img style=\"vertical-align:middle;border:none;cursor:pointer;width:16px;height:16px;\" src=\"{$aHelpFile[4]}\"></a>";
292                         $cell->add($linkHelpFile);
293                         }
294                         */
295                        $cell->clearCss();
296                        if( !$this->getWidth() || $this->getNowrapText() )
297                        {
298                            $cell->setProperty( 'nowrap', true );
299                        }
300                        $cell->setcss( 'padding-right', $this->getPaddingRight() . 'px' );
301                        if( ( int ) $this->getQtdColumns() > 1 )
302                        {
303                            $cell->setcss( 'border-right', '0px solid #c0c0c0' );
304                        }
305                        
306                        // definir a largura
307                        if( $this->columns[ $col ][ 0 ] )
308                        {
309                            $cell->width = $this->columns[ $col ][ 0 ];
310                        }
311                        // definir a cor
312                        if( $this->columns[ $col ][ 1 ] )
313                        {
314                            $cell->setCss( 'color', $this->columns[ $col ][ 1 ] );
315                        }
316                        // definir o alinhamento
317                        if( $this->columns[ $col ][ 1 ] )
318                        {
319                            $cell->setCss( 'text-align', $this->columns[ $col ][ 2 ] );
320                        }
321                        $col++;
322                        if( $col == $this->getQtdColumns() )
323                        {
324                            $col = 0;
325                        }
326            }
327        }
328        // trocar o id da div para não conflitar
329        $this->setid( $this->getId() . '_container' );
330        
331        // para colocar a borda vermelha na validação do campo obrigatório tem que ter uma borda já definida
332        if( !$this->getCss('border') )
333        {
334            $this->setCss('border','1px solid transparent');
335        }
336        // retirar os eventos do objeto containter
337        $this->clearEvents();
338        if( $this->getShowMinimal() )
339        {
340            return $input->show( $boolPrint );
341        }
342        
343    }
344    
345    
346    /**
347     * cria o html do input
348     * se $boolPrint for true, joga o html para o browser
349     * se $boolPrint for false, retorna o html gerado apenas
350     * se $boolShowOnlyInput for true, será retornada somente a tag input do campo
351     *
352     * @param boolean $boolPrint
353     * @param boolean $boolShowOnlyInput
354     * @return string
355     */
356    public function show( $boolPrint=true )
357    {
358        if( $this->getFieldType() == 'radio' || $this->getFieldType() == 'check' )
359        {
360            $this->showRadioOrCheck($boolPrint);
361        } else {
362            // criar o input do tipo select ( comboBox )
363            if( $this->getMultiSelect() ) {
364                $this->setTagType( 'select multiple' );
365                $this->setName( $this->getId() . '[]' );
366                $this->setProperty( 'id', $this->getId() );
367            } else {
368                $this->setTagType( 'select' );
369                $this->setHeight( null );
370            }
371            $this->setProperty( 'size', $this->getSelectSize() );
372            $this->setCss( 'background-color', '#ffffff' );
373            // colocar hint se não tiver
374            if( $this->getMultiSelect() && $this->title == '' ) {
375                $this->setProperty( 'title', 'Pressione a tecla CTRL ou SHIFT para marcar/desmarcar as opções!' );
376            }
377            if( is_array( $this->getOptions() ) ) {
378                $this->setCss( 'cursor', 'pointer' );
379                $arrOptionsData = $this->getOptionsData();
380                foreach( $this->getOptions() as $k=>$v ) {
381                    $k=trim($k);
382                    $v=trim($v);
383                    $this->add( $opt = new TElement( 'option' ) );
384                    $opt->setProperty( 'value', $k );
385                    $opt->clearCss();
386                    if( !is_array( $this->getValue() ) ) {
387                        $decodeOption   = isset($k)?html_entity_decode( ( string ) $k ):'';
388                        $value = $this->getValue();
389                        $decodeGetValue = isset($value)?html_entity_decode( (string)$value,ENT_NOQUOTES, ENCODINGS ):'';
390                        if( $decodeOption == $decodeGetValue ) {
391                            $opt->setProperty( 'selected', "true" );
392                        }
393                    } else {
394                        if( ( string ) array_search( $k, $this->getValue() ) != "" ) {
395                            $opt->setProperty( 'selected', "true" );
396                        }
397                    }
398                    $opt->add( $v );
399
400                    if( isset( $arrOptionsData[$k] ) ) {
401                        if( is_array( $arrOptionsData[$k]  )) {
402                            foreach($arrOptionsData[$k] as $e=>$f) {
403                                $opt->setAttribute($e,$f);
404                            }
405                        } else {
406                            $opt->setAttribute('data-value',$arrOptionsData[$k] );
407                        }
408                    }
409                }//Fim foreach
410            }
411        }
412
413        if( $this->getRequired() ) {
414            $this->setProperty( 'needed', 'true' );
415        }
416
417        return parent::show( $boolPrint );
418    }
419
420    /**
421     * Define a quantidade de itens que ficarão visíveis quando o input for do tipo multi select
422     *
423     * @param integer $intNewValue
424     */
425    public function setSelectSize( $intNewValue=null )
426    {
427        $this->selectSize = ( int ) $intNewValue;
428        return $this;
429    }
430    /**
431     * Recupera a quantidade de itens que ficarão visíveis quando o input for do tipo multi select
432     *
433     */
434    public function getSelectSize()
435    {
436        if( ( int ) $this->selectSize == 0 )
437        {
438            if( $this->getMultiSelect() )
439            {
440                $this->setSelectSize( count( $this->getOptions() ) );
441            }
442            else
443            {
444                $this->setSelectSize( 1 );
445            }
446        }
447        return ( int ) $this->selectSize;
448    }
449    /**
450     * Define se o input será do tipo multi select
451     *
452     * @param boolean $boolMultiSelect
453     */
454    public function setMultiSelect( $boolMultiSelect=null )
455    {
456        $this->multiSelect = ( bool ) $boolMultiSelect;
457        if( $this->getFieldType() == 'select' )
458        {
459            if( $this->multiSelect === true )
460            {
461                $this->setFieldType( 'multiselect' );
462            }
463        }
464        else if( $this->getFieldType() == 'multiselect' )
465        {
466            if( $this->multiSelect === false )
467            {
468                $this->setFieldType( 'select' );
469            }
470        }
471        return $this;
472    }
473    /**
474     * Recupera se o input será do tipo multi select
475     *
476     */
477    public function getMultiSelect()
478    {
479        return $this->multiSelect;
480    }
481    /**
482     * Adiciona uma coluna para gerar a visualiazação dos checkbox ou radio buttons em mais de uma coluna
483     * Tambem pode ser utilzado o parametro $intQtdColumns para definir a quantidade de colunas caso NÃO seja necessário
484     * especificar a largura, cor e alinhamento de cada coluna.
485     *
486     * @param int $intWidth
487     * @param string $strColor
488     * @param string $strAlign
489     */
490    public function addColumn( $intWidth=null, $strColor=null, $strAlign=null )
491    {
492        $this->columns[ ] = array( $intWidth, $strColor, $strAlign );
493        return $this;
494    }
495    /**
496     * Recupera a quantidade de colunas
497     *
498     */
499    public function getColumnCount()
500    {
501        $result  = CountHelper::count( $this->columns ); 
502        return $result;
503    }
504    /**
505     * Define o(s) valor(es) que será(ão) selecionado(s) no campo
506     *
507     * @param mixed $mixValues
508     */
509    public function setValue( $mixValues=null )
510    {
511        if (is_array($mixValues)) {
512            $this->arrValues = $mixValues;
513        } else {
514            $this->arrValues = array($mixValues);
515        }
516        return $this;
517//         $this->arrValues = ( array ) $mixValues;
518    }
519    /**
520     * recupera os valores selecionados no input
521     *
522     */
523    public function getValue()
524    {
525        $type = $this->getFieldType();
526        if( $type == self::SELECT && !$this->getMultiSelect() ) {
527            if( $this->arrValues ) {
528                if( is_array( $this->arrValues ) ) {
529                    return $this->arrValues[ 0 ];
530                } else {
531                    return null;
532                }
533            }
534            return null;
535        } elseif ($type == self::RADIO){
536            $result = $this->arrValues[0];
537            return $result;
538        } else {
539            return ( array ) $this->arrValues;
540        }
541    }
542
543    /**
544     * Define um array no formato "key=>value" ou string no formato "S=SIM,N=NAO,..." ou
545     * o nome de um pacoteFunção para recuperar do banco de dados, neste
546     * caso pode ser especificada a coluna chave, a coluna descrição e
547     * searchFields como parametros para a função do pacote oracle.
548     *
549     * Ex: $mixSearchFields="cod_uf=53,num_pessoa=20" ou array('COD_UF'=53,'NUM_PESSOA'=>20)
550     * Ex: $strDataColumns = "cod_uf,sig_uf,cod_regiao"
551     *
552     * @param mixed $mixOptions
553     * @param string $strDisplayField
554     * @param string $strKeyField
555     * @param mixed $mixSearchFields
556     * @param string $strDataColumns
557     */
558    public function setOptions( $mixOptions=null, $strDisplayField=null, $strKeyField=null, $mixSearchFields=null, $strDataColumns=null )
559    {
560        if( isset( $mixOptions ) ) {
561
562            if( !is_null($strDataColumns) && trim( $strDataColumns) != '' ) {
563                $arrDataColumns    = explode(',',$strDataColumns);
564                $strDataColumns    = ','.$strDataColumns.' ';
565            }
566
567            if( is_string( $mixOptions ) ) {
568                $where = null;
569                $cacheSeconds = null;
570                if( FormDinHelper::pregMatch('/\|/',$mixOptions)){
571                    $mixOptions      = explode( '|', $mixOptions );
572                    $mixOptions[1]  = ( isset( $mixOptions[1] ) ? $mixOptions[1] : '' );
573                    // segundo parametro pode ser o where ou tempo de cache
574                    $where          = is_numeric($mixOptions[1] ) ? '' : $mixOptions[1];
575                    $cacheSeconds= is_numeric($mixOptions[1])  ? $mixOptions[1] : null;
576                    $mixOptions  = $mixOptions[0];
577                }
578                // verificar se passou no formato "S=SIM,N=NAO...."
579                if( strpos( $mixOptions, '=' ) || strlen($mixOptions)==1 )
580                {
581
582                // tratar opção de 1 caractere. Ex: S,N,1,2...
583                    if( strlen($mixOptions)==1 ){
584                        $mixOptions = array( 'N'=>'' );
585                    } else {
586                        // tratar formato S=>SIM,N=>NÃO
587                        $mixOptions = preg_replace('/\=\>/','=',$mixOptions);
588                        $mixOptions = explode( ',', $mixOptions );
589                        forEach( $mixOptions as $k=>$v )
590                        {
591                            $v = explode( '=', $v );
592                            $v[ 1 ] = ( isset( $v[ 1 ] ) ) ? $v[ 1 ] : $v[ 0 ];
593                            $arrTemp[ $v[ 0 ] ] = $v[ 1 ];
594                        }
595                        $mixOptions = $arrTemp;
596                        $arrTemp = null;
597                    }
598                }
599                else
600                {
601                    if( function_exists( 'recuperarPacote' ) )
602                    {
603                        $packageName     = $mixOptions;
604                        $mixOptions = null;
605                        $searchFields = null;
606                        if( isset( $mixSearchFields ) )
607                        {
608                            if( is_string( $mixSearchFields ) )
609                            {
610                                $searchFields = explode( ',', $mixSearchFields );
611                                if( is_array( $searchFields ) )
612                                {
613                                    forEach( $searchFields as $k=>$v )
614                                    {
615                                        $v = explode( '=', $v );
616                                        $bvars[ $v[ 0 ] ] = $v[ 1 ];
617                                    }
618                                }
619                            }
620                            else if( is_array( $mixSearchFields ) )
621                            {
622                                $bvars = $mixSearchFields;
623                            }
624                        }
625                        // se passou somente o nome da tabela , criar comando select
626                        if( FormDinHelper::pregMatch( '/\.PK\a?/i', $packageName ) ){
627                            print_r( recuperarPacote( $packageName, $bvars, $mixOptions, $cacheSeconds ) );
628                        } else {
629                            if( $strKeyField && $strDisplayField ) {
630                                $sql = "select {$strKeyField},{$strDisplayField}{$strDataColumns} from  {$packageName} order by {$strDisplayField}";
631                            } else {
632                                if( !FormDinHelper::pregMatch( '/' . ESQUEMA . '\./', $packageName ) ){
633                                    $packageName = ESQUEMA . '.' . $packageName;
634                                }
635                                $sql = "select * from {$packageName}";
636                            }
637                            $bvars = null;
638                            $nrows = 0;
639                            $mixOptions = null;
640                            if( $GLOBALS[ 'conexao' ] ) {
641                                if( $GLOBALS[ 'conexao' ]->executar_recuperar( $sql, $bvars, $mixOptions, $nrows ) )
642                                {
643                                    echo 'Erro na execução do sql:' . $sql;
644                                }
645                            }
646                        }
647                    } else {
648                        if( TPDOConnection::getInstance() ) {
649                            if( FormDinHelper::pregMatch( '/^select/i', $mixOptions ) > 0 ){
650                                $mixOptions = TPDOConnection::executeSql( $mixOptions );
651                            } else {
652                                if( !is_null( $where ) ){
653                                    $where = ' where ' . preg_replace( '/"/', "'", $where );
654                                } else {
655                                    $where = '';
656                                }
657                                if( $this->getKeyField() && $this->getDisplayField() ) {
658                                    $sql = "select {$this->getKeyField()},{$this->getDisplayField()}{$strDataColumns} from {$mixOptions} {$where} order by {$this->getDisplayField()}";
659                                } else {
660                                    $sql = "select * from {$mixOptions} {$where}";
661                                }
662                                $mixOptions = TPDOConnection::executeSql( $sql );
663                            }
664                            TPDOConnection::showError();
665                        }
666                    }
667                }
668            }
669
670            $this->arrOptions = null;
671            if( is_array( $mixOptions ) )
672            {
673                // verificar se o array está no formato oracle
674                if( key( $mixOptions ) && is_array( $mixOptions[ key( $mixOptions ) ] ) )
675                {
676                    // assumir a primeira e segunda coluna para popular as opções caso não tenha sido informadas
677                    if( !isset( $strKeyField ) )
678                    {
679                        if( !$this->getKeyField() )
680                        {
681                            list($strKeyField) = array_keys( $mixOptions );
682                        }
683                        else
684                        {
685                            $strKeyField = $this->getKeyField();
686                        }
687                    }
688                    if( !isset( $strDisplayField ) )
689                    {
690                        if( !$this->getDisplayField() )
691                        {
692                            list(, $strDisplayField) = array_keys( $mixOptions );
693                        }
694                        else
695                        {
696                            $strDisplayField = $this->getDisplayField();
697                        }
698                        if( !isset( $strDisplayField ) )
699                        {
700                            $strDisplayField = $strKeyField;
701                        }
702                    }
703                    if( $strKeyField && $strDisplayField )
704                    {
705                        // reconhecer nome da columa em caixa baixa ou alta
706                        if( !array_key_exists( $strKeyField, $mixOptions ) )
707                        {
708                            $strKeyField = strtoupper( $strKeyField );
709                            $strDisplayField = strtoupper( $strDisplayField );
710                        }
711                        if( !array_key_exists( $strKeyField, $mixOptions ) )
712                        {
713                            $strKeyField = strtolower( $strKeyField );
714                            $strDisplayField = strtolower( $strDisplayField );
715                        }
716                        if( is_array( $mixOptions[ $strKeyField ] ) )
717                        {
718                            foreach( $mixOptions[ $strKeyField ] as $k=>$v )
719                            {
720                                $this->arrOptions[ $v ] = $mixOptions[ $strDisplayField ][ $k ];
721                                if( isset( $arrDataColumns ) && is_array( $arrDataColumns ) )
722                                {
723                                    foreach($arrDataColumns as $colName )
724                                    {
725                                        $value='';
726                                        if( isset( $mixOptions[$colName][$k] ) )
727                                        {
728                                            $value = $mixOptions[$colName][$k];
729                                        }
730                                        elseif( isset( $mixOptions[strtoupper($colName) ][$k] ) )
731                                        {
732                                            $value = $mixOptions[strtoupper($colName) ][$k];
733                                        }
734                                        elseif( isset( $mixOptions[strtolower($colName) ][$k] ) )
735                                        {
736                                            $value = $mixOptions[strtolower($colName)][$k];
737                                        }
738                                        $value = $this->specialChars2htmlEntities( $value );
739                                        $value = empty($value)?array():$value;
740                                        $value = preg_replace("/\n/",' ',$value);
741                                        $this->arrOptionsData[$v]['data-'.strtolower($colName)] = $value;
742                                    }
743                                }
744                            }
745                        }
746                    }
747                }
748                else
749                {
750                    $this->arrOptions = $mixOptions;
751                }
752            }
753        }
754        return $this;
755    }
756
757    /**
758     * Recupera o array de opções do campo
759     *
760     */
761    public function getOptions()
762    {
763        return $this->arrOptions;
764    }
765    /**
766     * Define se o campo deverá ter pelo menos uma opção selecinada para o teste de validação
767     *
768     * @param boolean $boolValue
769     */
770    public function setRequired( $boolValue=null )
771    {
772        $this->setAttribute('needed', ( ( bool ) $boolValue ? 'true' : 'false' ) );
773        return $this;
774    }
775    /**
776     * Retorna se campo está definido como obrigatório.
777     *
778     */
779    public function getRequired()
780    {
781        return $this->getAttribute('needed') == "true";
782    }
783
784    /**
785     * Define a quantidade de colunas para distribuição dos checkbox ou radios na tela
786     *
787     * @param integer $intNewValue
788     */
789    public function setQtdColumns( $intNewValue=null )
790    {
791        $this->qtdColunms = (( int ) $intNewValue == 0) ? 1 : ( int ) $intNewValue;
792        return $this;
793    }
794    /**
795     * Recupera a quantidade de colunas para distribuição dos checkbox ou radios na tela
796     *
797     */
798    public function getQtdColumns()
799    {
800        return ( int ) $this->qtdColunms;
801    }
802    /**
803     * Define a distância entre as colunas. Padrão=20px
804     * @deprecated
805     * @param integer $intNewValue
806     */
807    public function setPaddingItems( $intNewValue=null )
808    {
809        $this->paddingRight = (( int ) $intNewValue == 0) ? 20 : ( int ) $intNewValue;
810        return $this;
811    }
812    /**
813     * DEPRECADED - change to setClass
814     * recupera a distância entre as colunas. Padrão=20px
815     * @deprecated
816     * @return number
817     */
818    public function getPaddingRight()
819    {
820        return ( int ) $this->paddingRight;
821    }
822    //-------------------------------------------------
823    public function setKeyField( $strNewValue=null )
824    {
825        $this->keyField = $strNewValue;
826        return $this;
827    }
828    //-------------------------------------------------
829    public function setDisplayField( $strNewValue=null )
830    {
831        $this->displayField = $strNewValue;
832        return $this;
833    }
834    //-------------------------------------------------
835    public function getKeyField()
836    {
837        return $this->keyField;
838    }
839    //-------------------------------------------------
840    public function getDisplayField()
841    {
842        return $this->displayField;
843    }
844    //---------------------------------------------------
845    public function validate()
846    {
847        if( $this->getRequired() == true  )
848        {
849            $value = $this->getValue();
850            if( is_array( $value ) )
851            {
852                if( count( $value) == 0 || trim( $value[0] ) == ''  )
853                {
854                    $this->addError( "Campo obrigatório" );
855                }
856            }
857            else if ( is_null( $value ) || trim($value) == '' )
858            {
859                $this->addError( "Campo obrigatório" );
860            }
861        }
862        return ( ( string ) $this->getError() === "" );
863    }
864    /**
865     * Permite retornar somente a tag input do campo sem as tags de formatação para exibição na classe TForm.
866     *
867     * @param boolean $boolNewValue
868     */
869    public function setShowMinimal( $boolNewValue=null )
870    {
871        $this->showMinimal = $boolNewValue;
872        return $this;
873    }
874    public function getShowMinimal()
875    {
876        return $this->showMinimal;
877    }
878    public function setNowrapText($boolNewValue = null )
879    {
880        $this->nowWrapText = $boolNewValue;
881        return $this;
882    }
883    public function getNowrapText()
884    {
885        return $this->nowWrapText === true? true: false;
886    }
887    public function getOptionsData()
888    {
889        return is_null( $this->arrOptionsData ) ? array() : $this->arrOptionsData;
890    }
891    public function setOptionsData($arrData=null)
892    {
893        $this->arrOptionsData = $arrData;
894        return $this;
895    }
896    public function setOptionData($strKey=null,$strValue=null)
897    {
898        $this->arrOptionsData[$strKey] = $strValue;
899        return $this;
900    }
901}
902//return;
903/*
904  $radio = new TRadio('tip_bioma',array(1=>'Cerrado',2=>'Pantanal'),null,true,2);
905  $radio->show();
906  $check = new TCheck('tip_vegetacao',array(1=>'Cerrado',2=>'Pantanal'),null,true,2);
907  $check->show();
908  return;
909 */
910/* for($i=1;$i<10;$i++)
911  {
912  $opt[$i]='Opção Nº '.($i+1);
913  }
914  //$check = new TCheck('chk',array(1=>'Maça',2=>'Tomate',3=>'Limão'),array('2',1),false);
915  //$check = new TCheck('chk',$opt,array('2',1),false,5,null,null,null,5);
916  //$check->show();
917  //$check = new TCheck('chk',$opt,array('2',1),false,10,800,600,null,5);
918  //$check->addColumn(100,'black','left');
919  //$check->addColumn(100,'red','left');
920  //$check->addColumn(100,'blue','left');
921  //
922  //$check->setEvent('onclick','fwTeste(this.value)');
923  //$check->setflat(false);
924 */
925
926/*
927  print '<form name="formdin" method="POST" action="">';
928  $select = new TSelect('tip_arvore',array(1=>'Cerrado',2=>'Pantanal',3=>'Mata',5=>'Caatinga'),null,true,true,3,500);
929  $select->show();
930  print '<hr>';
931  print '<input type="submit" value="Gravar">';
932  print '</form>';
933  print_r($_REQUEST);
934 */
935
936/*
937  $select = new TSelect('seq_bioma',"1=Um,2=Dois");
938  $select->show();
939  $ta = new TMemo('memo','Lua de sao jorge',200,false,100,5);
940  $ta->show();
941 */
942?>