Carregar dados de um Datagrid Boa tarde a todos, Preciso carregar os dados de um datagrid de uma tela mestre detalhe. O que acontece é que se eu fizer: ...
WS
Carregar dados de um Datagrid  
Boa tarde a todos,

Preciso carregar os dados de um datagrid de uma tela mestre detalhe. O que acontece é que se eu fizer:

 
  1. <?php
  2. $data = $this->datagrid->getItems();
  3. // var_dump($data);
  4. if($data)
  5. {
  6. foreach ($data as $registro)
  7. {
  8. $teste = 'teste: ' . $registro->id;
  9. echo $teste;
  10. }
  11. }
  12. ?>


não consigo pegar dados. Lei as postagens antigas mas nenhuma resolveu.

Não vou colocar meu codigo aqui porque vai ocupar muito espaço. Vou colar um codigo do tutor com o método save alterado para entendimento apenas. Se conseguir fazer o getItems funcionar eu sigo tranquilo. Segue o código:

 
  1. <?php
  2. /**
  3. class SaleForm extends TWindow
  4. {
  5. protected $form; // form
  6. /**
  7. * Class constructor
  8. * Creates the page and the registration form
  9. */
  10. function __construct()
  11. {
  12. parent::__construct();
  13. parent::setSize(0.8, null);
  14. parent::removePadding();
  15. parent::removeTitleBar();
  16. parent::disableEscape();
  17. // creates the form
  18. $this->form = new BootstrapFormBuilder('form_Sale');
  19. $this->form->setFormTitle('Sale');
  20. $this->form->setProperty('style', 'margin:0;border:0');
  21. $this->form->setClientValidation(true);
  22. // master fields
  23. $id = new TEntry('id');
  24. $date = new TDate('date');
  25. $customer_id = new TDBUniqueSearch('customer_id', 'samples', 'Customer', 'id', 'name');
  26. $obs = new TText('obs');
  27. $button = new TActionLink('', new TAction(['CustomerFormWindow', 'onEdit']), 'green', null, null, 'fa:plus-circle');
  28. $button->class = 'btn btn-default inline-button';
  29. $button->title = _t('New');
  30. $customer_id->after($button);
  31. // detail fields
  32. $product_detail_unqid = new THidden('product_detail_uniqid');
  33. $product_detail_id = new THidden('product_detail_id');
  34. $product_detail_product_id = new TDBUniqueSearch('product_detail_product_id', 'samples', 'Product', 'id', 'description');
  35. $product_detail_price = new TEntry('product_detail_price');
  36. $product_detail_amount = new TEntry('product_detail_amount');
  37. $product_detail_discount = new TEntry('product_detail_discount');
  38. $product_detail_total = new TEntry('product_detail_total');
  39. // adjust field properties
  40. $id->setEditable(false);
  41. //$customer_id->setSize('100%');
  42. $customer_id->setSize('calc(100% - 30px)');
  43. $customer_id->setMinLength(1);
  44. $date->setSize('100%');
  45. $obs->setSize('100%', 80);
  46. $product_detail_product_id->setSize('100%');
  47. $product_detail_product_id->setMinLength(1);
  48. $product_detail_price->setSize('100%');
  49. $product_detail_amount->setSize('100%');
  50. $product_detail_discount->setSize('100%');
  51. // add validations
  52. $date->addValidation('Date', new TRequiredValidator);
  53. $customer_id->addValidation('Customer', new TRequiredValidator);
  54. // change action
  55. $product_detail_product_id->setChangeAction(new TAction([$this,'onProductChange']));
  56. // add master form fields
  57. $this->form->addFields( [new TLabel('ID')], [$id],
  58. [new TLabel('Date (*)', '#FF0000')], [$date] );
  59. $this->form->addFields( [new TLabel('Customer (*)', '#FF0000')], [$customer_id ] );
  60. $this->form->addFields( [new TLabel('Obs')], [$obs] );
  61. $this->form->addContent( ['<h4>Details</h4><hr>'] );
  62. $this->form->addFields( [ $product_detail_unqid], [$product_detail_id] );
  63. $this->form->addFields( [ new TLabel('Product (*)', '#FF0000') ], [$product_detail_product_id],
  64. [ new TLabel('Amount(*)', '#FF0000') ], [$product_detail_amount] );
  65. $this->form->addFields( [ new TLabel('Price (*)', '#FF0000') ], [$product_detail_price],
  66. [ new TLabel('Discount')], [$product_detail_discount] );
  67. $add_product = TButton::create('add_product', [$this, 'onProductAdd'], 'Register', 'fa:plus-circle green');
  68. $add_product->getAction()->setParameter('static','1');
  69. $this->form->addFields( [], [$add_product] );
  70. $this->product_list = new BootstrapDatagridWrapper(new TDataGrid);
  71. $this->product_list->setHeight(150);
  72. $this->product_list->makeScrollable();
  73. $this->product_list->setId('products_list');
  74. $this->product_list->generateHiddenFields();
  75. $this->product_list->style = "min-width: 700px; width:100%;margin-bottom: 10px";
  76. $col_uniq = new TDataGridColumn( 'uniqid', 'Uniqid', 'center', '10%');
  77. $col_id = new TDataGridColumn( 'id', 'ID', 'center', '10%');
  78. $col_pid = new TDataGridColumn( 'product_id', 'ProdID', 'center', '10%');
  79. $col_descr = new TDataGridColumn( 'product_id', 'Product', 'left', '30%');
  80. $col_amount = new TDataGridColumn( 'amount', 'Amount', 'left', '10%');
  81. $col_price = new TDataGridColumn( 'sale_price', 'Price', 'right', '15%');
  82. $col_disc = new TDataGridColumn( 'discount', 'Discount', 'right', '15%');
  83. $col_subt = new TDataGridColumn( '={amount} * ( {sale_price} - {discount} )', 'Subtotal', 'right', '20%');
  84. $this->product_list->addColumn( $col_uniq );
  85. $this->product_list->addColumn( $col_id );
  86. $this->product_list->addColumn( $col_pid );
  87. $this->product_list->addColumn( $col_descr );
  88. $this->product_list->addColumn( $col_amount );
  89. $this->product_list->addColumn( $col_price );
  90. $this->product_list->addColumn( $col_disc );
  91. $this->product_list->addColumn( $col_subt );
  92. $col_descr->setTransformer(function($value) {
  93. return Product::findInTransaction('samples', $value)->description;
  94. });
  95. $col_subt->enableTotal('sum', 'R$', 2, ',', '.');
  96. $col_id->setVisibility(false);
  97. $col_uniq->setVisibility(false);
  98. // creates two datagrid actions
  99. $action1 = new TDataGridAction([$this, 'onEditItemProduto'] );
  100. $action1->setFields( ['uniqid', '*'] );
  101. $action2 = new TDataGridAction([$this, 'onDeleteItem']);
  102. $action2->setField('uniqid');
  103. // add the actions to the datagrid
  104. $this->product_list->addAction($action1, _t('Edit'), 'far:edit blue');
  105. $this->product_list->addAction($action2, _t('Delete'), 'far:trash-alt red');
  106. $this->product_list->createModel();
  107. $panel = new TPanelGroup;
  108. $panel->add($this->product_list);
  109. $panel->getBody()->style = 'overflow-x:auto';
  110. $this->form->addContent( [$panel] );
  111. $format_value = function($value) {
  112. if (is_numeric($value)) {
  113. return 'R$ '.number_format($value, 2, ',', '.');
  114. }
  115. return $value;
  116. };
  117. $col_price->setTransformer( $format_value );
  118. $col_disc->setTransformer( $format_value );
  119. $col_subt->setTransformer( $format_value );
  120. $this->form->addHeaderActionLink( _t('Close'), new TAction([__CLASS__, 'onClose'], ['static'=>'1']), 'fa:times red');
  121. $this->form->addAction( 'Save', new TAction([$this, 'onSave'], ['static'=>'1']), 'fa:save green');
  122. $this->form->addAction( 'Clear', new TAction([$this, 'onClear']), 'fa:eraser red');
  123. // create the page container
  124. $container = new TVBox;
  125. $container->style = 'width: 100%';
  126. //$container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  127. $container->add($this->form);
  128. parent::add($container);
  129. }
  130. /**
  131. * Pre load some data
  132. */
  133. public function onLoad($param)
  134. {
  135. $data = new stdClass;
  136. $data->customer_id = $param['customer_id'];
  137. $this->form->setData($data);
  138. }
  139. /**
  140. * On product change
  141. */
  142. public static function onProductChange( $params )
  143. {
  144. if( !empty($params['product_detail_product_id']) )
  145. {
  146. try
  147. {
  148. TTransaction::open('samples');
  149. $product = new Product($params['product_detail_product_id']);
  150. TForm::sendData('form_Sale', (object) ['product_detail_price' => $product->sale_price ]);
  151. TTransaction::close();
  152. }
  153. catch (Exception $e)
  154. {
  155. new TMessage('error', $e->getMessage());
  156. TTransaction::rollback();
  157. }
  158. }
  159. }
  160. /**
  161. * Clear form
  162. * @param $param URL parameters
  163. */
  164. function onClear($param)
  165. {
  166. $this->form->clear();
  167. }
  168. /**
  169. * Add a product into item list
  170. * @param $param URL parameters
  171. */
  172. public function onProductAdd( $param )
  173. {
  174. try
  175. {
  176. $this->form->validate();
  177. $data = $this->form->getData();
  178. if( (! $data->product_detail_product_id) || (! $data->product_detail_amount) || (! $data->product_detail_price) )
  179. {
  180. throw new Exception('The fields Product, Amount and Price are required');
  181. }
  182. $uniqid = !empty($data->product_detail_uniqid) ? $data->product_detail_uniqid : uniqid();
  183. $grid_data = ['uniqid' => $uniqid,
  184. 'id' => $data->product_detail_id,
  185. 'product_id' => $data->product_detail_product_id,
  186. 'amount' => $data->product_detail_amount,
  187. 'sale_price' => $data->product_detail_price,
  188. 'discount' => $data->product_detail_discount];
  189. // insert row dynamically
  190. $row = $this->product_list->addItem( (object) $grid_data );
  191. $row->id = $uniqid;
  192. TDataGrid::replaceRowById('products_list', $uniqid, $row);
  193. // clear product form fields after add
  194. $data->product_detail_uniqid = '';
  195. $data->product_detail_id = '';
  196. $data->product_detail_product_id = '';
  197. $data->product_detail_name = '';
  198. $data->product_detail_amount = '';
  199. $data->product_detail_price = '';
  200. $data->product_detail_discount = '';
  201. // send data, do not fire change/exit events
  202. TForm::sendData( 'form_Sale', $data, false, false );
  203. }
  204. catch (Exception $e)
  205. {
  206. $this->form->setData( $this->form->getData());
  207. new TMessage('error', $e->getMessage());
  208. }
  209. }
  210. /**
  211. * Edit a product from item list
  212. * @param $param URL parameters
  213. */
  214. public static function onEditItemProduto( $param )
  215. {
  216. $data = new stdClass;
  217. $data->product_detail_uniqid = $param['uniqid'];
  218. $data->product_detail_id = $param['id'];
  219. $data->product_detail_product_id = $param['product_id'];
  220. $data->product_detail_amount = $param['amount'];
  221. $data->product_detail_price = $param['sale_price'];
  222. $data->product_detail_discount = $param['discount'];
  223. // send data, do not fire change/exit events
  224. TForm::sendData( 'form_Sale', $data, false, false );
  225. }
  226. /**
  227. * Delete a product from item list
  228. * @param $param URL parameters
  229. */
  230. public static function onDeleteItem( $param )
  231. {
  232. $data = new stdClass;
  233. $data->product_detail_uniqid = '';
  234. $data->product_detail_id = '';
  235. $data->product_detail_product_id = '';
  236. $data->product_detail_amount = '';
  237. $data->product_detail_price = '';
  238. $data->product_detail_discount = '';
  239. // send data, do not fire change/exit events
  240. TForm::sendData( 'form_Sale', $data, false, false );
  241. // remove row
  242. TDataGrid::removeRowById('products_list', $param['uniqid']);
  243. }
  244. /**
  245. * Edit Sale
  246. */
  247. public function onEdit($param)
  248. {
  249. try
  250. {
  251. TTransaction::open('samples');
  252. if (isset($param['key']))
  253. {
  254. $key = $param['key'];
  255. $object = new Sale($key);
  256. $sale_items = SaleItem::where('sale_id', '=', $object->id)->load();
  257. foreach( $sale_items as $item )
  258. {
  259. $item->uniqid = uniqid();
  260. $row = $this->product_list->addItem( $item );
  261. $row->id = $item->uniqid;
  262. }
  263. $this->form->setData($object);
  264. TTransaction::close();
  265. }
  266. else
  267. {
  268. $this->form->clear();
  269. }
  270. }
  271. catch (Exception $e)
  272. {
  273. new TMessage('error', $e->getMessage());
  274. TTransaction::rollback();
  275. }
  276. }
  277. /**
  278. * Save the sale and the sale items
  279. */
  280. public function onSave($param)
  281. {
  282. $data = $this->datagrid->getItems();
  283. var_dump($data);
  284. if($data)
  285. {
  286. foreach ($data as $registro)
  287. {
  288. $teste = 'teste: ' . $registro->id;
  289. echo $teste;
  290. }
  291. }
  292. }
  293. /**
  294. * Closes window
  295. */
  296. public static function onClose()
  297. {
  298. parent::closeWindow();
  299. }
  300. }
  301. ?>


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


NR

A solução está nesse mesmo exemplo que você passou. Veja a função onSave original do tutor:
 
  1. <?php
  2. if( !empty($param['products_list_product_id'] ))
  3. {
  4. foreach( $param['products_list_product_id'] as $key => $item_id )
  5. {
  6. $item = new SaleItem;
  7. $item->product_id = $item_id;
  8. $item->sale_price = (float) $param['products_list_sale_price'][$key];
  9. $item->amount = (float) $param['products_list_amount'][$key];
  10. $item->discount = (float) $param['products_list_discount'][$key];
  11. ....
  12. ?>

Ou seja, você vai pegar os dados da grid via $param(post), pois a grid está sendo alimentada estaticamente e assim na onSave ela vai estar vazia.
NR

Não recebi o email de confirmação anterior...
WS

Oi Nataniel Rabaioli,

só agora vou conseguir dar andamento no código.
Vou testar e posto oresultado.

muito obrigado pela ajuda!