Inserir data de criação e data de edição em formulario Ola, estou com um problema tenho um objeto que é um diario de paradas de produção, eu gostaria que quando criar um novo registro ele guarde a data/hora inicial e quando editar e guarde a data/hora final. Nao encontrei uma maneira de fazer isso. Eu tentei criando um repositório, pois em teoria só na edição haveria uma id igual, mas não faz nada. eu pensei na função onEdit, antes de obj...
CO
Inserir data de criação e data de edição em formulario  
Ola, estou com um problema tenho um objeto que é um diario de paradas de produção, eu gostaria que quando criar um novo registro ele guarde a data/hora inicial e quando editar e guarde a data/hora final.

Nao encontrei uma maneira de fazer isso. Eu tentei criando um repositório, pois em teoria só na edição haveria uma id igual, mas não faz nada. eu pensei na função onEdit, antes de object store eu definir este valor, mas tambem nao deu certo, não consegui atribuir o valor.


class DiarioForm extends TPage { protected $form; // form use Adianti\Base\AdiantiStandardFormTrait; // Standard form methods /** * Class constructor * Creates the page and the registration form */ function __construct() { parent::__construct(); $this->setDatabase('basedados'); // defines the database $this->setActiveRecord('Diario'); // defines the active record // creates the form $this->form = new TQuickForm('form_Diario'); $this->form->class = 'tform'; // change CSS class $this->form->style = 'display: table;width:100%'; // change style // define the form title $this->form->setFormTitle('Diario'); // create the form fields $id = new TEntry('id'); $parada_id = new TDBCombo('parada_id','basedados','Parada','id','codigo'); $system_user_id = new TDBCombo('system_user_id','basedados','SystemUser','id','login'); $eqpto_id = new TDBCombo('eqpto_id','basedados','Equipamento','id','name'); $data_inicio = new THidden('data_inicio'); $data_fim = new THidden('data_fim'); //se existir o ID é edição entao define o valor da data_fim try { TTransaction::open('gestor'); $criteria = new TCriteria; //$criteria->setProperty('limit',1); $criteria->add( new TFilter('id', '=','id')); $repos = new TRepository('Diario'); $objetos = $repos->load($criteria); echo "teste de filter"; foreach ($objetos as $objeto) { $data_fim->setValue(date('Y-m-d H:i:s')); } TTransaction::close(); } catch (Exception $e) { TMessage('Erro', $e->getMessage()); } try { TTransaction::open('gestor'); $criterio = new TCriteria; $criterio->setProperty('limit',1); $criterio->add( new TFilter('login', '=',TSession::getValue('login'))); $repo = new TRepository('SystemUser'); $objetos = $repo->load($criterio); foreach ($objetos as $objeto) { $system_user_id->setValue($objeto->id); $system_user_id->setEditable(false); if (TSession::getValue('login') == 'admin') { $system_user_id->setEditable(true); } } TTransaction::close(); } catch (Exception $e) { TMessage('Erro', $e->getMessage()); } // add the fields $this->form->addQuickField('Id', $id, 100 ); $this->form->addQuickField('Parada Id', $parada_id, 100 ); $this->form->addQuickField('System User Id', $system_user_id, 100 ); $this->form->addQuickField('Eqpto Id', $eqpto_id, 100 ); $this->form->addQuickField('Data Inicio', $data_inicio, 100 ); $this->form->addQuickField('Data Fim', $data_fim, 100 ); $data_inicio->setValue(date('Y-m-d H:i:s')); if (!empty($id)) { $id->setEditable(FALSE); } // create the form actions $this->form->addQuickAction(_t('Save'), new TAction(array($this, 'onSave')), 'fa:floppy-o'); $this->form->addQuickAction(_t('Resume'), new TAction(array($this, 'onEdit')),'fa:floopy-o'); // vertical box container $container = new TVBox; $container->style = 'width: 90%'; // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__)); $container->add($this->form); parent::add($container); } public function onSave( $param ) { try { TTransaction::open('gestor'); // open a transaction /** // Enable Debug logger for SQL operations inside the transaction TTransaction::setLogger(new TLoggerSTD); // standard output TTransaction::setLogger(new TLoggerTXT('log.txt')); // file **/ $this->form->validate(); // validate form data $object = new Diario; // create an empty object $data = $this->form->getData(); // get form data as array $object->fromArray( (array) $data); // load the object with data $object->store(); // save the object // get the generated id $data->id = $object->id; $this->form->setData($data); // fill form data TTransaction::close(); // close the transaction new TMessage('info', TAdiantiCoreTranslator::translate('Record saved')); } catch (Exception $e) // in case of exception { new TMessage('error', $e->getMessage()); // shows the exception error message $this->form->setData( $this->form->clear(True)); // Clear form data TTransaction::rollback(); // undo all pending operations } } /** * Clear form data * @param $param Request */ public function onClear( $param ) { $this->form->clear(TRUE); } /** * Load object to form data * @param $param Request */ public function onEdit( $param ) { try { TTransaction::open('gestor'); // open a transaction /** // Enable Debug logger for SQL operations inside the transaction TTransaction::setLogger(new TLoggerSTD); // standard output TTransaction::setLogger(new TLoggerTXT('log.txt')); // file **/ $this->form->validate(); // validate form data $object = new Diario; // create an empty object $data = $this->form->getData(); // get form data as array $object->fromArray( (array) $data); // load the object with data $object->store(); // save the object // get the generated id $data->id = $object->id; TTransaction::close(); // close the transaction new TMessage('info', TAdiantiCoreTranslator::translate('Record saved')); } catch (Exception $e) // in case of exception { new TMessage('error', $e->getMessage()); // shows the exception error message $this->form->setData( $this->form->clear(True)); // Clear form data TTransaction::rollback(); // undo all pending operations } } }


Agradeço a ajuda,
Claudio Oliveira

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


NR

Claudio, eu faria as verificações diretamente na função onSave:
 
  1. <?php
  2. public function onSave( $param )
  3. {
  4. try
  5. {
  6. TTransaction::open('gestor'); // open a transaction
  7. $this->form->validate(); // validate form data
  8. $object = new Diario; // create an empty object
  9. $data = $this->form->getData(); // get form data as array
  10. $object->fromArray( (array) $data); // load the object with data
  11. // se tiver id trata-se de uma edição
  12. if ($data->id)
  13. $object->data_fim = date('Y-m-d H:i:s');
  14. else
  15. $object->data_inicio = date('Y-m-d H:i:s');
  16. $object->store(); // save the object
  17. // get the generated id
  18. $data->id = $object->id;
  19. $this->form->setData($data); // fill form data
  20. TTransaction::close(); // close the transaction
  21. new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'));
  22. }
  23. catch (Exception $e) // in case of exception
  24. {
  25. new TMessage('error', $e->getMessage()); // shows the exception error message
  26. $this->form->setData( $this->form->getData());
  27. TTransaction::rollback(); // undo all pending operations
  28. }
  29. }
  30. ?>
CO

Funcionou!!

Muito obrigado pela ajuda!!