Lançado Adianti Framework 7.6!
Clique aqui para saber mais
Colorir campo Status na Grid de acordo com critério. Boa noite pessoal. Tenho uma grid de atendimentos ao qual existe uma coluna de status (id_status). Gostaria que de acordo com o valor da coluna o campo exibisse a cor conforme o critérios. Estou usando o código abaixo, mas some o valor da coluna e nada acontece. Segue: ...
CM
Colorir campo Status na Grid de acordo com critério.  
Boa noite pessoal.
Tenho uma grid de atendimentos ao qual existe uma coluna de status (id_status).
Gostaria que de acordo com o valor da coluna o campo exibisse a cor conforme o critérios.
Estou usando o código abaixo, mas some o valor da coluna e nada acontece.
Segue:

  1. <?php
  2. $column_id_status->setTransformer(function($value$object$row) { 
  3.          $lbl = new TLabel(''); 
  4.          if ($value == '1') { 
  5.              $lbl->setLabel('REGISTRADO'); 
  6.              $lbl->class 'label label-primary'
  7.          } 
  8.          if ($value == '3') { 
  9.              $lbl->setLabel('EM ATENDIMENTO'); 
  10.              $lbl->class 'label label-warning'
  11.          }  
  12.          if ($value == '4') { 
  13.              $lbl->setLabel('CONCLUÍDO'); 
  14.              $lbl->class 'label label-success'
  15.          }  
  16.          return $lbl
  17.          });
  18. ?>


Lembrando que a coluna pega o valor do banco de dados.

Obrigado

Pacotão Dominando o Adianti Framework 7
O material mais completo de treinamento do Framework.
Curso em vídeo aulas + Livro completo + Códigos fontes do projeto ERPHouse.
Conteúdo Atualizado! Versão 7.4


Dominando o Adianti 7 Quero me inscrever agora!

Comentários (7)


CM

