key da TDataGrid Olá! Estou desenvolvendo uma aplicação onde uma listagem de dados (contas) leva a outra listagem de dados (movimentos da conta de uma conta especifica). Logo, na primeira listagem tenho na URL &key=id_do_objeto_conta; Na segunda listagem, leio o ID para carregar somente os movimentos da conta selecionada; Mas, na segunda listagem, cada linha tem o parâmetro &key=id_do_objeto_movime...
MD
key da TDataGrid  
Fechado
Olá!

Estou desenvolvendo uma aplicação onde uma listagem de dados (contas) leva a outra listagem de dados (movimentos da conta de uma conta especifica).

Logo, na primeira listagem tenho na URL &key=id_do_objeto_conta;

Na segunda listagem, leio o ID para carregar somente os movimentos da conta selecionada;

Mas, na segunda listagem, cada linha tem o parâmetro &key=id_do_objeto_movimento, logo, quando peço para remover um item, ele chama a listagem novamente, mas, sem o ID da conta, e sim com o ID do movimento.

Para resolver esse detalhe, copiei a classe TDataGrid para a área que tenho em minha aplicação onde eventualmente alguma classe do framework é "sobrescrita" (para tal modifiquei a classe TAdiantiLoader para buscar primeiro as classes em app/lib/adianti_mod dessa forma não modifico nenhum arquivo do framework e sei quais classes devem ser verificadas em um update do framework) e então criei um metodo chamado setKey onde posso setar um novo key para a TDataGrid.

