[Dúvida] Salvando dados de uma TPage em um TRecord Bom dia, estou com dificuldades em montar uma função onSave na qual alimente uma tabela específica. No StandardForm não tenho esse problema, pois eu declaro o Database e o TRecord no inicio e assim a função onSave, por default, consegue salvar normalmente. Porém como tive que usar o TPage para construir uma seção de preenchimento com adição de linhas iguais. Segue o código: ...
MS
[Dúvida] Salvando dados de uma TPage em um TRecord  
Bom dia, estou com dificuldades em montar uma função onSave na qual alimente uma tabela específica. No StandardForm não tenho esse problema, pois eu declaro o Database e o TRecord no inicio e assim a função onSave, por default, consegue salvar normalmente. Porém como tive que usar o TPage para construir uma seção de preenchimento com adição de linhas iguais. Segue o código:

 
  1. <?php
  2. class CadastroProdutosPO extends TPage
  3. {
  4. private $form;
  5. /**
  6. * Constructor
  7. */
  8. public function __construct()
  9. {
  10. parent::__construct();
  11. // create form and table container
  12. $this->form = new TForm;
  13. $table = new TTable;
  14. $table->addSection('thead');
  15. // create the form fields
  16. $numpo = new TEntry('numpo');
  17. $apelido = new TEntry('apelido');
  18. //form page 2
  19. $table->addRowSet('',array($d1 = new TLabel('Número PO'),$numpo,$d2 = new TLabel('Apelido'),$apelido, $d3 = new TLabel('')));
  20. $d1 -> setSize(100);
  21. $d2 -> setSize(130);
  22. $d3 -> setSize(230);
  23. $table->addRowSet('',array($d1 = new TLabel(''),$d2 = new TLabel(''), $d3 = new TLabel('')));
  24. $d1 -> setSize(100);
  25. $d2 -> setSize(130);
  26. $d3 -> setSize(230);
  27. $numpo -> setSize(200);
  28. $apelido -> setSize(200);
  29. //$numpo->setEditable( FALSE );
  30. //$apelido->setEditable( FALSE );
  31. $this->form->add($table);
  32. $table->addSection('tbody');
  33. for ($n=1; $n<=5; $n++)
  34. {
  35. $cod = new TDBEntry('cod','sample','Ds','cod');
  36. $cod->setMinLength(1);
  37. $cod->cod ='cod';
  38. $descpo = new TText('descpo');
  39. $quantidade = new TEntry('quantidade');
  40. $custo = new TEntry('custo');
  41. //Regras do form page2
  42. $custo->setNumericMask(3, '.', ',');
  43. // create delete button
  44. $del = new TImage('fa:trash-o red');
  45. $del->onclick = 'ttable_remove_row(this)';
  46. $table->addRowSet('',array($d1 = new TLabel('Cód. Kian'),$cod,$d2 = new TLabel('Description'),$descpo,$d3 = new TLabel('Qtd.'),$quantidade,$d4 = new TLabel('Custo USD'),$custo,$del));
  47. $d1 -> setSize(65);
  48. $d2 -> setSize(75);
  49. $d3 -> setSize(40);
  50. $d4 -> setSize(70);
  51. $cod->setSize(60);
  52. $descpo->setSize(540,30);
  53. $quantidade->setSize(60);
  54. $custo->setSize(60);
  55. }
  56. // create add button
  57. $add = new TButton('clone');
  58. $add->setLabel('Add');
  59. $add->setImage('fa:plus-circle green');
  60. $add->addFunction('ttable_clone_previous_row(this)');
  61. // create save button
  62. $save = TButton::create('save', array($this, 'onSave'), 'Save', 'fa:save green');
  63. $this->form->addField($save);
  64. $cadastropo = TButton::create('cadastropo', array($this, 'displayColumn'), 'Cadastro PO', 'fa:table blue');
  65. $this->form->addField($cadastropo);
  66. $list = TButton::create('list', array('ProdutosPOList', 'onReload'), 'Listagem Produtos', 'fa:table black');
  67. $this->form->addField($list);
  68. //$this->form->addQuickAction('Lista PO', new TAction(array('POList', 'onReload')), 'fa:table black');
  69. $table->addRowSet('',array($d1 = new TLabel(''),$save,$d2 = new TLabel(''),$cadastropo,$d3 = new TLabel(''),$add,$d4 = new TLabel(''),$list));
  70. $d1 -> setSize(0);
  71. $d2 -> setSize(10);
  72. $d3 -> setSize(10);
  73. $d4 -> setSize(10);
  74. $panel = new TPanelGroup('Produtos da PO');
  75. $panel->add($this->form);
  76. // wrap the page content using vertical box
  77. $vbox = new TVBox;
  78. //$vbox->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  79. $vbox->add($panel);
  80. parent::add($vbox);
  81. }
  82. /**
  83. * Redirecionar para uma página (class)
  84. */
  85. public function displayColumn( $numpo )
  86. {
  87. $data = $this->form->getData();
  88. $this->form->setData($data);
  89. TApplication::loadPage('CadastroPO');
  90. }
  91. /**
  92. * method onSave()
  93. * Executed whenever the user clicks at the save button
  94. */
  95. public function onSave()
  96. {
  97. try
  98. {
  99. if (empty('sample'))
  100. {
  101. throw new Exception(AdiantiCoreTranslator::translate('^1 was not defined. You must call ^2 in ^3', AdiantiCoreTranslator::translate('Database'), 'setDatabase()', AdiantiCoreTranslator::translate('Constructor')));
  102. }
  103. if (empty('Cpprod'))
  104. {
  105. throw new Exception(AdiantiCoreTranslator::translate('^1 was not defined. You must call ^2 in ^3', 'Active Record', 'setActiveRecord()', AdiantiCoreTranslator::translate('Constructor')));
  106. }
  107. // open a transaction with database
  108. TTransaction::open('sample');
  109. // get the form data
  110. $object = $this->form->getData('Cpprod');
  111. // validate data
  112. $this->form->validate();
  113. // stores the object
  114. $object->store();
  115. // fill the form with the active record data
  116. $this->form->setData($object);
  117. // close the transaction
  118. TTransaction::close();
  119. // shows the success message
  120. new TMessage('info', AdiantiCoreTranslator::translate('Record saved'));
  121. return $object;
  122. }
  123. catch (Exception $e) // in case of exception
  124. {
  125. // get the form data
  126. $object = $this->form->getData();
  127. // fill the form with the active record data
  128. $this->form->setData($object);
  129. // shows the exception error message
  130. new TMessage('error', $e->getMessage());
  131. // undo all pending operations
  132. TTransaction::rollback();
  133. }
  134. }
  135. /**
  136. * method onReload()
  137. * Load the datagrid with the database objects
  138. */
  139. public function onReload($param = NULL)
  140. {
  141. try
  142. {
  143. // open a transaction with database
  144. TTransaction::open('sample');
  145. // instancia um repositório
  146. $repository = new TRepository('Cpprod');
  147. $limit = isset($this->limit) ? ( $this->limit > 0 ? $this->limit : NULL) : 100;
  148. // creates a criteria
  149. $criteria = isset($this->criteria) ? clone $this->criteria : new TCriteria;
  150. if ($this->order)
  151. {
  152. $criteria->setProperty('order', $this->order);
  153. $criteria->setProperty('direction', $this->direction);
  154. }
  155. $criteria->setProperties($param); // order, offset
  156. $criteria->setProperty('limit', $limit);
  157. // load the objects according to criteria
  158. $objects = $repository->load($criteria, FALSE);
  159. if (is_callable($this->transformCallback))
  160. {
  161. call_user_func($this->transformCallback, $objects);
  162. }
  163. $this->datagrid->clear();
  164. if ($objects)
  165. {
  166. // iterate the collection of active records
  167. foreach ($objects as $object)
  168. {
  169. // add the object inside the datagrid
  170. $this->datagrid->addItem($object);
  171. }
  172. }
  173. // reset the criteria for record count
  174. $criteria->resetProperties();
  175. $count= $repository->count($criteria);
  176. if (isset($this->pageNavigation))
  177. {
  178. $this->pageNavigation->setCount($count); // count of records
  179. $this->pageNavigation->setProperties($param); // order, page
  180. $this->pageNavigation->setLimit($limit); // limit
  181. }
  182. // close the transaction
  183. TTransaction::close();
  184. $this->loaded = true;
  185. }
  186. catch (Exception $e) // in case of exception
  187. {
  188. // shows the exception error message
  189. new TMessage('error', $e->getMessage());
  190. // undo all pending operations
  191. TTransaction::rollback();
  192. }
  193. }
  194. /**
  195. * Clear form
  196. public function onClear($param)
  197. {
  198. $this->form->clear();
  199. }
  200. * method onEdit()
  201. * Executed whenever the user clicks at the edit button da datagrid
  202. * @param $param An array containing the GET ($_GET) parameters
  203. */
  204. public function onEdit($param)
  205. {
  206. try
  207. {
  208. if (empty('sample'))
  209. {
  210. throw new Exception(AdiantiCoreTranslator::translate('^1 was not defined. You must call ^2 in ^3', AdiantiCoreTranslator::translate('Database'), 'setDatabase()', AdiantiCoreTranslator::translate('Constructor')));
  211. }
  212. if (empty('Cpprod'))
  213. {
  214. throw new Exception(AdiantiCoreTranslator::translate('^1 was not defined. You must call ^2 in ^3', 'Active Record', 'setActiveRecord()', AdiantiCoreTranslator::translate('Constructor')));
  215. }
  216. if (isset($param['key']))
  217. {
  218. // get the parameter $key
  219. $key=$param['key'];
  220. // open a transaction with database
  221. TTransaction::open('sample');
  222. $class = 'Cpprod';
  223. // instantiates object
  224. $object = new $class($key);
  225. // fill the form with the active record data
  226. $this->form->setData($object);
  227. // close the transaction
  228. TTransaction::close();
  229. return $object;
  230. }
  231. else
  232. {
  233. $this->form->clear();
  234. }
  235. }
  236. catch (Exception $e) // in case of exception
  237. {
  238. // shows the exception error message
  239. new TMessage('error', $e->getMessage());
  240. // undo all pending operations
  241. TTransaction::rollback();
  242. }
  243. }
  244. /**
  245. * Shows the page
  246. public function show()
  247. {
  248. // check if the datagrid is already loaded
  249. if (!$this->loaded AND (!isset($_GET['method']) OR $_GET['method'] !== 'onReload') )
  250. {
  251. $this->onReload( func_get_arg(0) );
  252. }
  253. parent::show();
  254. }
  255. */
  256. }
  257. ?>

obs.: Quando cliclo no botão (add), a linha de cima é repetida na próxima que é criada ao invés de vir em branco. Também não consegui resolver esse problema.

Desde já agradeço pela ajuda.

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

Marcos, a função onSave de uma classe com campos vetoriais é um pouco diferente das demais. Veja no link abaixo:
adianti.com.br/framework_files/tutor/index.php?class=SaleMultiValueF

Outro detalhe está na criação dos campos, o nome precisa ser seguido por '[]' para que os campos sejam passados como array na postagem do formulário:
 
  1. <?php
  2. $quantidade = new TEntry('quantidade[]');
  3. ?>
MS

Obrigado Nataniel. Segui o exemplo do tutor e entendi a relação com os parâmetros dos 3 modelos utilizados. Muito obrigado mesmo!

O que você acha, é possível encontrar um [url=www.deviceranking.pt/phone/14396/xiaomi-mi-play]aplicativo[/url] no telefone na loja que poderia ser usado como um bloco de notas na escrita de códigos para a construção de determinadas tarefas?