Salvar a soma dos itens dinâmico na capa do pedido e bootstrap Pessoal, estou precisando salvar a soma dos ítens (campo $st) na capa do pedido mas não estou conseguindo. Outra coisa que não entendo porque sendo um form bootstrap se eu aumento o tamanho do campo e quando redimensiono ele não diminui como acontece com a página inteira. ...
GG
Salvar a soma dos itens dinâmico na capa do pedido e bootstrap  
Pessoal,
estou precisando salvar a soma dos ítens (campo $st) na capa do pedido mas não estou conseguindo. Outra coisa que não entendo porque sendo um form bootstrap se eu aumento o tamanho do campo e quando redimensiono ele não diminui como acontece com a página inteira.
 
  1. <?php
  2. /**
  3. * Pedido_compraForm Master/Detail
  4. * @author <your name here>
  5. */
  6. class Pedido_compraForm extends TPage
  7. {
  8. protected $form; // form
  9. protected $formFields;
  10. protected $detail_list;
  11. /**
  12. * Page constructor
  13. */
  14. public function __construct()
  15. {
  16. parent::__construct();
  17. // creates the form
  18. $this->form = new TForm('form_Pedido_compra');
  19. $this->form->class = 'tform'; // CSS class
  20. $this->form->style = 'max-width:2500px'; // style
  21. $vbox = new TVBox;
  22. $vbox->style = 'width: 30%';
  23. parent::include_css('app/resources/custom-frame.css');
  24. $table_master = new TTable;
  25. $table_master->width = '100%';
  26. $table_master->addRowSet( new TLabel('Pedido de compra'), '', '')->class = 'tformtitle';
  27. // add a table inside form
  28. $table_general = new TTable;
  29. $table_detail = new TTable;
  30. $table_general-> width = '100%';
  31. $table_detail-> width = '100%';
  32. $frame_general = new TFrame;
  33. $frame_general->setLegend('Capa');
  34. $frame_general->style = 'background:whiteSmoke';
  35. $frame_general->add($table_general);
  36. $table_master->addRow()->addCell( $frame_general )->colspan=2;
  37. $row = $table_master->addRow();
  38. $row->addCell( $table_detail );
  39. $this->form->add($table_master);
  40. // master fields
  41. $id = new TEntry('id');
  42. $fornecedor_id = new ">TDBSeekButton('fornecedor_id', 'erpweb',$this->form->getName(), 'Fornecedor','pessoa->nome', 'fornecedor_id', 'fornecedor_nome');
  43. $condicao_pagamento_id = new TDBCombo('condicao_pagamento_id', 'erpweb', 'Condicao_pagamento', 'id', 'descricao');
  44. $fornecedor_nome = new TEntry('fornecedor_nome');
  45. $data_compra = new TDate('data_compra');
  46. $observacao = new TText('observacao');
  47. $estoque_interno = new TRadioGroup('estoque_interno');
  48. $situacao = new TRadioGroup('situacao');
  49. $valor_total = new TEntry('valor_total');
  50. $valor_desconto = new TEntry('valor_desconto');
  51. $valor_tota_liquido = new TEntry('valor_tota_liquido');
  52. $items = array();
  53. $items['1'] ='Sim';
  54. $items['0'] ='Nao';
  55. $estoque_interno->addItems($items);
  56. $situacao->setLayout('horizontal');
  57. $items = array();
  58. $items['0'] ='Em aberto';
  59. $items['1'] ='Em andamento';
  60. $items['2'] ='Atendido';
  61. $items['3'] ='Cancelado';
  62. $situacao->addItems($items);
  63. if (!empty($id))
  64. {
  65. $id->setEditable(FALSE);
  66. }
  67. $fornecedor_id->setSize(50);
  68. $fornecedor_nome->setEditable(false);
  69. $data_compra->setValue(date("Y-m-d"));
  70. $valor_total->setEditable(FALSE);
  71. $valor_tota_liquido->setEditable(FALSE);
  72. $valor_total->setNumericMask(2, ',','.',true);
  73. $valor_tota_liquido->setNumericMask(2, ',','.',true);
  74. $valor_desconto->setNumericMask(2, ',','.',true);
  75. // detail fields
  76. $detail_id = new THidden('detail_id');
  77. $detail_qtde = new TEntry('detail_qtde');
  78. $detail_qtde_bonificada = new TEntry('detail_qtde_bonificada');
  79. $detail_valor_item = new TEntry('detail_valor_item');
  80. $detail_valor_total_item = new TEntry('detail_valor_total_item');
  81. $detail_produto_id = new ">TDBSeekButton('detail_produto_id', 'erpweb',$this->form->getName(), 'Produto','descricao', 'detail_produto_id', 'detail_produto_nome');
  82. $detail_produto_nome = new TEntry('detail_produto_nome');
  83. $detail_qtde->setNumericMask(3, ',','.',true);
  84. $detail_qtde_bonificada->setNumericMask(3, ',','.',true);
  85. $detail_valor_item->setNumericMask(2, ',','.',true);
  86. $detail_valor_total_item->setNumericMask(2, ',','.',true);
  87. $detail_produto_id->setSize(50);
  88. $detail_valor_total_item->setEditable(FALSE);
  89. $detail_produto_id->setExitAction(new TAction(array($this,'onProductChange')));
  90. $detail_qtde_bonificada->setExitAction(new TAction(array($this,'onQtdebonificadaChange')));
  91. $detail_produto_nome->setEditable(false);
  92. /** samples
  93. $this->form->addQuickFields('Date', array($date1, new TLabel('to'), $date2)); // side by side fields
  94. $fieldX->addValidation( 'Field X', new TRequiredValidator ); // add validation
  95. $fieldX->setSize( 100, 40 ); // set size
  96. **/
  97. // master
  98. $table_general->addRowSet( new TLabel('Id'), $id );
  99. $table_general->addRowSet( new TLabel('Data de Compra'), $data_compra );
  100. $table_general->addRowSet( $label_fornecedor = new TLabel('Fornecedor (*)'), array( $fornecedor_id, $fornecedor_nome ) );
  101. $table_general->addRowSet( new TLabel('Condicao de Pagamento (*)'), $condicao_pagamento_id );
  102. $table_general->addRowSet( new TLabel('Estoque Interno'), $estoque_interno );
  103. $table_general->addRowSet( new TLabel('Situação'), $situacao );
  104. $table_general->addRowSet( new TLabel('Valor Total'), $valor_total );
  105. $table_general->addRowSet( new TLabel('Valor Desconto'), $valor_desconto );
  106. $table_general->addRowSet( new TLabel('Valor Total Liquido'), $valor_tota_liquido );
  107. $table_general->addRowSet( new TLabel('Observação'), $observacao );
  108. // detail
  109. $frame_details = new TFrame();
  110. $frame_details->setLegend('Ítens');
  111. $row = $table_detail->addRow();
  112. $row->addCell($frame_details);
  113. $vbox->add( $frame_general );
  114. $vbox->add( $frame_details );
  115. $btn_save_detail = new TButton('btn_save_detail');
  116. $btn_save_detail->setAction(new TAction(array($this, 'onSaveDetail')), 'Adicionar');
  117. $btn_save_detail->setImage('fa:save');
  118. $table_details = new TTable;
  119. $frame_details->add($table_details);
  120. $table_details->addRowSet( '', $detail_id );
  121. $table_details->addRowSet( new TLabel('Produto (*)'), array( $detail_produto_id, $detail_produto_nome ) );
  122. $table_details->addRowSet( new TLabel('Qtde'), $detail_qtde );
  123. $table_details->addRowSet( new TLabel('Qtde Bonificada'), $detail_qtde_bonificada );
  124. $table_details->addRowSet( new TLabel('Valor Item'), $detail_valor_item );
  125. $table_details->addRowSet( new TLabel('Valor Total Item'), $detail_valor_total_item );
  126. $table_details->addRowSet( $btn_save_detail );
  127. $this->detail_list = new TQuickGrid;
  128. $this->detail_list->setHeight( 50 );
  129. $this->detail_list->makeScrollable();
  130. $this->detail_list->disableDefaultClick();
  131. $this->detail_list->addQuickColumn('', 'edit', 'left', 40);
  132. $this->detail_list->addQuickColumn('', 'delete', 'left', 40);
  133. // items
  134. $this->detail_list->style = "margin-bottom: 50px";
  135. $this->detail_list->addQuickColumn('Id', 'produto_id', 'center', 50);
  136. $this->detail_list->addQuickColumn('Produto', 'produto_nome', 'left', 200);
  137. $qt = $this->detail_list->addQuickColumn('Qtde', 'qtde', 'left', 200);
  138. $qb = $this->detail_list->addQuickColumn('Qtde Bonificada', 'qtde_bonificada', 'left', 200);
  139. $pr = $this->detail_list->addQuickColumn('Valor Item', 'valor_item', 'left', 200);
  140. $st = $this->detail_list->addQuickColumn('Valor Total Item', 'valor_total_item', 'left', 200);
  141. $this->detail_list->createModel();
  142. $vbox->add( $this->detail_list );
  143. $format_value = function($value) {
  144. if (is_numeric($value)) {
  145. return 'R$ '.number_format($value, 2, ',', '.');
  146. }
  147. return $value;
  148. };
  149. $format_qtde = function($value) {
  150. if (is_numeric($value)) {
  151. return number_format($value, 3, ',', '.');
  152. }
  153. return $value;
  154. };
  155. $pr->setTransformer( $format_value );
  156. $st->setTransformer( $format_value );
  157. $qt->setTransformer( $format_qtde );
  158. $qb->setTransformer( $format_qtde );
  159. $st->setTotalFunction( function($values) {
  160. return array_sum((array) $values);
  161. });
  162. $row = $table_detail->addRow();
  163. $row->addCell($this->detail_list);
  164. // create an action button (save)
  165. $save_button=new TButton('save');
  166. $save_button->setAction(new TAction(array($this, 'onSave')), _t('Save'));
  167. $save_button->setImage('ico_save.png');
  168. // create an new button (edit with no parameters)
  169. $new_button=new TButton('new');
  170. $new_button->setAction(new TAction(array($this, 'onClear')), _t('New'));
  171. $new_button->setImage('ico_new.png');
  172. // define form fields
  173. $this->formFields = array($id,$data_compra,$valor_total,$valor_desconto,$valor_tota_liquido,$observacao,$estoque_interno,$situacao,$fornecedor_id,$fornecedor_nome,$condicao_pagamento_id,$detail_qtde,$detail_qtde_bonificada,$detail_valor_item,$detail_valor_total_item,$detail_produto_id,$detail_produto_nome);
  174. $this->formFields[] = $btn_save_detail;
  175. $this->formFields[] = $save_button;
  176. $this->formFields[] = $new_button;
  177. $this->formFields[] = $detail_id;
  178. $this->form->setFields( $this->formFields );
  179. $table_master->addRowSet( array($save_button, $new_button), '', '')->class = 'tformaction'; // CSS class
  180. // create the page container
  181. $container = new TVBox;
  182. $container->style = 'width: 90%';
  183. // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  184. $container->add($this->form);
  185. parent::add($container);
  186. }
  187. public function onLoad($param)
  188. {
  189. $data = new stdClass;
  190. $data->fornecedor_id = $param['fornecedor_id'];
  191. $data->fornecedor_nome = $param['fornecedor_nome'];
  192. $this->form->setData($data);
  193. }
  194. static function onProductChange( $params )
  195. {
  196. if( isset($params['detail_produto_id']) && $params['detail_produto_id'] )
  197. {
  198. try
  199. {
  200. TTransaction::open('erpweb');
  201. $produto = new Produto($params['detail_produto_id']);
  202. $fill_data = new StdClass;
  203. $fill_data->detail_valor_item = number_format($produto->valor_unitario_venda, 2, ',','.');
  204. TForm::sendData('form_Pedido_compra', $fill_data);
  205. TTransaction::close();
  206. }
  207. catch (Exception $e) // in case of exception
  208. {
  209. new TMessage('error', '<b>Error</b> ' . $e->getMessage());
  210. TTransaction::rollback();
  211. }
  212. }
  213. else
  214. {
  215. $fill_data = new StdClass;
  216. $fill_data->detail_valor_item = null;
  217. $fill_data->detail_produto_nome = null;
  218. TForm::sendData('form_Pedido_compra', $fill_data);
  219. TTransaction::close();
  220. }
  221. }
  222. static function onQtdebonificadaChange( $params )
  223. {
  224. if( isset($params['detail_produto_id']) && $params['detail_produto_id'] )
  225. {
  226. try
  227. {
  228. TTransaction::open('erpweb');
  229. $produto = new Produto($params['detail_produto_id']);
  230. $fill_data = new StdClass;
  231. $fill_data->detail_valor_total_item = number_format((((double) str_replace(',', '.',$params['detail_qtde']) - (double) str_replace(',', '.',$params['detail_qtde_bonificada']) ) * (double) str_replace(',', '.',$params['detail_valor_item'])), 2, ',', '.');
  232. TForm::sendData('form_Pedido_compra', $fill_data);
  233. TTransaction::close();
  234. }
  235. catch (Exception $e) // in case of exception
  236. {
  237. new TMessage('error', '<b>Error</b> ' . $e->getMessage());
  238. TTransaction::rollback();
  239. }
  240. }
  241. else
  242. {
  243. $fill_data = new StdClass;
  244. $fill_data->detail_valor_item = null;
  245. $fill_data->detail_produto_nome = null;
  246. TForm::sendData('form_Pedido_compra', $fill_data);
  247. TTransaction::close();
  248. }
  249. }
  250. /**
  251. * Clear form
  252. * @param $param URL parameters
  253. */
  254. public function onClear($param)
  255. {
  256. $this->form->clear(TRUE);
  257. TSession::setValue(__CLASS__.'_items', array());
  258. $this->onReload( $param );
  259. }
  260. /**
  261. * Save an item from form to session list
  262. * @param $param URL parameters
  263. */
  264. public function onSaveDetail( $param )
  265. {
  266. try
  267. {
  268. TTransaction::open('erpweb');
  269. $data = $this->form->getData();
  270. /** validation sample
  271. if (! $data->fieldX)
  272. throw new Exception('The field fieldX is required');
  273. **/
  274. $items = TSession::getValue(__CLASS__.'_items');
  275. $key = empty($data->detail_id) ? 'X'.mt_rand(1000000000, 1999999999) : $data->detail_id;
  276. $items[ $key ] = array();
  277. $items[ $key ]['id'] = $key;
  278. $items[ $key ]['qtde'] = $data->detail_qtde;
  279. $items[ $key ]['qtde_bonificada'] = $data->detail_qtde_bonificada;
  280. $items[ $key ]['valor_item'] = $data->detail_valor_item;
  281. $items[ $key ]['valor_total_item'] = $data->detail_valor_total_item;
  282. $items[ $key ]['produto_id'] = $data->detail_produto_id;
  283. $items[ $key ]['produto_nome'] = $data->detail_produto_nome;
  284. TSession::setValue(__CLASS__.'_items', $items);
  285. // clear detail form fields
  286. $data->detail_id = '';
  287. $data->detail_qtde = '';
  288. $data->detail_qtde_bonificada = '';
  289. $data->detail_valor_item = '';
  290. $data->detail_valor_total_item = '';
  291. $data->detail_produto_id = '';
  292. $data->detail_produto_nome = '';
  293. TTransaction::close();
  294. $this->form->setData($data);
  295. $this->onReload( $param ); // reload the items
  296. }
  297. catch (Exception $e)
  298. {
  299. $this->form->setData( $this->form->getData());
  300. new TMessage('error', $e->getMessage());
  301. }
  302. }
  303. /**
  304. * Load an item from session list to detail form
  305. * @param $param URL parameters
  306. */
  307. public function onEditDetail( $param )
  308. {
  309. $data = $this->form->getData();
  310. // read session items
  311. $items = TSession::getValue(__CLASS__.'_items');
  312. // get the session item
  313. $item = $items[ $param['item_key'] ];
  314. $data->detail_id = $item['id'];
  315. $data->detail_qtde = $item['qtde'];
  316. $data->detail_qtde_bonificada = $item['qtde_bonificada'];
  317. $data->detail_valor_item = $item['valor_item'];
  318. $data->detail_valor_total_item = $item['valor_total_item'];
  319. $data->detail_produto_id = $item['produto_id'];
  320. $data->detail_produto_nome = $item['produto_nome'];
  321. // fill detail fields
  322. $this->form->setData( $data );
  323. $this->onReload( $param );
  324. }
  325. /**
  326. * Delete an item from session list
  327. * @param $param URL parameters
  328. */
  329. public function onDeleteDetail( $param )
  330. {
  331. $data = $this->form->getData();
  332. // reset items
  333. $data->detail_qtde = '';
  334. $data->detail_qtde_bonificada = '';
  335. $data->detail_valor_item = '';
  336. $data->detail_valor_total_item = '';
  337. $data->detail_produto_id = '';
  338. $data->detail_produto_nome = '';
  339. // clear form data
  340. $this->form->setData( $data );
  341. // read session items
  342. $items = TSession::getValue(__CLASS__.'_items');
  343. // delete the item from session
  344. unset($items[ $param['item_key'] ] );
  345. TSession::setValue(__CLASS__.'_items', $items);
  346. // reload items
  347. $this->onReload( $param );
  348. }
  349. /**
  350. * Load the items list from session
  351. * @param $param URL parameters
  352. */
  353. public function onReload($param)
  354. {
  355. // read session items
  356. $items = TSession::getValue(__CLASS__.'_items');
  357. $this->detail_list->clear(); // clear detail list
  358. $data = $this->form->getData();
  359. if ($items)
  360. {
  361. $cont = 1;
  362. foreach ($items as $list_item_key => $list_item)
  363. {
  364. $item_name = 'prod_' . $cont++;
  365. $item = new StdClass;
  366. // create action buttons
  367. $action_del = new TAction(array($this, 'onDeleteDetail'));
  368. $action_del->setParameter('item_key', $list_item_key);
  369. $action_edi = new TAction(array($this, 'onEditDetail'));
  370. $action_edi->setParameter('item_key', $list_item_key);
  371. $button_del = new TButton('delete_detail'.$cont);
  372. $button_del->class = 'btn btn-default btn-sm';
  373. $button_del->setAction( $action_del, '' );
  374. $button_del->setImage('fa:trash-o red fa-lg');
  375. $button_edi = new TButton('edit_detail'.$cont);
  376. $button_edi->class = 'btn btn-default btn-sm';
  377. $button_edi->setAction( $action_edi, '' );
  378. $button_edi->setImage('fa:edit blue fa-lg');
  379. $item->edit = $button_edi;
  380. $item->delete = $button_del;
  381. $this->formFields[ $item_name.'_edit' ] = $item->edit;
  382. $this->formFields[ $item_name.'_delete' ] = $item->delete;
  383. // items
  384. $item->id = $list_item['id'];
  385. $item->qtde = $list_item['qtde'];
  386. $item->qtde_bonificada = $list_item['qtde_bonificada'];
  387. $item->valor_item = $list_item['valor_item'];
  388. $item->valor_total_item = $list_item['valor_total_item'];
  389. $item->produto_id = $list_item['produto_id'];
  390. $item->produto_nome = $list_item['produto_nome'];
  391. $row = $this->detail_list->addItem( $item );
  392. $row->onmouseover='';
  393. $row->onmouseout='';
  394. }
  395. $this->form->setFields( $this->formFields );
  396. }
  397. $this->loaded = TRUE;
  398. }
  399. /**
  400. * Load Master/Detail data from database to form/session
  401. */
  402. public function onEdit($param)
  403. {
  404. try
  405. {
  406. TTransaction::open('erpweb');
  407. if (isset($param['key']))
  408. {
  409. $key = $param['key'];
  410. $object = new Pedido_compra($key);
  411. $items = Item_pedido_compra::where('pedido_compra_id', '=', $key)->load();
  412. $session_items = array();
  413. foreach( $items as $item )
  414. {
  415. $item_key = $item->id;
  416. $session_items[$item_key] = $item->toArray();
  417. $session_items[$item_key]['id'] = $item->id;
  418. $session_items[$item_key]['qtde'] = $item->qtde;
  419. $session_items[$item_key]['qtde_bonificada'] = $item->qtde_bonificada;
  420. $session_items[$item_key]['valor_item'] = $item->valor_item;
  421. $session_items[$item_key]['valor_total_item'] = $item->valor_total_item;
  422. $session_items[$item_key]['produto_id'] = $item->produto_id;
  423. $session_items[$item_key]['produto_nome'] = $item->produto->descricao;
  424. }
  425. TSession::setValue(__CLASS__.'_items', $session_items);
  426. $this->form->setData($object); // fill the form with the active record data
  427. $this->onReload( $param ); // reload items list
  428. TTransaction::close(); // close transaction
  429. }
  430. else
  431. {
  432. $this->form->clear(TRUE);
  433. TSession::setValue(__CLASS__.'_items', null);
  434. $this->onReload( $param );
  435. }
  436. }
  437. catch (Exception $e) // in case of exception
  438. {
  439. new TMessage('error', $e->getMessage());
  440. TTransaction::rollback();
  441. }
  442. }
  443. /**
  444. * Save the Master/Detail data from form/session to database
  445. */
  446. public function onSave()
  447. {
  448. try
  449. {
  450. // open a transaction with database
  451. TTransaction::open('erpweb');
  452. $data = $this->form->getData();
  453. $master = new Pedido_compra;
  454. $master->fromArray( (array) $data);
  455. $this->form->validate(); // form validation
  456. $master->store(); // save master object
  457. // delete details
  458. $old_items = Item_pedido_compra::where('pedido_compra_id', '=', $master->id)->load();
  459. $keep_items = array();
  460. // get session items
  461. $items = TSession::getValue(__CLASS__.'_items');
  462. if( $items )
  463. {
  464. foreach( $items as $item )
  465. {
  466. if (substr($item['id'],0,1) == 'X' ) // new record
  467. {
  468. $detail = new Item_pedido_compra;
  469. }
  470. else
  471. {
  472. $detail = Item_pedido_compra::find($item['id']);
  473. }
  474. $detail->qtde = $item['qtde'];
  475. $detail->qtde_bonificada = $item['qtde_bonificada'];
  476. $detail->valor_item = $item['valor_item'];
  477. $detail->valor_total_item = $item['valor_total_item'];
  478. $detail->produto_id = $item['produto_id'];
  479. $detail->pedido_compra_id = $master->id;
  480. $detail->store();
  481. $keep_items[] = $detail->id;
  482. }
  483. }
  484. if ($old_items)
  485. {
  486. foreach ($old_items as $old_item)
  487. {
  488. if (!in_array( $old_item->id, $keep_items))
  489. {
  490. $old_item->delete();
  491. }
  492. }
  493. }
  494. TTransaction::close(); // close the transaction
  495. // reload form and session items
  496. $this->onEdit(array('key'=>$master->id));
  497. new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'));
  498. }
  499. catch (Exception $e) // in case of exception
  500. {
  501. new TMessage('error', $e->getMessage());
  502. $this->form->setData( $this->form->getData() ); // keep form data
  503. TTransaction::rollback();
  504. }
  505. }
  506. /**
  507. * Show the page
  508. */
  509. public function show()
  510. {
  511. // check if the datagrid is already loaded
  512. if (!$this->loaded AND (!isset($_GET['method']) OR $_GET['method'] !== 'onReload') )
  513. {
  514. $this->onReload( func_get_arg(0) );
  515. }
  516. parent::show();
  517. }
  518. }
  519. ?>

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


NR

Para que os campos se ajustem conforme a tela você precisa definir o tamanho em %:
 
  1. <?php
  2. $campo->setSize('100%');
  3. ?>

Você quer gravar o total na função onSave? Se for, crie uma variável que faça a soma no foreach dos details, depois passe essa variável para o master e chame o store.
GG

Obrigado Nataniel
GG

Na verdade eu tenho uma função soma dinâmica que soma os itens ($st->setTotalFunction) sempre que adiciona um novo ou exclui, quero pegar este valor e colocar no campo $valor_total para aparecer assim como faço nos campos onexit no código acima
NR

Acho melhor nesse caso então fazer a soma no foreach da função onReload e depois jogar o total para o campo através da função setData