Abaixo segue a classe espero que possa ajudar:

 
  1. <?php
  2. /**
  3. * DataGrid Widget: Allows to create datagrids with rows, columns and actions
  4. *
  5. * @version 1.0
  6. * @package widget_web
  7. * @subpackage datagrid
  8. * @author Pablo Dall'Oglio
  9. * @author Marco A. Driemeyer <marco@plenatech.com.br>
  10. * @copyright Copyright (c) 2006-2013 Adianti Solutions Ltd. (http://www.adianti.com.br)
  11. * @license http://www.adianti.com.br/framework-license
  12. */
  13. class TDataGrid extends TTable
  14. {
  15. private $columns;
  16. private $actions;
  17. private $rowcount;
  18. private $tbody;
  19. private $height;
  20. private $scrollable;
  21. private $modelCreated;
  22. private $pageNavigation;
  23. private $defaultClick;
  24. /**
  25. * Essa Classe foi modificada para que se possa setar o nome do field passado
  26. * para a datagrid, por padrão seu nome é key, mas, eventualmente como na
  27. * classe ContaControleMovimentoList é necessário mudar o nome da Key
  28. */
  29. private $key; // variavel para receber o nome da key
  30. // o mesmo bloco de comentario acima será repetido e cada mudança realizada na classe para poder melhor verificar as alterações
  31. /**
  32. * Class Constructor
  33. */
  34. public function __construct()
  35. {
  36. parent::__construct();
  37. $this->modelCreated = FALSE;
  38. $this->defaultClick = TRUE;
  39. $this->{'class'} = 'tdatagrid_table';
  40. $this-> id = 'tdatagrid_table';
  41. /**
  42. * Essa Classe foi modificada para que se possa setar o nome do field passado
  43. * para a datagrid, por padrão seu nome é key, mas, eventualmente como na
  44. * classe ContaControleMovimentoList é necessário mudar o nome da Key
  45. */
  46. $this->key = 'key'; // no contruct seta o nome default de key
  47. }
  48. /**
  49. * Essa Classe foi modificada para que se possa setar o nome do field passado
  50. * para a datagrid, por padrão seu nome é key, mas, eventualmente como na
  51. * classe ContaControleMovimentoList é necessário mudar o nome da Key
  52. */
  53. /**
  54. * Metodo que seta o nome da Key da datagrid
  55. */
  56. public function setKey($key){
  57. $this->key = $key;
  58. }
  59. /**
  60. * Make the datagrid scrollable
  61. */
  62. public function makeScrollable()
  63. {
  64. $this->scrollable = TRUE;
  65. }
  66. /**
  67. * disable the default click action
  68. */
  69. public function disableDefaultClick()
  70. {
  71. $this->defaultClick = FALSE;
  72. }
  73. /**
  74. * Define the Height
  75. * @param $height An integer containing the height
  76. */
  77. function setHeight($height)
  78. {
  79. $this->height = $height;
  80. }
  81. /**
  82. * Add a Column to the DataGrid
  83. * @param $object A TDataGridColumn object
  84. */
  85. public function addColumn(TDataGridColumn $object)
  86. {
  87. if ($this->modelCreated)
  88. {
  89. throw new Exception(TAdiantiCoreTranslator::translate('You must call ^1 before ^2', __METHOD__ , 'createModel') );
  90. }
  91. else
  92. {
  93. $this->columns[] = $object;
  94. }
  95. }
  96. /**
  97. * Add an Action to the DataGrid
  98. * @param $object A TDataGridAction object
  99. */
  100. public function addAction(TDataGridAction $object)
  101. {
  102. if ($this->modelCreated)
  103. {
  104. throw new Exception(TAdiantiCoreTranslator::translate('You must call ^1 before ^2', __METHOD__ , 'createModel') );
  105. }
  106. else
  107. {
  108. $this->actions[] = $object;
  109. }
  110. }
  111. /**
  112. * Clear the DataGrid contents
  113. */
  114. function clear()
  115. {
  116. if ($this->modelCreated)
  117. {
  118. // copy the headers
  119. $copy = $this->children[0];
  120. // reset the row array
  121. $this->children = array();
  122. // add the header again
  123. $this->children[] = $copy;
  124. // add an empty body
  125. $this->tbody = new TElement('tbody');
  126. $this->tbody->{'class'} = 'tdatagrid_body';
  127. if ($this->scrollable)
  128. {
  129. $this->tbody->{'style'} = "height: {$this->height}px; display: block; overflow-y:scroll; overflow-x:hidden;";
  130. }
  131. parent::add($this->tbody);
  132. // restart the row count
  133. $this->rowcount = 0;
  134. }
  135. }
  136. /**
  137. * Creates the DataGrid Structure
  138. */
  139. public function createModel()
  140. {
  141. if (!$this->columns)
  142. {
  143. return;
  144. }
  145. $thead = new TElement('thead');
  146. $thead->{'class'} = 'tdatagrid_head';
  147. parent::add($thead);
  148. $row = new TElement('tr');
  149. if ($this->scrollable)
  150. {
  151. $row->{'style'} = 'display:block';
  152. }
  153. $thead->add($row);
  154. // add some cells for the actions
  155. if ($this->actions)
  156. {
  157. foreach ($this->actions as $action)
  158. {
  159. $cell = new TElement('td');
  160. $row->add($cell);
  161. $cell->add('&nbsp;');
  162. $cell->{'class'} = 'tdatagrid_col';
  163. $cell-> width = '15px';
  164. }
  165. }
  166. // add some cells for the data
  167. if ($this->columns)
  168. {
  169. // iterate the DataGrid columns
  170. foreach ($this->columns as $column)
  171. {
  172. // get the column properties
  173. $name = $column->getName();
  174. $label = '&nbsp;'.$column->getLabel().'&nbsp;';
  175. $align = $column->getAlign();
  176. $width = $column->getWidth();
  177. if (isset($_GET['order']))
  178. {
  179. if ($_GET['order'] == $name)
  180. {
  181. $label .= '<img src="lib/adianti/images/ico_down.png">';
  182. }
  183. }
  184. // add a cell with the columns label
  185. $cell = new TElement('td');
  186. $row->add($cell);
  187. $cell->add($label);
  188. $cell->{'class'} = 'tdatagrid_col';
  189. $cell-> align = $align;
  190. if ($width)
  191. {
  192. //$cell-> width = $width.'px';
  193. $cell-> width = ($width+7).'px';
  194. }
  195. // verify if the column has an attached action
  196. if ($column->getAction())
  197. {
  198. $url = $column->getAction();
  199. $cell-> onmouseover = "this.className='tdatagrid_col_over';";
  200. $cell-> onmouseout = "this.className='tdatagrid_col'";
  201. $cell-> href = $url;
  202. $cell-> generator = 'adianti';
  203. }
  204. }
  205. }
  206. // add one row to the DataGrid
  207. $this->tbody = new TElement('tbody');
  208. $this->tbody->{'class'} = 'tdatagrid_body';
  209. if ($this->scrollable)
  210. {
  211. $this->tbody->{'style'} = "height: {$this->height}px; display: block; overflow-y:scroll; overflow-x:hidden;";
  212. }
  213. parent::add($this->tbody);
  214. $this->modelCreated = TRUE;
  215. }
  216. /**
  217. * Add an object to the DataGrid
  218. * @param $object An Active Record Object
  219. */
  220. public function addItem($object)
  221. {
  222. if ($this->modelCreated)
  223. {
  224. // define the background color for that line
  225. $classname = ($this->rowcount % 2) == 0 ? 'tdatagrid_row_even' : 'tdatagrid_row_odd';
  226. $row = new TElement('tr');
  227. $this->tbody->add($row);
  228. $row->{'class'} = $classname;
  229. // verify if the DataGrid has ColumnActions
  230. if ($this->actions)
  231. {
  232. // iterate the actions
  233. foreach ($this->actions as $action)
  234. {
  235. // get the action properties
  236. $field = $action->getField();
  237. $label = $action->getLabel();
  238. $image = $action->getImage();
  239. if (is_null($field))
  240. {
  241. throw new Exception(TAdiantiCoreTranslator::translate('Field for action ^1 not defined', $label) . '.<br>' .
  242. TAdiantiCoreTranslator::translate('Use the ^1 method', 'setField'.'()').'.');
  243. }
  244. // get the object property that will be passed ahead
  245. $key = $object->$field;
  246. /**
  247. * Essa Classe foi modificada para que se possa setar o nome do field passado
  248. * para a datagrid, por padrão seu nome é key, mas, eventualmente como na
  249. * classe ContaControleMovimentoList é necessário mudar o nome da Key
  250. */
  251. //$action->setParameter('key', $key);
  252. $action->setParameter($this->key, $key);
  253. $url = $action->serialize();
  254. // creates a link
  255. $link = new TElement('a');
  256. $link-> href = $url;
  257. $link-> generator = 'adianti';
  258. $first_url = isset($first_url) ? $first_url : $link-> href;
  259. // verify if the link will have an icon or a label
  260. if ($image)
  261. {
  262. // add the image to the link
  263. if (file_exists("lib/adianti/images/$image"))
  264. {
  265. $image=new TImage("lib/adianti/images/$image");
  266. }
  267. else
  268. {
  269. $image=new TImage("app/images/$image");
  270. }
  271. $image-> title = $label;
  272. $link->add($image);
  273. }
  274. else
  275. {
  276. // add the label to the link
  277. $link->add($label);
  278. }
  279. // add the cell to the row
  280. $cell = new TElement('td');
  281. $row->add($cell);
  282. $cell->add($link);
  283. $cell-> width = '16px';
  284. $cell->{'class'} = 'tdatagrid_cell';
  285. }
  286. }
  287. if ($this->columns)
  288. {
  289. // iterate the DataGrid columns
  290. foreach ($this->columns as $column)
  291. {
  292. // get the column properties
  293. $name = $column->getName();
  294. $align = $column->getAlign();
  295. $width = $column->getWidth();
  296. $function = $column->getTransformer();
  297. $data = is_null($object->$name) ? '' : $object->$name;
  298. // verify if there's a transformer function
  299. if ($function)
  300. {
  301. // apply the transformer functions over the data
  302. $data = call_user_func($function, $data);
  303. }
  304. if ($editaction = $column->getEditAction())
  305. {
  306. $editaction_field = $editaction->getField();
  307. $div = new TElement('div');
  308. $div->{'class'} = 'inlineediting';
  309. $div->{'style'} = 'padding-left:5px;padding-right:5px';
  310. $div->{'action'} = $editaction->serialize();
  311. $div->{'field'} = $name;
  312. $div->{'key'} = $object->{$editaction_field};
  313. $div->add($data);
  314. $cell = new TElement('td');
  315. $row->add($cell);
  316. $cell->add($div);
  317. $cell->{'class'} = 'tdatagrid_cell';
  318. }
  319. else
  320. {
  321. // add the cell to the row
  322. $cell = new TElement('td');
  323. $row->add($cell);
  324. $cell->add($data);
  325. $cell->{'class'} = 'tdatagrid_cell';
  326. $cell-> align = $align;
  327. $cell->{'style'} = 'padding-left:5px;padding-right:5px';
  328. if (isset($first_url) AND $this->defaultClick)
  329. {
  330. $cell-> href = $first_url;
  331. $cell-> generator = 'adianti';
  332. }
  333. }
  334. if ($width)
  335. {
  336. $cell-> width = $width.'px';
  337. }
  338. }
  339. }
  340. // when the mouse is over the datagrid row
  341. $row-> onmouseover = "className='tdatagrid_row_sel'; style.cursor='pointer'";
  342. $row-> onmouseout = "className='{$classname}';";
  343. // increments the row counter
  344. $this->rowcount ++;
  345. }
  346. else
  347. {
  348. throw new Exception(TAdiantiCoreTranslator::translate('You must call ^1 before ^2', 'createModel', __METHOD__ ) );
  349. }
  350. }
  351. /**
  352. * Returns the DataGrid's width
  353. * @return An integer containing the DataGrid's width
  354. */
  355. public function getWidth()
  356. {
  357. $width=0;
  358. if ($this->actions)
  359. {
  360. // iterate the DataGrid Actions
  361. foreach ($this->actions as $action)
  362. {
  363. $width += 22;
  364. }
  365. }
  366. if ($this->columns)
  367. {
  368. // iterate the DataGrid Columns
  369. foreach ($this->columns as $column)
  370. {
  371. $width += $column->getWidth();
  372. }
  373. }
  374. return $width;
  375. }
  376. /**
  377. * Shows the DataGrid
  378. */
  379. function show()
  380. {
  381. TPage::include_css('lib/adianti/include/tdatagrid/tdatagrid.css');
  382. // shows the datagrid
  383. parent::show();
  384. $params = $_REQUEST;
  385. unset($params['class']);
  386. unset($params['method']);
  387. // to keep browsing parameters (order, page, first_page, ...)
  388. $urlparams='&'.http_build_query($params);
  389. // inline editing treatment
  390. $script = new TElement('script');
  391. $script->add('$(function() {
  392. $(".inlineediting").editInPlace({
  393. callback: function(unused, enteredText)
  394. {
  395. __adianti_load_page($(this).attr("action")+"'.$urlparams.'&key="+$(this).attr("key")+"&field="+$(this).attr("field")+"&value="+encodeURIComponent(enteredText));
  396. return enteredText;
  397. },
  398. show_buttons: false,
  399. text_size:20,
  400. params:column=name
  401. });
  402. });');
  403. $script->show();
  404. }
  405. /**
  406. * Assign a PageNavigation object
  407. * @param $pageNavigation object
  408. */
  409. function setPageNavigation($pageNavigation)
  410. {
  411. $this->pageNavigation = $pageNavigation;
  412. }
  413. /**
  414. * Return the assigned PageNavigation object
  415. * @return $pageNavigation object
  416. */
  417. function getPageNavigation()
  418. {
  419. return $this->pageNavigation;
  420. }
  421. }
  422. ?>



