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

Curso Dominando o Adianti Framework

O material mais completo de treinamento do Framework.
Curso em vídeo aulas + Livro completo + Códigos fontes do projeto ERPHouse.
Conteúdo Atualizado!


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