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:
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.
- <?php
- class CadastroProdutosPO extends TPage
- {
- private $form;
-
- /**
- * Constructor
- */
- public function __construct()
- {
- parent::__construct();
-
- // create form and table container
- $this->form = new TForm;
- $table = new TTable;
- $table->addSection('thead');
-
- // create the form fields
- $numpo = new TEntry('numpo');
- $apelido = new TEntry('apelido');
- //form page 2
- $table->addRowSet('',array($d1 = new TLabel('Número PO'),$numpo,$d2 = new TLabel('Apelido'),$apelido, $d3 = new TLabel('')));
- $d1 -> setSize(100);
- $d2 -> setSize(130);
- $d3 -> setSize(230);
-
- $table->addRowSet('',array($d1 = new TLabel(''),$d2 = new TLabel(''), $d3 = new TLabel('')));
- $d1 -> setSize(100);
- $d2 -> setSize(130);
- $d3 -> setSize(230);
-
- $numpo -> setSize(200);
- $apelido -> setSize(200);
-
- //$numpo->setEditable( FALSE );
- //$apelido->setEditable( FALSE );
-
- $this->form->add($table);
-
- $table->addSection('tbody');
- for ($n=1; $n<=5; $n++)
- {
- $cod = new TDBEntry('cod','sample','Ds','cod');
- $cod->setMinLength(1);
- $cod->cod ='cod';
- $descpo = new TText('descpo');
- $quantidade = new TEntry('quantidade');
- $custo = new TEntry('custo');
-
- //Regras do form page2
-
- $custo->setNumericMask(3, '.', ',');
- // create delete button
- $del = new TImage('fa:trash-o red');
- $del->onclick = 'ttable_remove_row(this)';
-
- $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));
- $d1 -> setSize(65);
- $d2 -> setSize(75);
- $d3 -> setSize(40);
- $d4 -> setSize(70);
- $cod->setSize(60);
- $descpo->setSize(540,30);
- $quantidade->setSize(60);
- $custo->setSize(60);
-
- }
-
- // create add button
- $add = new TButton('clone');
- $add->setLabel('Add');
- $add->setImage('fa:plus-circle green');
- $add->addFunction('ttable_clone_previous_row(this)');
-
- // create save button
- $save = TButton::create('save', array($this, 'onSave'), 'Save', 'fa:save green');
- $this->form->addField($save);
-
- $cadastropo = TButton::create('cadastropo', array($this, 'displayColumn'), 'Cadastro PO', 'fa:table blue');
- $this->form->addField($cadastropo);
-
- $list = TButton::create('list', array('ProdutosPOList', 'onReload'), 'Listagem Produtos', 'fa:table black');
- $this->form->addField($list);
-
- //$this->form->addQuickAction('Lista PO', new TAction(array('POList', 'onReload')), 'fa:table black');
-
- $table->addRowSet('',array($d1 = new TLabel(''),$save,$d2 = new TLabel(''),$cadastropo,$d3 = new TLabel(''),$add,$d4 = new TLabel(''),$list));
- $d1 -> setSize(0);
- $d2 -> setSize(10);
- $d3 -> setSize(10);
- $d4 -> setSize(10);
-
- $panel = new TPanelGroup('Produtos da PO');
- $panel->add($this->form);
-
- // wrap the page content using vertical box
- $vbox = new TVBox;
- //$vbox->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
- $vbox->add($panel);
- parent::add($vbox);
- }
- /**
- * Redirecionar para uma página (class)
- */
- public function displayColumn( $numpo )
- {
- $data = $this->form->getData();
- $this->form->setData($data);
- TApplication::loadPage('CadastroPO');
- }
- /**
- * method onSave()
- * Executed whenever the user clicks at the save button
- */
- public function onSave()
- {
- try
- {
- if (empty('sample'))
- {
- throw new Exception(AdiantiCoreTranslator::translate('^1 was not defined. You must call ^2 in ^3', AdiantiCoreTranslator::translate('Database'), 'setDatabase()', AdiantiCoreTranslator::translate('Constructor')));
- }
-
- if (empty('Cpprod'))
- {
- throw new Exception(AdiantiCoreTranslator::translate('^1 was not defined. You must call ^2 in ^3', 'Active Record', 'setActiveRecord()', AdiantiCoreTranslator::translate('Constructor')));
- }
-
- // open a transaction with database
- TTransaction::open('sample');
-
- // get the form data
- $object = $this->form->getData('Cpprod');
-
- // validate data
- $this->form->validate();
-
- // stores the object
- $object->store();
-
- // fill the form with the active record data
- $this->form->setData($object);
-
- // close the transaction
- TTransaction::close();
-
- // shows the success message
- new TMessage('info', AdiantiCoreTranslator::translate('Record saved'));
-
- return $object;
- }
- catch (Exception $e) // in case of exception
- {
- // get the form data
- $object = $this->form->getData();
-
- // fill the form with the active record data
- $this->form->setData($object);
-
- // shows the exception error message
- new TMessage('error', $e->getMessage());
-
- // undo all pending operations
- TTransaction::rollback();
- }
- }
-
- /**
- * method onReload()
- * Load the datagrid with the database objects
- */
- public function onReload($param = NULL)
- {
- try
- {
- // open a transaction with database
- TTransaction::open('sample');
-
- // instancia um repositório
- $repository = new TRepository('Cpprod');
- $limit = isset($this->limit) ? ( $this->limit > 0 ? $this->limit : NULL) : 100;
- // creates a criteria
- $criteria = isset($this->criteria) ? clone $this->criteria : new TCriteria;
- if ($this->order)
- {
- $criteria->setProperty('order', $this->order);
- $criteria->setProperty('direction', $this->direction);
- }
- $criteria->setProperties($param); // order, offset
- $criteria->setProperty('limit', $limit);
-
- // load the objects according to criteria
- $objects = $repository->load($criteria, FALSE);
-
- if (is_callable($this->transformCallback))
- {
- call_user_func($this->transformCallback, $objects);
- }
-
- $this->datagrid->clear();
- if ($objects)
- {
- // iterate the collection of active records
- foreach ($objects as $object)
- {
- // add the object inside the datagrid
- $this->datagrid->addItem($object);
- }
- }
-
- // reset the criteria for record count
- $criteria->resetProperties();
- $count= $repository->count($criteria);
-
-
- if (isset($this->pageNavigation))
- {
- $this->pageNavigation->setCount($count); // count of records
- $this->pageNavigation->setProperties($param); // order, page
- $this->pageNavigation->setLimit($limit); // limit
- }
-
- // close the transaction
- TTransaction::close();
- $this->loaded = true;
- }
- catch (Exception $e) // in case of exception
- {
- // shows the exception error message
- new TMessage('error', $e->getMessage());
- // undo all pending operations
- TTransaction::rollback();
- }
- }
- /**
- * Clear form
-
- public function onClear($param)
- {
- $this->form->clear();
- }
-
- * method onEdit()
- * Executed whenever the user clicks at the edit button da datagrid
- * @param $param An array containing the GET ($_GET) parameters
- */
- public function onEdit($param)
- {
- try
- {
- if (empty('sample'))
- {
- throw new Exception(AdiantiCoreTranslator::translate('^1 was not defined. You must call ^2 in ^3', AdiantiCoreTranslator::translate('Database'), 'setDatabase()', AdiantiCoreTranslator::translate('Constructor')));
- }
-
- if (empty('Cpprod'))
- {
- throw new Exception(AdiantiCoreTranslator::translate('^1 was not defined. You must call ^2 in ^3', 'Active Record', 'setActiveRecord()', AdiantiCoreTranslator::translate('Constructor')));
- }
-
- if (isset($param['key']))
- {
- // get the parameter $key
- $key=$param['key'];
-
- // open a transaction with database
- TTransaction::open('sample');
-
- $class = 'Cpprod';
-
- // instantiates object
- $object = new $class($key);
-
- // fill the form with the active record data
- $this->form->setData($object);
-
- // close the transaction
- TTransaction::close();
-
- return $object;
- }
- else
- {
- $this->form->clear();
- }
- }
- catch (Exception $e) // in case of exception
- {
- // shows the exception error message
- new TMessage('error', $e->getMessage());
- // undo all pending operations
- TTransaction::rollback();
- }
- }
-
- /**
- * Shows the page
-
- public function show()
- {
- // check if the datagrid is already loaded
- if (!$this->loaded AND (!isset($_GET['method']) OR $_GET['method'] !== 'onReload') )
- {
- $this->onReload( func_get_arg(0) );
- }
- parent::show();
- }
- */
- }
- ?>
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.
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:
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?