No construct da classe de movimentos da conta sempre leio o ID da conta movimentada e então posso montar um link assim na listagem "...&method=onDelete&key=id_da_conta&id_movimento=id_do_movimento"

Abaixo exemplo de utilização:

 
  1. <?php
  2. public function __construct()
  3. {
  4. ...
  5. // creates a DataGrid
  6. $this->datagrid = new TDataGrid;
  7. $this->datagrid->setHeight(320);
  8. $this->datagrid->setKey('id_movimento'); // seta uma nova key para a TDataGrid
  9. ...
  10. $action2 = new TDataGridAction(array($this, 'onDelete'));
  11. $action2->setParameter('key', $this->id_conta); // aqui seto o real id da conta
  12. $action2->setLabel('Delete');
  13. $action2->setImage('ico_delete.png');
  14. $action2->setField('id');
  15. // add the actions to the datagrid
  16. $this->datagrid->addAction($action2);
  17. }
  18. ?>


Espero ter ajudado.

Um forte abraço!

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 (1)


AS

opa Marco Driemeyer, deixa eu ver se entendi vocẽ tem a conta, e quando clica na conta quer mostrar os movimentos referentes a quela conta.

se for isso é facil, fassa um listagem usando a TPage mesmo, lista os dados, depois envia a key para uma ContasMovimento que é uma StandartGrid, se seu banco tiver feito redondinho da certo, fiz isso com um modulo de vendas, para adicionar itens a venda, a ideia é a mesma, precisando tamo no skype

ale-php