Se precisar, segue o código da grid.

  1. <?php
  1. <?php
  2. /**
  3.  * AgendaAtendimentoList Listing
  4.  * @author  <your name here>
  5.  */
  6. class AgendaAtendimentoList extends TPage
  7. {
  8.     private $form// form
  9.     private $datagrid// listing
  10.     private $pageNavigation;
  11.     private $formgrid;
  12.     private $loaded;
  13.     private $deleteButton;
  14.     private $column_id_status;
  15.         
  16.     /**
  17.      * Class constructor
  18.      * Creates the page, the form and the listing
  19.      */
  20.     public function __construct()
  21.     {
  22.         parent::__construct();
  23.         $Titulo_pg '<b><font color="#3C8DBC" size="4px">Lista de Atendimentos</font> </b>'
  24.         echo "$Titulo_pg <br/> <br/>" 
  25.              
  26.         // creates the form
  27.         $this->form = new BootstrapFormBuilder('form_AgendaAtendimento');       
  28.         // create the form fields
  29.         $id = new TEntry('id');
  30.         $id_atendente = new TDBCombo('id_atendente''sistema''Atendentes''id''descricao');
  31.         $id_cliente = new TDBCombo('id_cliente''sistema''Clientes''id''descricao');
  32.         $data_registro = new TEntry('data_registro');
  33.         $registrado_por = new TEntry('registrado_por');
  34.         $data_atendimento = new TEntry('data_atendimento');
  35.         $hora_atendimento = new TEntry('hora_atendimento');
  36.         $id_status = new TDBCombo('id_status''sistema''AtendimentoStatus''id''descricao');
  37.         // add the fields
  38.         $this->form->addFields( [ new TLabel('Atendente') ], [ $id_atendente ],
  39.                                 [ new TLabel('Cliente') ], [ $id_cliente ] );
  40.                
  41.         // set sizes
  42.         $id->setSize('100%');
  43.         $id_atendente->setSize('100%');
  44.         $id_cliente->setSize('100%');
  45.         $data_registro->setSize('100%');
  46.         $registrado_por->setSize('100%');
  47.         $data_atendimento->setSize('100%');
  48.         $hora_atendimento->setSize('100%');
  49.         $id_status->setSize('100%');
  50.         
  51.         // keep the form filled during navigation with session data
  52.         $this->form->setDataTSession::getValue('AgendaAtendimento_filter_data') );
  53.         
  54.         // add the search form actions
  55.         $btn_salvar $this->form->addAction(_t('Find'), new TAction([$this'onSearch']), 'fa:search');
  56.         $btn_salvar->class 'btn btn-sm btn-primary';
  57.         $btn_novo $this->form->addActionLink(_t('New'), new TAction(['AgendaAtendimentoForm''onEdit']), 'fa:plus white');
  58.         $btn_novo->class 'btn btn-sm btn-success';
  59.         
  60.         // creates a Datagrid
  61.         $this->datagrid = new BootstrapDatagridWrapper(new TDataGrid);
  62.         $this->datagrid->style 'width: 100%';
  63.         $this->datagrid->datatable 'true';
  64.         // $this->datagrid->enablePopover('Popover', 'Hi <b> {name} </b>');
  65.         
  66.         // creates the datagrid columns
  67.         $column_id = new TDataGridColumn('id''Id''left');
  68.         $column_id_atendente = new TDataGridColumn('{atendente->descricao}''Atendente''left');
  69.         $column_id_cliente = new TDataGridColumn('{cliente->descricao}''Cliente''left');
  70.         $column_data_registro = new TDataGridColumn('data_registro''Data Registro''left');
  71.         $column_registrado_por = new TDataGridColumn('registrado_por''Registrado Por''left');
  72.         $column_data_atendimento = new TDataGridColumn('data_atendimento''Data Atend.''left');
  73.         $column_hora_atendimento = new TDataGridColumn('hora_atendimento''Hora Atend.''left');
  74.         $column_id_status = new TDataGridColumn('{status->descricao}''Status''left');
  75.         
  76.         // add the columns to the DataGrid
  77.         $this->datagrid->addColumn($column_id);
  78.         $this->datagrid->addColumn($column_id_atendente);
  79.         $this->datagrid->addColumn($column_id_cliente);
  80.         $this->datagrid->addColumn($column_data_atendimento);
  81.         $this->datagrid->addColumn($column_id_status);
  82.        
  83.          $column_id_status->setTransformer(function($value$object$row) { 
  84.          $lbl = new TLabel(''); 
  85.          if ($value == '1') { 
  86.              $lbl->setLabel('REGISTRADO'); 
  87.              $lbl->class 'label label-primary'
  88.          } 
  89.          if ($value == '3') { 
  90.              $lbl->setLabel('EM ATENDIMENTO'); 
  91.              $lbl->class 'label label-warning'
  92.          }  
  93.          if ($value == '4') { 
  94.              $lbl->setLabel('CONCLUÍDO'); 
  95.              $lbl->class 'label label-success'
  96.          }  
  97.          return $lbl
  98.          });
  99.         
  100.            
  101.         // define the transformer method over image
  102.         $column_id_atendente->setTransformer( function($value$object$row) {
  103.             return strtoupper($value);
  104.         });
  105.         // define the transformer method over image
  106.         $column_id_cliente->setTransformer( function($value$object$row) {
  107.             return strtoupper($value);
  108.         });
  109.         // define the transformer method over image
  110.         $column_data_registro->setTransformer( function($value$object$row) {
  111.             if ($value)
  112.             {
  113.                 try
  114.                 {
  115.                     $date = new DateTime($value);
  116.                     return $date->format('d/m/Y');
  117.                 }
  118.                 catch (Exception $e)
  119.                 {
  120.                     return $value;
  121.                 }
  122.             }
  123.             return $value;
  124.         });
  125.         // define the transformer method over image
  126.         $column_registrado_por->setTransformer( function($value$object$row) {
  127.             return strtoupper($value);
  128.         });
  129.         // define the transformer method over image
  130.         $column_data_atendimento->setTransformer( function($value$object$row) {
  131.             if ($value)
  132.             {
  133.                 try
  134.                 {
  135.                     $date = new DateTime($value);
  136.                     return $date->format('d/m/Y');
  137.                 }
  138.                 catch (Exception $e)
  139.                 {
  140.                     return $value;
  141.                 }
  142.             }
  143.             return $value;
  144.         });
  145.         // creates the datagrid column actions
  146.         $column_data_registro->setAction(new TAction([$this'onReload']), ['order' => 'data_registro']);
  147.         $column_data_atendimento->setAction(new TAction([$this'onReload']), ['order' => 'data_atendimento']);
  148.         
  149.         // create EDIT action
  150.         $action_edit = new TDataGridAction(['AgendaAtendimentoForm''onEdit']);
  151.         //$action_edit->setUseButton(TRUE);
  152.         //$action_edit->setButtonClass('btn btn-default');
  153.         $action_edit->setLabel(_t('Edit'));
  154.         $action_edit->setImage('fa:pencil-square-o blue fa-lg');
  155.         $action_edit->setField('id');
  156.         $this->datagrid->addAction($action_edit);
  157.         
  158.         // create DELETE action
  159.         $action_del = new TDataGridAction(array($this'onDelete'));
  160.         //$action_del->setUseButton(TRUE);
  161.         //$action_del->setButtonClass('btn btn-default');
  162.         $action_del->setLabel(_t('Delete'));
  163.         $action_del->setImage('fa:trash-o red fa-lg');
  164.         $action_del->setField('id');
  165.         $this->datagrid->addAction($action_del);
  166.         
  167.         // create the datagrid model
  168.         $this->datagrid->createModel();
  169.         
  170.         // creates the page navigation
  171.         $this->pageNavigation = new TPageNavigation;
  172.         $this->pageNavigation->setAction(new TAction([$this'onReload']));
  173.         $this->pageNavigation->setWidth($this->datagrid->getWidth());          
  174.         // vertical box container
  175.         $container = new TVBox;
  176.         $container->style 'width: 90%';
  177.         //$container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  178.         $container->add($this->form);
  179.         $container->add(TPanelGroup::pack(''$this->datagrid$this->pageNavigation));
  180.                 
  181.         parent::add($container);
  182.     }
  183.    
  184.                 
  185.     /**
  186.      * Inline record editing
  187.      * @param $param Array containing:
  188.      *              key: object ID value
  189.      *              field name: object attribute to be updated
  190.      *              value: new attribute content 
  191.      */
  192.     public function onInlineEdit($param)
  193.     {
  194.         try
  195.         {
  196.             // get the parameter $key
  197.             $field $param['field'];
  198.             $key   $param['key'];
  199.             $value $param['value'];
  200.             
  201.             TTransaction::open('sistema'); // open a transaction with database
  202.             $object = new AgendaAtendimento($key); // instantiates the Active Record
  203.             $object->{$field} = $value;
  204.             $object->store(); // update the object in the database
  205.             TTransaction::close(); // close the transaction
  206.             
  207.             $this->onReload($param); // reload the listing
  208.             new TMessage('info'"Record Updated");
  209.         }
  210.         catch (Exception $e// in case of exception
  211.         {
  212.             new TMessage('error'$e->getMessage()); // shows the exception error message
  213.             TTransaction::rollback(); // undo all pending operations
  214.         }
  215.     }
  216.     
  217.     /**
  218.      * Register the filter in the session
  219.      */
  220.     public function onSearch()
  221.     {
  222.         // get the search form data
  223.         $data $this->form->getData();
  224.         
  225.         // clear session filters
  226.         TSession::setValue('AgendaAtendimentoList_filter_id',   NULL);
  227.         TSession::setValue('AgendaAtendimentoList_filter_id_atendente',   NULL);
  228.         TSession::setValue('AgendaAtendimentoList_filter_id_cliente',   NULL);
  229.         TSession::setValue('AgendaAtendimentoList_filter_data_registro',   NULL);
  230.         TSession::setValue('AgendaAtendimentoList_filter_registrado_por',   NULL);
  231.         TSession::setValue('AgendaAtendimentoList_filter_data_atendimento',   NULL);
  232.         TSession::setValue('AgendaAtendimentoList_filter_hora_atendimento',   NULL);
  233.         TSession::setValue('AgendaAtendimentoList_filter_id_status',   NULL);
  234.         if (isset($data->id) AND ($data->id)) {
  235.             $filter = new TFilter('id''='"$data->id"); // create the filter
  236.             TSession::setValue('AgendaAtendimentoList_filter_id',   $filter); // stores the filter in the session
  237.         }
  238.         if (isset($data->id_atendente) AND ($data->id_atendente)) {
  239.             $filter = new TFilter('id_atendente''like'"%{$data->id_atendente}%"); // create the filter
  240.             TSession::setValue('AgendaAtendimentoList_filter_id_atendente',   $filter); // stores the filter in the session
  241.         }
  242.         if (isset($data->id_cliente) AND ($data->id_cliente)) {
  243.             $filter = new TFilter('id_cliente''like'"%{$data->id_cliente}%"); // create the filter
  244.             TSession::setValue('AgendaAtendimentoList_filter_id_cliente',   $filter); // stores the filter in the session
  245.         }
  246.         if (isset($data->data_registro) AND ($data->data_registro)) {
  247.             $filter = new TFilter('data_registro''like'"%{$data->data_registro}%"); // create the filter
  248.             TSession::setValue('AgendaAtendimentoList_filter_data_registro',   $filter); // stores the filter in the session
  249.         }
  250.         if (isset($data->registrado_por) AND ($data->registrado_por)) {
  251.             $filter = new TFilter('registrado_por''like'"%{$data->registrado_por}%"); // create the filter
  252.             TSession::setValue('AgendaAtendimentoList_filter_registrado_por',   $filter); // stores the filter in the session
  253.         }
  254.         if (isset($data->data_atendimento) AND ($data->data_atendimento)) {
  255.             $filter = new TFilter('data_atendimento''like'"%{$data->data_atendimento}%"); // create the filter
  256.             TSession::setValue('AgendaAtendimentoList_filter_data_atendimento',   $filter); // stores the filter in the session
  257.         }
  258.         if (isset($data->hora_atendimento) AND ($data->hora_atendimento)) {
  259.             $filter = new TFilter('hora_atendimento''like'"%{$data->hora_atendimento}%"); // create the filter
  260.             TSession::setValue('AgendaAtendimentoList_filter_hora_atendimento',   $filter); // stores the filter in the session
  261.         }
  262.         if (isset($data->id_status) AND ($data->id_status)) {
  263.             $filter = new TFilter('id_status''like'"%{$data->id_status}%"); // create the filter
  264.             TSession::setValue('AgendaAtendimentoList_filter_id_status',   $filter); // stores the filter in the session
  265.         }
  266.         
  267.         // fill the form with data again
  268.         $this->form->setData($data);
  269.         
  270.         // keep the search data in the session
  271.         TSession::setValue('AgendaAtendimento_filter_data'$data);
  272.         
  273.         $param = array();
  274.         $param['offset']    =0;
  275.         $param['first_page']=1;
  276.         $this->onReload($param);
  277.     }
  278.     
  279.     /**
  280.      * Load the datagrid with data
  281.      */
  282.     public function onReload($param NULL)
  283.     {
  284.         try
  285.         {
  286.             // open a transaction with database 'sistema'
  287.             TTransaction::open('sistema');
  288.             
  289.             // creates a repository for AgendaAtendimento
  290.             $repository = new TRepository('AgendaAtendimento');
  291.             $limit 10;
  292.             // creates a criteria
  293.             $criteria = new TCriteria;
  294.             
  295.             // default order
  296.             if (empty($param['order']))
  297.             {
  298.                 $param['order'] = 'data_atendimento';
  299.                 $param['direction'] = 'desc';
  300.             }
  301.             $criteria->setProperties($param); // order, offset
  302.             $criteria->setProperty('limit'$limit);
  303.             
  304.             if (TSession::getValue('AgendaAtendimentoList_filter_id')) {
  305.                 $criteria->add(TSession::getValue('AgendaAtendimentoList_filter_id')); // add the session filter
  306.             }
  307.             if (TSession::getValue('AgendaAtendimentoList_filter_id_atendente')) {
  308.                 $criteria->add(TSession::getValue('AgendaAtendimentoList_filter_id_atendente')); // add the session filter
  309.             }
  310.             if (TSession::getValue('AgendaAtendimentoList_filter_id_cliente')) {
  311.                 $criteria->add(TSession::getValue('AgendaAtendimentoList_filter_id_cliente')); // add the session filter
  312.             }
  313.             if (TSession::getValue('AgendaAtendimentoList_filter_data_registro')) {
  314.                 $criteria->add(TSession::getValue('AgendaAtendimentoList_filter_data_registro')); // add the session filter
  315.             }
  316.             if (TSession::getValue('AgendaAtendimentoList_filter_registrado_por')) {
  317.                 $criteria->add(TSession::getValue('AgendaAtendimentoList_filter_registrado_por')); // add the session filter
  318.             }
  319.             if (TSession::getValue('AgendaAtendimentoList_filter_data_atendimento')) {
  320.                 $criteria->add(TSession::getValue('AgendaAtendimentoList_filter_data_atendimento')); // add the session filter
  321.             }
  322.             if (TSession::getValue('AgendaAtendimentoList_filter_hora_atendimento')) {
  323.                 $criteria->add(TSession::getValue('AgendaAtendimentoList_filter_hora_atendimento')); // add the session filter
  324.             }
  325.             if (TSession::getValue('AgendaAtendimentoList_filter_id_status')) {
  326.                 $criteria->add(TSession::getValue('AgendaAtendimentoList_filter_id_status')); // add the session filter
  327.             }
  328.             
  329.             // load the objects according to criteria
  330.             $objects $repository->load($criteriaFALSE);
  331.             
  332.             if (is_callable($this->transformCallback))
  333.             {
  334.                 call_user_func($this->transformCallback$objects$param);
  335.             }
  336.             
  337.             $this->datagrid->clear();
  338.             if ($objects)
  339.             {
  340.                 // iterate the collection of active records
  341.                 foreach ($objects as $object)
  342.                 {
  343.                     // add the object inside the datagrid
  344.                     $this->datagrid->addItem($object);
  345.                 }
  346.             }
  347.             
  348.             // reset the criteria for record count
  349.             $criteria->resetProperties();
  350.             $count$repository->count($criteria);
  351.             
  352.             $this->pageNavigation->setCount($count); // count of records
  353.             $this->pageNavigation->setProperties($param); // order, page
  354.             $this->pageNavigation->setLimit($limit); // limit
  355.             
  356.             // close the transaction
  357.             TTransaction::close();
  358.             $this->loaded true;
  359.         }
  360.         catch (Exception $e// in case of exception
  361.         {
  362.             // shows the exception error message
  363.             new TMessage('error'$e->getMessage());
  364.             // undo all pending operations
  365.             TTransaction::rollback();
  366.         }
  367.     }
  368.     
  369.     /**
  370.      * Ask before deletion
  371.      */
  372.     public static function onDelete($param)
  373.     {
  374.         // define the delete action
  375.         $action = new TAction([__CLASS__'Delete']);
  376.         $action->setParameters($param); // pass the key parameter ahead
  377.         
  378.         // shows a dialog to the user
  379.         new TQuestion(TAdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
  380.     }
  381.     
  382.     /**
  383.      * Delete a record
  384.      */
  385.     public static function Delete($param)
  386.     {
  387.         try
  388.         {
  389.             $key=$param['key']; // get the parameter $key
  390.             TTransaction::open('sistema'); // open a transaction with database
  391.             $object = new AgendaAtendimento($keyFALSE); // instantiates the Active Record
  392.             $object->delete(); // deletes the object from the database
  393.             TTransaction::close(); // close the transaction
  394.             
  395.             $pos_action = new TAction([__CLASS__'onReload']);
  396.             new TMessage('info'TAdiantiCoreTranslator::translate('Record deleted'), $pos_action); // success message
  397.         }
  398.         catch (Exception $e// in case of exception
  399.         {
  400.             new TMessage('error'$e->getMessage()); // shows the exception error message
  401.             TTransaction::rollback(); // undo all pending operations
  402.         }
  403.     }
  404.     
  405.     
  406.     /**
  407.      * method show()
  408.      * Shows the page
  409.      */
  410.     public function show()
  411.     {
  412.         // check if the datagrid is already loaded
  413.         if (!$this->loaded AND (!isset($_GET['method']) OR !(in_array($_GET['method'],  array('onReload''onSearch')))) )
  414.         {
  415.             if (func_num_args() > 0)
  416.             {
  417.                 $this->onReloadfunc_get_arg(0) );
  418.             }
  419.             else
  420.             {
  421.                 $this->onReload();
  422.             }
  423.         }
  424.         parent::show();
  425.     }
  426. }
  427. ?>
</your>
NR

Você está pegando a descrição na coluna, mas na função de formatação está comparando com o código:
  1. <?php
  2.  $column_id_status = new TDataGridColumn('{status->descricao}''Status''left'); //status->descricao vai retornar a descrição
  3. $column_id_status->setTransformer(function($value$object$row) { // value = descricao
  4.          $lbl = new TLabel(''); 
  5.          if ($value == '1') { 
  6.              $lbl->setLabel('REGISTRADO'); 
  7.              $lbl->class 'label label-primary'
  8.          } ...
  9. ?>
CM

Bom dia Nataniel.
Obrigado pela ajuda, mas sinceramente não entendi sua resposta.
CM

Inclusive já fiz desta forma também:

  1. <?php
  2. $column_id_status->setTransformer(function($value$object$row) { 
  3.          $lbl = new TLabel(''); 
  4.          if ($value == 'REGISTRADO') { 
  5.              $lbl->setLabel('REGISTRADO'); 
  6.              $lbl->class 'label label-primary'
  7.          }  ...
  8. ?>
CM

Só que não funciona de jeito nenhum.
Já modifiquei a forma em que os dados da coluna são exibidos e nada.
NR

Troque setLabel por setValue:
  1. <?php
  2. //$lbl->setLabel('REGISTRADO'); 
  3. $lbl->setValue('REGISTRADO'); 
  4. ?>

setLabel é uma função herdada de TField com outro propósito
CM

Bom dia Nataniel.
Muito obrigado pela ajuda. Resolvido

O código ficou assim:

  1. <?php
  2. $column_id_status->setTransformer(function($value$object$row) { 
  3.          $lbl = new TLabel(''); 
  4.          if ($value == 'REGISTRADO') { 
  5.              $lbl->setValue('REGISTRADO'); 
  6.              $lbl->class 'label label-primary'
  7.          } 
  8.          if ($value == 'EM ATENDIMENTO') { 
  9.              $lbl->setValue('EM ATENDIMENTO'); 
  10.              $lbl->class 'label label-warning'
  11.          }  
  12.          if ($value == 'CONCLUÍDO') { 
  13.              $lbl->setValue('CONCLUÍDO'); 
  14.              $lbl->class 'label label-success'
  15.          }  
  16.          return $lbl
  17.          });
  18. ?>