Gravar na tabela a Unidade do Usuário Boa tarde Amigos, Alguém sabe informar como faço para gravar na tabela o nome do usuário logado no sistema e a unidade em que o usuário está cadastrado quando este gravar um novo registro? ...
ST
Gravar na tabela a Unidade do Usuário  
Boa tarde Amigos,
Alguém sabe informar como faço para gravar na tabela o nome do usuário logado no sistema e a unidade em que o usuário está cadastrado quando este
gravar um novo registro?


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


MG

No controller "LoginForm" ao se logar o sistema grava na variável de sessão o userid, recupere assim $userId = TSession::getValue('userid').
Se observar o modelo "SystemUser" poderá ver que há um relacionamento com "SystemUnit", uma vez recuperado um objeto "SystemUser", vc poderá obter a unit.
Exemplo:

$user = new SystemUser(TSession::getValue('userid'));
$unitId = $user->unit->id;

e assim por diante
ST

Marcelo,
Certo. Mas como gravar no banco de dados, ao clicar em salvar?
MG

No seu model e banco de dados vc deve ter os campos: system_user_id e system_unit_id.

Antes de salvar ($obj->store()), vc associa, por exemplo:

 
  1. <?php
  2. public funciton onSave( $param )
  3. {
  4. ....
  5. $obj->system_user_id = TSession::getvalue('userid');
  6. $user = new SystemUser(TSession::getValue('userod'));
  7. $obj->system_unit_id = $user->system_unit_id;
  8. $obj->store();
  9. ...
  10. }
  11. ?>
ST

Marcelo,
Certo. Mas como gravar no banco de dados, ao clicar em salvar?
ST

Marcelo,
Onde eu coloco esse código OnSave?
MG

Sebastião

Acredito que você tenha um form, certo?

Neste form você tem os componentes de entrada de dados e num dado momento você deve ter adicionado um TAction, certo?

Isto é o básico do framework....

Veja um exemplo:

 
  1. <?php
 
  1. <?php
  2. /**
  3. * TipoPercursosFormList Form List
  4. * @author <your name here>
  5. */
  6. class TipoPercursosFormList extends TPage
  7. {
  8. protected $form; // form
  9. protected $datagrid; // datagrid
  10. protected $pageNavigation;
  11. protected $loaded;
  12. /**
  13. * Form constructor
  14. * @param $param Request
  15. */
  16. public function __construct( $param )
  17. {
  18. parent::__construct();
  19. // creates the form
  20. $this->form = new TQuickForm('form_TipoPercursos');
  21. $this->form->class = 'tform'; // change CSS class
  22. $this->form = new BootstrapFormWrapper($this->form);
  23. $this->form->style = 'display: table;width:100%'; // change style
  24. $this->form->setFormTitle('TipoPercursos');
  25. $this->form->setFieldsByRow(2);
  26. // create the form fields
  27. $id = new TEntry('id');
  28. $descricao = new TEntry('descricao');
  29. $valor_pagar = new TEntry('valor_pagar');
  30. $valor_percurso = new TEntry('valor_percurso');
  31. $status = new TCombo('status');
  32. $id->setEditable(FALSE);
  33. $valor_pagar->setNumericMask(2,',','.',TRUE);
  34. $valor_percurso->setNumericMask(2,',','.',TRUE);
  35. // config
  36. $stt = array(
  37. '1' => 'Ativo',
  38. '0' => 'Inativo'
  39. );
  40. $status->addItems($stt);
  41. $status->setValue(1);
  42. // add the fields
  43. $this->form->addQuickField('Id', $id, 100 );
  44. $this->form->addQuickField('Descrição', $descricao, 200 , new TRequiredValidator);
  45. $this->form->addQuickField('Valor Percurso', $valor_percurso, 200 , new TRequiredValidator);
  46. $this->form->addQuickField('Valor Pagar', $valor_pagar, 200 , new TRequiredValidator);
  47. $this->form->addQuickField('Status', $status, 100 , new TRequiredValidator);
  48. /** samples
  49. $this->form->addQuickFields('Date', array($date1, new TLabel('to'), $date2)); // side by side fields
  50. $fieldX->addValidation( 'Field X', new TRequiredValidator ); // add validation
  51. $fieldX->setSize( 100, 40 ); // set size
  52. **/
  53. // create the form actions
  54. $this->form->addQuickAction(_t('Save'), new TAction(array($this, 'onSave')), 'fa:floppy-o');
  55. $this->form->addQuickAction(_t('New'), new TAction(array($this, 'onClear')), 'bs:plus-sign green');
  56. // creates a Datagrid
  57. $this->datagrid = new TDataGrid;
  58. ##LIST_DECORATOR##
  59. $this->datagrid->style = 'width: 100%';
  60. $this->datagrid->setHeight(320);
  61. // $this->datagrid->datatable = 'true';
  62. // $this->datagrid->enablePopover('Popover', 'Hi <b> {name} </b>');
  63. // creates the datagrid columns
  64. $column_id = new TDataGridColumn('id', 'Id', 'left');
  65. $column_descrucai = new TDataGridColumn('descricao', 'Descrição', 'left');
  66. $column_valor_pagar = new TDataGridColumn('valor_pagar', 'Valor Pagar', 'right');
  67. $column_valor_percurso = new TDataGridColumn('valor_percurso', 'Valor Percurso', 'right');
  68. $column_status = new TDataGridColumn('status', 'Status', 'center');
  69. $column_user = new TDataGridColumn('system_user->name','Por','center');
  70. $column_update = new TDataGridColumn('update_at','Em','center');
  71. // add the columns to the DataGrid
  72. $this->datagrid->addColumn($column_id);
  73. $this->datagrid->addColumn($column_descrucai);
  74. $this->datagrid->addColumn($column_valor_pagar);
  75. $this->datagrid->addColumn($column_valor_percurso);
  76. $this->datagrid->addColumn($column_status);
  77. $this->datagrid->addColumn($column_user);
  78. $this->datagrid->addColumn($column_update);
  79. // transformers
  80. $column_status->setTransformer(function($value, $object, $row){
  81. $lbl = new TLabel('');
  82. switch ($value) {
  83. case 1 :
  84. $lbl->setValue('Ativo');
  85. $lbl->class = 'label label-success';
  86. break;
  87. case 0 :
  88. $lbl->setValue('Inativo');
  89. $lbl->class = 'label label-danger';
  90. break;
  91. }
  92. return $lbl;
  93. });
  94. $column_update->setTransformer(function($value, $object, $row){
  95. $data = new DateTime($value);
  96. return $data->format('d/m/Y H:m:s');
  97. });
  98. // creates two datagrid actions
  99. $action1 = new TDataGridAction(array($this, 'onEdit'));
  100. $action1->setUseButton(TRUE);
  101. $action1->setButtonClass('btn btn-default');
  102. $action1->setLabel(_t('Edit'));
  103. $action1->setImage('fa:pencil-square-o blue fa-lg');
  104. $action1->setField('id');
  105. $action2 = new TDataGridAction(array($this, 'onDelete'));
  106. $action2->setUseButton(TRUE);
  107. $action2->setButtonClass('btn btn-default');
  108. $action2->setLabel(_t('Delete'));
  109. $action2->setImage('fa:trash-o red fa-lg');
  110. $action2->setField('id');
  111. // add the actions to the datagrid
  112. $this->datagrid->addAction($action1);
  113. $this->datagrid->addAction($action2);
  114. // create the datagrid model
  115. $this->datagrid->createModel();
  116. // creates the page navigation
  117. $this->pageNavigation = new TPageNavigation;
  118. $this->pageNavigation->setAction(new TAction(array($this, 'onReload')));
  119. $this->pageNavigation->setWidth($this->datagrid->getWidth());
  120. // vertical box container
  121. $container = new TVBox;
  122. $container->style = 'width: 90%';
  123. $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  124. $container->add(TPanelGroup::pack('Cadastro de Valores e Percursos', $this->form));
  125. $container->add($this->datagrid);
  126. $container->add($this->pageNavigation);
  127. parent::add($container);
  128. }
  129. /**
  130. * Load the datagrid with data
  131. */
  132. public function onReload($param = NULL)
  133. {
  134. try
  135. {
  136. // open a transaction with database 'moto'
  137. TTransaction::open('moto');
  138. // creates a repository for TipoPercursos
  139. $repository = new TRepository('TipoPercursos');
  140. $limit = 10;
  141. // creates a criteria
  142. $criteria = new TCriteria;
  143. // default order
  144. if (empty($param['order']))
  145. {
  146. $param['order'] = 'id';
  147. $param['direction'] = 'asc';
  148. }
  149. $criteria->setProperties($param); // order, offset
  150. $criteria->setProperty('limit', $limit);
  151. if (TSession::getValue('TipoPercursos_filter'))
  152. {
  153. // add the filter stored in the session to the criteria
  154. $criteria->add(TSession::getValue('TipoPercursos_filter'));
  155. }
  156. // load the objects according to criteria
  157. $objects = $repository->load($criteria, FALSE);
  158. $this->datagrid->clear();
  159. if ($objects)
  160. {
  161. // iterate the collection of active records
  162. foreach ($objects as $object)
  163. {
  164. // add the object inside the datagrid
  165. $this->datagrid->addItem($object);
  166. }
  167. }
  168. // reset the criteria for record count
  169. $criteria->resetProperties();
  170. $count= $repository->count($criteria);
  171. $this->pageNavigation->setCount($count); // count of records
  172. $this->pageNavigation->setProperties($param); // order, page
  173. $this->pageNavigation->setLimit($limit); // limit
  174. // close the transaction
  175. TTransaction::close();
  176. $this->loaded = true;
  177. }
  178. catch (Exception $e) // in case of exception
  179. {
  180. // shows the exception error message
  181. new TMessage('error', '<b>Error</b> ' . $e->getMessage());
  182. // undo all pending operations
  183. TTransaction::rollback();
  184. }
  185. }
  186. /**
  187. * Ask before deletion
  188. */
  189. public function onDelete($param)
  190. {
  191. // define the delete action
  192. $action = new TAction(array($this, 'Delete'));
  193. $action->setParameters($param); // pass the key parameter ahead
  194. // shows a dialog to the user
  195. new TQuestion(TAdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
  196. }
  197. /**
  198. * Delete a record
  199. */
  200. public function Delete($param)
  201. {
  202. try
  203. {
  204. $key=$param['key']; // get the parameter $key
  205. TTransaction::open('moto'); // open a transaction with database
  206. $object = new TipoPercursos($key, FALSE); // instantiates the Active Record
  207. $object->delete(); // deletes the object from the database
  208. TTransaction::close(); // close the transaction
  209. $this->onReload( $param ); // reload the listing
  210. new TMessage('info', TAdiantiCoreTranslator::translate('Record deleted')); // success message
  211. }
  212. catch (Exception $e) // in case of exception
  213. {
  214. new TMessage('error', '<b>Error</b> ' . $e->getMessage()); // shows the exception error message
  215. TTransaction::rollback(); // undo all pending operations
  216. }
  217. }
  218. /**
  219. * Save form data
  220. * @param $param Request
  221. */
  222. public function onSave( $param )
  223. {
  224. try
  225. {
  226. TTransaction::open('moto'); // open a transaction
  227. /**
  228. // Enable Debug logger for SQL operations inside the transaction
  229. TTransaction::setLogger(new TLoggerSTD); // standard output
  230. TTransaction::setLogger(new TLoggerTXT('log.txt')); // file
  231. **/
  232. $this->form->validate(); // validate form data
  233. $object = new TipoPercursos; // create an empty object
  234. $data = $this->form->getData(); // get form data as array
  235. $object->fromArray( (array) $data); // load the object with data
  236. $object->system_user_id = TSession::getValue('userid');
  237. if (empty($object->id)) {
  238. $object->create_at = date('Y-m-d H:m:s');
  239. }
  240. $object->updade_at = date('Y-m-d H:m:s');
  241. $object->store(); // save the object
  242. // get the generated id
  243. $data->id = $object->id;
  244. $this->form->setData($data); // fill form data
  245. TTransaction::close(); // close the transaction
  246. new TMessage('info', TAdiantiCoreTranslator::translate('Record saved')); // success message
  247. $this->onReload(); // reload the listing
  248. }
  249. catch (Exception $e) // in case of exception
  250. {
  251. new TMessage('error', $e->getMessage()); // shows the exception error message
  252. $this->form->setData( $this->form->getData() ); // keep form data
  253. TTransaction::rollback(); // undo all pending operations
  254. }
  255. }
  256. /**
  257. * Clear form data
  258. * @param $param Request
  259. */
  260. public function onClear( $param )
  261. {
  262. $this->form->clear(TRUE);
  263. }
  264. /**
  265. * Load object to form data
  266. * @param $param Request
  267. */
  268. public function onEdit( $param )
  269. {
  270. try
  271. {
  272. if (isset($param['key']))
  273. {
  274. $key = $param['key']; // get the parameter $key
  275. TTransaction::open('moto'); // open a transaction
  276. $object = new TipoPercursos($key); // instantiates the Active Record
  277. $this->form->setData($object); // fill the form
  278. TTransaction::close(); // close the transaction
  279. }
  280. else
  281. {
  282. $this->form->clear(TRUE);
  283. }
  284. }
  285. catch (Exception $e) // in case of exception
  286. {
  287. new TMessage('error', $e->getMessage()); // shows the exception error message
  288. TTransaction::rollback(); // undo all pending operations
  289. }
  290. }
  291. /**
  292. * method show()
  293. * Shows the page
  294. */
  295. public function show()
  296. {
  297. // check if the datagrid is already loaded
  298. if (!$this->loaded AND (!isset($_GET['method']) OR $_GET['method'] !== 'onReload') )
  299. {
  300. $this->onReload( func_get_arg(0) );
  301. }
  302. parent::show();
  303. }
  304. }
  305. ?>

</your>
ST

Marcelo,
Obrigado por sua ajuda.
Saiba que estou na fase inicial da Ferramenta Adianti Framework.
Este é o meu primeiro projeto, por isso estou com dúvidas de como implementar o código.
MG

Tranquilo
Estamos aqui para ajudar.
Você conseguiu entender a lógica?
Isso é o mais importante!
ST

Marcelo,

Não consigo nem gravar a unidade do usuário e nem o usuário no banco de dados.
Sinceramente estou completamente perdido.
Se puder me ajudar a identificar onde estou errando, te agradeceria muito.

Segue o modelo:

 
  1. <?php
  2. /**
  3. * Perdcomp Active Record
  4. * @author <your-name-here>
  5. */
  6. class Perdcomp extends TRecord
  7. {
  8. const TABLENAME = 'perdcomp';
  9. const PRIMARYKEY= 'perdcomp_id';
  10. const IDPOLICY = 'max'; // {max, serial}
  11. private $origem_documento;
  12. private $tipo_credito;
  13. private $tipo_documento;
  14. private $tipo_imposto;
  15. private $unit;
  16. /**
  17. * Constructor method
  18. */
  19. public function __construct($id = NULL, $callObjectLoad = TRUE)
  20. {
  21. parent::__construct($id, $callObjectLoad);
  22. parent::addAttribute('DataCriacao');
  23. parent::addAttribute('DataTransmissao');
  24. parent::addAttribute('Sequencial');
  25. parent::addAttribute('Nr_Perdcomp');
  26. parent::addAttribute('TipoDocumento_id');
  27. parent::addAttribute('OrigemDocumento_id');
  28. parent::addAttribute('TipoCredito_id');
  29. parent::addAttribute('SaldoDeclarado');
  30. parent::addAttribute('Exercicio');
  31. parent::addAttribute('TipoImposto_id');
  32. parent::addAttribute('ValorCompensado');
  33. parent::addAttribute('Competencia');
  34. parent::addAttribute('PerdcompOriginal');
  35. parent::addAttribute('Situacao');
  36. parent::addAttribute('Cancelamento');
  37. parent::addAttribute('CreditoOriginalInicial');
  38. parent::addAttribute('CreditoOriginalUtilizadoCompensacoes');
  39. parent::addAttribute('CreditoOriginalDisponivel');
  40. parent::addAttribute('CreditoOriginalTransmissao');
  41. parent::addAttribute('SelicAcumulada');
  42. parent::addAttribute('CreditoAtualizado');
  43. parent::addAttribute('DebitosDocumento');
  44. parent::addAttribute('CreditoOriginalUtilizadoDocumento');
  45. parent::addAttribute('SaldoCreditoOriginal');
  46. parent::addAttribute('system_unit_id');
  47. parent::addAttribute('system_user_id');
  48. parent::addAttribute('Ged');
  49. }
  50. public function get_tipo_credito()
  51. {
  52. if (empty($this->tipo_credito))
  53. $this->tipo_credito = new TipoCredito($this->TipoCredito_id);
  54. return $this->tipo_credito->TipoCreditoDescricao;
  55. }
  56. public function get_tipo_documento()
  57. {
  58. if (empty($this->tipo_documento))
  59. $this->tipo_documento = new TipoDocumento($this->TipoDocumento_id);
  60. return $this->tipo_documento->TipoDocumentoDescricao;
  61. }
  62. public function get_origem_documento()
  63. {
  64. if (empty($this->origem_documento))
  65. $this->origem_documento = new OrigemDocumento($this->OrigemDocumento_id);
  66. return $this->origem_documento->OrigemDocumentoDescricao;
  67. }
  68. public function get_tipo_imposto()
  69. {
  70. if (empty($this->tipo_imposto))
  71. $this->tipo_imposto = new TipoImposto($this->TipoImposto_id);
  72. return $this->tipo_imposto->TipoImpostoDescricao;
  73. }
  74. public function get_unit()
  75. {
  76. // loads the associated object
  77. if (empty($this->unit))
  78. $this->unit = new SystemUnit($this->system_unit_id);
  79. // returns the associated object
  80. return $this->unit;
  81. }
  82. }
  83. Formulário:
 
  1. <?php
  2. /**
  3. * PerdcompForm Registration
  4. * @author <your name here>
  5. */
  6. class PerdcompForm extends TPage
  7. {
  8. protected $form; // form
  9. use Adianti\Base\AdiantiStandardFormTrait; // Standard form methods
  10. /**
  11. * Class constructor
  12. * Creates the page and the registration form
  13. */
  14. function __construct()
  15. {
  16. parent::__construct();
  17. $this->setDatabase('perdcomp'); // defines the database
  18. $this->setActiveRecord('Perdcomp'); // defines the active record
  19. // creates the form
  20. $this->form = new TQuickForm('form_Perdcomp');
  21. $this->form->class = 'tform'; // change CSS class
  22. $this->form->style = 'display: table;width:100%'; // change style
  23. // define the form title
  24. $this->form->setFormTitle('Perdcomp');
  25. // create the form fields
  26. $perdcomp_id = new TEntry('perdcomp_id');
  27. $DataCriacao = new TDate('DataCriacao');
  28. $DataTransmissao = new TDate('DataTransmissao');
  29. $Sequencial = new TEntry('Sequencial');
  30. $Nr_Perdcomp = new TEntry('Nr_Perdcomp');
  31. $TipoDocumento_id = new ">TDBSeekButton('TipoDocumento_id', 'perdcomp',$this->form->getName(),'TipoDocumento', 'TipoDocumentoDescricao','TipoDocumento_id','tipo_documento');
  32. $TipoDocumentoDescricao = new TEntry('tipo_documento');
  33. $OrigemDocumento_id = new ">TDBSeekButton('OrigemDocumento_id', 'perdcomp', $this->form->getName(), 'OrigemDocumento', 'OrigemDocumentoDescricao', 'OrigemDocumento_id', 'origem_documento');
  34. $OrigemDocumentoDescricao = new TEntry('origem_documento');
  35. $TipoCredito_id = new ">TDBSeekButton('TipoCredito_id', 'perdcomp', $this->form->getName(), 'TipoCredito', 'TipoCreditoDescricao', 'TipoCredito_id', 'tipo_credito');
  36. $TipoCreditoDescricao = new TEntry('tipo_credito');
  37. $SaldoDeclarado = new TEntry('SaldoDeclarado');
  38. $Exercicio = new TEntry('Exercicio');
  39. $TipoImposto_id = new ">TDBSeekButton('TipoImposto_id', 'perdcomp', $this->form->getName(), 'TipoImposto', 'TipoImpostoDescricao', 'TipoImposto_id', 'tipo_imposto');
  40. $TipoImpostoDescricao = new TEntry('tipo_imposto');
  41. $ValorCompensado = new TEntry('ValorCompensado');
  42. $Competencia = new TDate('Competencia');
  43. $PerdcompOriginal = new TEntry('PerdcompOriginal');
  44. $Situacao = new TEntry('Situacao');
  45. $Cancelamento = new TEntry('Cancelamento');
  46. $CreditoOriginalInicial = new TEntry('CreditoOriginalInicial');
  47. $CreditoOriginalUtilizadoCompensacoes = new TEntry('CreditoOriginalUtilizadoCompensacoes');
  48. $CreditoOriginalDisponivel = new TEntry('CreditoOriginalDisponivel');
  49. $CreditoOriginalTransmissao = new TEntry('CreditoOriginalTransmissao');
  50. $SelicAcumulada = new TEntry('SelicAcumulada');
  51. $CreditoAtualizado = new TEntry('CreditoAtualizado');
  52. $DebitosDocumento = new TEntry('DebitosDocumento');
  53. $CreditoOriginalUtilizadoDocumento = new TEntry('CreditoOriginalUtilizadoDocumento');
  54. $SaldoCreditoOriginal = new TEntry('SaldoCreditoOriginal');
  55. // $system_unit_id = new TDBSeekButton('system_unit_id', 'permission', $this->form->getName(),'SystemUnit', 'name', 'system_unit_id', 'unit');
  56. // $system_unit = new TEntry('unit');
  57. //$system_unit_id = new TDBCombo('system_unit_id','permission','SystemUnit','id','name');
  58. $Ged = new TFile('Ged');
  59. // complete upload action
  60. $TipoDocumentoDescricao->setEditable(FALSE);
  61. $TipoDocumento_id->setSize('40');
  62. $TipoDocumentoDescricao->setSize('500');
  63. $OrigemDocumentoDescricao->setEditable(FALSE);
  64. $OrigemDocumento_id->setSize('40');
  65. $OrigemDocumentoDescricao->setSize('500');
  66. $TipoCreditoDescricao->setEditable(FALSE);
  67. $TipoCredito_id->setSize('40');
  68. $TipoCreditoDescricao->setSize('500');
  69. $TipoImpostoDescricao->setEditable(FALSE);
  70. $TipoImposto_id->setSize('40');
  71. $TipoImpostoDescricao->setSize('500');
  72. // $system_unit->setEditable(FALSE);
  73. // $system_unit_id->setSize('40');
  74. // $system_unit->setSize('500');
  75. $SaldoDeclarado->setNumericMask(2, ',', '.', TRUE);
  76. $ValorCompensado->setNumericMask(2, ',', '.', TRUE);
  77. $CreditoOriginalInicial->setNumericMask(2, ',', '.', TRUE);
  78. $CreditoOriginalUtilizadoCompensacoes->setNumericMask(2, ',', '.', TRUE);
  79. $CreditoOriginalDisponivel->setNumericMask(2, ',', '.', TRUE);
  80. $CreditoOriginalTransmissao->setNumericMask(2, ',', '.', TRUE);
  81. $SelicAcumulada->setNumericMask(2, ',', '.', TRUE);
  82. $CreditoAtualizado->setNumericMask(2, ',', '.', TRUE);
  83. $DebitosDocumento->setNumericMask(2, ',', '.', TRUE);
  84. $CreditoOriginalUtilizadoDocumento->setNumericMask(2, ',', '.', TRUE);
  85. $SaldoCreditoOriginal->setNumericMask(2, ',', '.', TRUE);
  86. $Nr_Perdcomp->setMask('99999.99999.999999.9.9.99-9999');
  87. $PerdcompOriginal->setMask('99999.99999.999999.9.9.99-9999');
  88. $DataCriacao->setMask('dd/mm/yyyy');
  89. $DataTransmissao->setMask('dd/mm/yyyy');
  90. $Competencia->setMask('dd/mm/yyyy');
  91. // add the fields
  92. $this->form->addQuickField('Código:', $perdcomp_id, 100 );
  93. $this->form->addQuickField('Data Criação:', $DataCriacao, 100 );
  94. $this->form->addQuickField('Data Transmissão:', $DataTransmissao, 100 );
  95. $this->form->addQuickField('Sequencial:', $Sequencial, 200 );
  96. $this->form->addQuickField('Nº Perdcomp:', $Nr_Perdcomp, 200 );
  97. $this->form->addQuickFields('Tipo Documento:', [$TipoDocumento_id,$TipoDocumentoDescricao] );
  98. $this->form->addQuickFields('Origem Documento:', [ $OrigemDocumento_id, $OrigemDocumentoDescricao ] );
  99. $this->form->addQuickFields('Tipo Crédito:', [ $TipoCredito_id, $TipoCreditoDescricao] );
  100. $this->form->addQuickField('Saldo Declarado:', $SaldoDeclarado, 100 );
  101. $this->form->addQuickField('Exercicio:', $Exercicio, 100 );
  102. $this->form->addQuickFields('Tipo Imposto:', [ $TipoImposto_id, $TipoImpostoDescricao] );
  103. $this->form->addQuickField('Valor Compensado:', $ValorCompensado, 100 );
  104. $this->form->addQuickField('Competência:', $Competencia, 100 );
  105. $this->form->addQuickField('Perdcomp Original:', $PerdcompOriginal, 200 );
  106. $this->form->addQuickField('Situação:', $Situacao, 200 );
  107. $this->form->addQuickField('Cancelamento:', $Cancelamento, 200 );
  108. $this->form->addQuickField('Crédito Original Inicial:', $CreditoOriginalInicial, 100 );
  109. $this->form->addQuickField('Crédito Original Utilizado Compensações:', $CreditoOriginalUtilizadoCompensacoes, 100 );
  110. $this->form->addQuickField('Crédito Original Disponível:', $CreditoOriginalDisponivel, 100 );
  111. $this->form->addQuickField('Crédito Original Transmissão:', $CreditoOriginalTransmissao, 100 );
  112. $this->form->addQuickField('Selic Acumulada:', $SelicAcumulada, 100 );
  113. $this->form->addQuickField('Crédito Atualizado:', $CreditoAtualizado, 100 );
  114. $this->form->addQuickField('Débitos Documento:', $DebitosDocumento, 100 );
  115. $this->form->addQuickField('Crédito Original Utilizado Documento:', $CreditoOriginalUtilizadoDocumento, 100 );
  116. $this->form->addQuickField('Saldo Crédito Original:', $SaldoCreditoOriginal, 100);
  117. // $this->form->addQuickFields('Empresa:', [$system_unit_id,$system_unit], new TRequiredValidator);
  118. $this->form->addQuickField('Ged:', $Ged, 500 );
  119. if (!empty($perdcomp_id))
  120. {
  121. $perdcomp_id->setEditable(FALSE);
  122. }
  123. /** samples
  124. $this->form->addQuickFields('Date', array($date1, new TLabel('to'), $date2)); // side by side fields
  125. $fieldX->addValidation( 'Field X', new TRequiredValidator ); // add validation
  126. $fieldX->setSize( 100, 40 ); // set size
  127. **/
  128. // create the form actions
  129. $this->form->addQuickAction(_t('Save'), new TAction(array($this, 'onSave')), 'fa:floppy-o');
  130. $this->form->addQuickAction(_t('New'), new TAction(array($this, 'onEdit')), 'bs:plus-sign green');
  131. $this->form->addQuickAction(_t('Back to the listing'), new TAction(array('PerdcompList', 'onReload')), 'fa:table blue');
  132. // vertical box container
  133. $container = new TVBox;
  134. $container->style = 'width: 90%';
  135. // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  136. $container->add($this->form);
  137. parent::add($container);
  138. }
  139. /**
  140. * Save form data
  141. * @param $param Request
  142. */
  143. public function onSave( $param )
  144. {
  145. try
  146. {
  147. TTransaction::open('perdcomp'); // open a transaction
  148. /**
  149. // Enable Debug logger for SQL operations inside the transaction
  150. TTransaction::setLogger(new TLoggerSTD); // standard output
  151. TTransaction::setLogger(new TLoggerTXT('log.txt')); // file
  152. **/
  153. $this->form->validate(); // validate form data
  154. $object = new Perdcomp; // create an empty object
  155. $data = $this->form->getData(); // get form data as array
  156. $object->fromArray( (array) $data); // load the object with data
  157. $object->DataCriacao = DateTime::createFromFormat('d/m/Y', $object->DataCriacao)->format( 'Y-m-d' );
  158. if (!empty($object->DataTransmissao)) {
  159. $object->DataTransmissao = DateTime::createFromFormat('d/m/Y', $object->DataTransmissao)->format( 'Y-m-d' );
  160. }
  161. if (!empty($object->Competencia)) {
  162. $object->Competencia = DateTime::createFromFormat('d/m/Y', $object->Competencia)->format( 'Y-m-d' );
  163. }
  164. $object->system_user_id = TSession::getvalue('userid');
  165. $user = new SystemUser(TSession::getValue('userod'));
  166. $object->system_unit_id = $user->system_unit_id;
  167. $object->store(); // save the object
  168. // get the generated id
  169. $data->id = $object->id;
  170. $this->form->setData($data); // fill form data
  171. TTransaction::close(); // close the transaction
  172. new TMessage('info', TAdiantiCoreTranslator::translate('Record saved'));
  173. }
  174. catch (Exception $e) // in case of exception
  175. {
  176. new TMessage('error', $e->getMessage()); // shows the exception error message
  177. $this->form->setData( $this->form->getData() ); // keep form data
  178. TTransaction::rollback(); // undo all pending operations
  179. }
  180. if ($object instanceof Perdcomp)
  181. {
  182. $source_file = 'tmp/1/'.$object->Ged;
  183. $target_file = 'images/' . $object->Ged;
  184. $finfo = new finfo(FILEINFO_MIME_TYPE);
  185. // if the user uploaded a source file
  186. if (file_exists($source_file) AND ($finfo->file($source_file) == 'image/pdf'))
  187. {
  188. // move to the target directory
  189. rename($source_file, $target_file);
  190. try
  191. {
  192. TTransaction::open($this->database);
  193. // update the Ged
  194. $object->Ged = 'images/'.$object->Ged;
  195. $object->store();
  196. TTransaction::close();
  197. }
  198. catch (Exception $e) // in case of exception
  199. {
  200. new TMessage('error', $e->getMessage());
  201. TTransaction::rollback();
  202. }
  203. }
  204. }
  205. }
  206. /**
  207. * Clear form data
  208. * @param $param Request
  209. */
  210. public function onClear( $param )
  211. {
  212. $this->form->clear();
  213. }
  214. /**
  215. * Load object to form data
  216. * @param $param Request
  217. */
  218. public function onEdit( $param )
  219. {
  220. try
  221. {
  222. if (isset($param['key']))
  223. {
  224. $key = $param['key']; // get the parameter $key
  225. TTransaction::open('perdcomp'); // open a transaction
  226. $object = new Perdcomp($key); // instantiates the Active Record
  227. $object->DataCriacao = DateTime::createFromFormat('Y-m-d', $object->DataCriacao)->format( 'd/m/Y' );
  228. if (!empty($object->DataTransmissao)) {
  229. $object->DataTransmissao = DateTime::createFromFormat('Y-m-d', $object->DataTransmissao)->format( 'd/m/Y' );
  230. }
  231. if (!empty($object->Competencia)) {
  232. $object->Competencia = DateTime::createFromFormat('Y-m-d', $object->Competencia)->format( 'd/m/Y' );
  233. }
  234. $this->form->setData($object); // fill the form
  235. TTransaction::close(); // close the transaction
  236. }
  237. else
  238. {
  239. $this->form->clear();
  240. }
  241. }
  242. catch (Exception $e) // in case of exception
  243. {
  244. new TMessage('error', $e->getMessage()); // shows the exception error message
  245. TTransaction::rollback(); // undo all pending operations
  246. }
  247. }
  248. }
  249. Datagrid:
 
  1. <?php
  2. /**
  3. * PerdcompList Listing
  4. * @author <your name here>
  5. */
  6. class PerdcompList extends TStandardList
  7. {
  8. protected $form; // registration form
  9. protected $datagrid; // listing
  10. protected $pageNavigation;
  11. protected $formgrid;
  12. protected $deleteButton;
  13. protected $transformCallback;
  14. /**
  15. * Page constructor
  16. */
  17. public function __construct()
  18. {
  19. parent::__construct();
  20. parent::setDatabase('perdcomp'); // defines the database
  21. parent::setActiveRecord('Perdcomp'); // defines the active record
  22. parent::setDefaultOrder('perdcomp_id', 'asc'); // defines the default order
  23. // parent::setCriteria($criteria) // define a standard filter
  24. parent::addFilterField('perdcomp_id', '=', 'perdcomp_id'); // filterField, operator, formField
  25. parent::addFilterField('DataCriacao', 'like', 'DataCriacao'); // filterField, operator, formField
  26. parent::addFilterField('DataTransmissao', 'like', 'DataTransmissao'); // filterField, operator, formField
  27. parent::addFilterField('Sequencial', 'like', 'Sequencial'); // filterField, operator, formField
  28. parent::addFilterField('Nr_Perdcomp', 'like', 'Nr_Perdcomp'); // filterField, operator, formField
  29. parent::addFilterField('TipoDocumento_id', 'like', 'TipoDocumento_id'); // filterField, operator, formField
  30. parent::addFilterField('OrigemDocumento_id', 'like', 'OrigemDocumento_id'); // filterField, operator, formField
  31. parent::addFilterField('TipoCredito_id', 'like', 'TipoCredito_id'); // filterField, operator, formField
  32. parent::addFilterField('SaldoDeclarado', 'like', 'SaldoDeclarado'); // filterField, operator, formField
  33. parent::addFilterField('Exercicio', 'like', 'Exercicio'); // filterField, operator, formField
  34. parent::addFilterField('TipoImposto_id', 'like', 'TipoImposto_id'); // filterField, operator, formField
  35. // creates the form
  36. $this->form = new TQuickForm('form_search_Perdcomp');
  37. $this->form->class = 'tform'; // change CSS class
  38. $this->form->style = 'display: table;width:100%'; // change style
  39. $this->form->setFormTitle('Filtro Perdcomp');
  40. // create the form fields
  41. $perdcomp_id = new TEntry('perdcomp_id');
  42. $DataCriacao = new TDate('DataCriacao');
  43. $DataTransmissao = new TDate('DataTransmissao');
  44. $Nr_Perdcomp = new TEntry('Nr_Perdcomp');
  45. $TipoDocumento_id = new ">TDBSeekButton('TipoDocumento_id', 'perdcomp', $this->form->getName(), 'TipoDocumento', 'TipoDocumentoDescricao', 'TipoDocumento_id', 'tipo_documento');
  46. $TipoDocumentoDescricao = new TEntry('tipo_documento');
  47. $TipoCredito_id = new ">TDBSeekButton('TipoCredito_id', 'perdcomp', $this->form->getName(), 'TipoCredito', 'TipoCreditoDescricao', 'TipoCredito_id', 'tipo_credito');
  48. $TipoCreditoDescricao = new TEntry('tipo_credito');
  49. $OrigemDocumento_id = new ">TDBSeekButton('OrigemDocumento_id', 'perdcomp', $this->form->getName(), 'OrigemDocumento', 'OrigemDocumentoDescricao', 'OrigemDocumento_id', 'origem_documento');
  50. $OrigemDocumentoDescricao = new TEntry('origem_documento');
  51. $TipoImposto_id = new ">TDBSeekButton('TipoImposto_id', 'perdcomp', $this->form->getName(), 'TipoImposto', 'TipoImpostoDescricao', 'TipoImposto_id', 'tipo_imposto');
  52. $TipoImpostoDescricao = new TEntry('tipo_imposto');
  53. $Exercicio = new TEntry('Exercicio');
  54. $TipoDocumentoDescricao->setEditable(FALSE);
  55. $TipoDocumento_id->setSize('40');
  56. $TipoDocumentoDescricao->setSize('500');
  57. $TipoCreditoDescricao->setEditable(FALSE);
  58. $TipoCredito_id->setSize('40');
  59. $TipoCreditoDescricao->setSize('500');
  60. $OrigemDocumentoDescricao->setEditable(FALSE);
  61. $OrigemDocumento_id->setSize('40');
  62. $OrigemDocumentoDescricao->setSize('500');
  63. $TipoImpostoDescricao->setEditable(FALSE);
  64. $TipoImposto_id->setSize('40');
  65. $TipoImpostoDescricao->setSize('500');
  66. // add the fields
  67. $this->form->addQuickField('Código:', $perdcomp_id, 80 );
  68. $this->form->addQuickField('Data Criação', $DataCriacao, 80 );
  69. $this->form->addQuickField('Data Transmissão:', $DataTransmissao, 80 );
  70. $this->form->addQuickField('Nº Perdcomp:', $Nr_Perdcomp, 500 );
  71. $this->form->addQuickFields('Tipo Documento:', [ $TipoDocumento_id, $TipoDocumentoDescricao ] );
  72. $this->form->addQuickFields('Tipo Crédito:', [ $TipoCredito_id, $TipoCreditoDescricao] );
  73. $this->form->addQuickFields('Origem Documento:', [ $OrigemDocumento_id, $OrigemDocumentoDescricao ] );
  74. $this->form->addQuickFields('Tipo Imposto:', [ $TipoImposto_id, $TipoImpostoDescricao] );
  75. $this->form->addQuickField('Exercício', $Exercicio, 100 );
  76. // keep the form filled during navigation with session data
  77. $this->form->setData( TSession::getValue('Perdcomp_filter_data') );
  78. // add the search form actions
  79. $this->form->addQuickAction(_t('Find'), new TAction(array($this, 'onSearch')), 'fa:search');
  80. $this->form->addQuickAction(_t('New'), new TAction(array('PerdcompForm', 'onEdit')), 'bs:plus-sign green');
  81. // creates a DataGrid
  82. $this->datagrid = new TDataGrid;
  83. // $this->datagrid->enablePopover('Image', "<img src='{photo_path}'>");
  84. $this->datagrid->style = 'width: 100%';
  85. $this->datagrid->datatable = 'true';
  86. // $this->datagrid->enablePopover('Popover', 'Hi <b> {name} </b>');
  87. // creates the datagrid columns
  88. $column_check = new TDataGridColumn('check', '', 'center');
  89. $column_perdcomp_id = new TDataGridColumn('perdcomp_id', 'Código', 'right');
  90. $column_DataCriacao = new TDataGridColumn('DataCriacao', 'Data Criação', 'left');
  91. $column_DataTransmissao = new TDataGridColumn('DataTransmissao', 'Data Transmissão', 'left');
  92. $column_Nr_Perdcomp = new TDataGridColumn('Nr_Perdcomp', 'Nº Perdcomp', 'left');
  93. $column_TipoDocumento_id = new TDataGridColumn('tipo_documento', 'Tipo Documento', 'left');
  94. $column_TipoCredito_id = new TDataGridColumn('tipo_credito', 'Tipo Crédito', 'left');
  95. $column_TipoImposto_id = new TDataGridColumn('tipo_imposto', 'Tipo Imposto', 'left');
  96. $column_OrigemDocumento_id = new TDataGridColumn('origem_documento', 'Origem Documento', 'left');
  97. $column_SaldoDeclarado = new TDataGridColumn('SaldoDeclarado', 'Saldo Declarado', 'right');
  98. $column_Exercicio = new TDataGridColumn('Exercicio', 'Exercício', 'right');
  99. $column_ValorCompensado = new TDataGridColumn('ValorCompensado', 'Valor Compensado', 'right');
  100. $column_Sequencial = new TDataGridColumn('Sequencial', 'Sequencial', 'left');
  101. $column_Competencia = new TDataGridColumn('Competencia', 'Competência', 'left');
  102. $column_PerdcompOriginal = new TDataGridColumn('PerdcompOriginal', 'Perdcomp Original', 'left');
  103. $column_Situacao = new TDataGridColumn('Situacao', 'Situação', 'left');
  104. $column_Cancelamento = new TDataGridColumn('Cancelamento', 'Cancelamento', 'left');
  105. $column_CreditoOriginalInicial = new TDataGridColumn('CreditoOriginalInicial', 'Crédito Original Inicial', 'right');
  106. $column_CreditoOriginalUtilizadoCompensacoes = new TDataGridColumn('Credito Original Utilizado Compensações', 'Creditooriginalutilizadocompensacoes', 'right');
  107. $column_CreditoOriginalDisponivel = new TDataGridColumn('Crédito Original Disponível', 'Crédito Original Disponível', 'right');
  108. $column_CreditoOriginalTransmissao = new TDataGridColumn('Credito Original Transmissão', 'Crédito Original Transmissão', 'right');
  109. $column_SelicAcumulada = new TDataGridColumn('Selic Acumulada', 'Selic Acumulada', 'right');
  110. $column_CreditoAtualizado = new TDataGridColumn('CreditoAtualizado', 'Crédito Atualizado', 'right');
  111. $column_DebitosDocumento = new TDataGridColumn('DebitosDocumento', 'Débitos Documento', 'right');
  112. $column_CreditoOriginalUtilizadoDocumento = new TDataGridColumn('CreditoOriginalUtilizadoDocumento', 'Crédito Original Utilizado Documento', 'right');
  113. $column_SaldoCreditoOriginal = new TDataGridColumn('SaldoCreditoOriginal', 'Saldo Crédito Original', 'right');
  114. $column_system_unit_id = new TDataGridColumn('system_unit_id', 'Empresa', 'right');
  115. $column_Ged = new TDataGridColumn('Ged', 'Ged', 'left');
  116. // add the columns to the DataGrid
  117. $this->datagrid->addColumn($column_check);
  118. $this->datagrid->addColumn($column_perdcomp_id);
  119. $this->datagrid->addColumn($column_DataCriacao);
  120. $this->datagrid->addColumn($column_DataTransmissao);
  121. $this->datagrid->addColumn($column_Sequencial);
  122. $this->datagrid->addColumn($column_Nr_Perdcomp);
  123. $this->datagrid->addColumn($column_TipoDocumento_id);
  124. $this->datagrid->addColumn($column_OrigemDocumento_id);
  125. $this->datagrid->addColumn($column_TipoCredito_id);
  126. $this->datagrid->addColumn($column_TipoImposto_id);
  127. $this->datagrid->addColumn($column_SaldoDeclarado);
  128. $this->datagrid->addColumn($column_ValorCompensado);
  129. $this->datagrid->addColumn($column_Exercicio);
  130. $this->datagrid->addColumn($column_Competencia);
  131. $this->datagrid->addColumn($column_PerdcompOriginal);
  132. $this->datagrid->addColumn($column_Situacao);
  133. $this->datagrid->addColumn($column_Cancelamento);
  134. $this->datagrid->addColumn($column_CreditoOriginalInicial);
  135. $this->datagrid->addColumn($column_CreditoOriginalUtilizadoCompensacoes);
  136. $this->datagrid->addColumn($column_CreditoOriginalDisponivel);
  137. $this->datagrid->addColumn($column_CreditoOriginalTransmissao);
  138. $this->datagrid->addColumn($column_SelicAcumulada);
  139. $this->datagrid->addColumn($column_CreditoAtualizado);
  140. $this->datagrid->addColumn($column_DebitosDocumento);
  141. $this->datagrid->addColumn($column_CreditoOriginalUtilizadoDocumento);
  142. $this->datagrid->addColumn($column_SaldoCreditoOriginal);
  143. $this->datagrid->addColumn($column_Ged);
  144. $this->datagrid->addColumn($column_system_unit_id);
  145. $order_perdcomp_id = new TAction(array($this, 'onReload'));
  146. $order_perdcomp_id->setParameter('order', 'perdcomp_id');
  147. $column_perdcomp_id->setAction($order_perdcomp_id);
  148. $order_DataCriacao = new TAction(array($this, 'onReload'));
  149. $order_DataCriacao->setParameter('order', 'DataCriacao');
  150. $column_DataCriacao->setAction($order_DataCriacao);
  151. $order_DataTransmissao = new TAction(array($this, 'onReload'));
  152. $order_DataTransmissao->setParameter('order', 'DataTransmissao');
  153. $column_DataTransmissao->setAction($order_DataTransmissao);
  154. // define the transformer method over image
  155. $column_Ged->setTransformer(function($value, $object, $row){
  156. $link = new THyperLink($value,'tmp/1/' . $value, 'blue', 12, 'biu');
  157. return $link;
  158. });
  159. $column_Competencia->setTransformer( function($value, $object, $row) {
  160. $date = new DateTime($value);
  161. return $date->format('d/m/Y');
  162. });
  163. // define the transformer method over image
  164. $column_DataCriacao->setTransformer( function($value, $object, $row) {
  165. $date = new DateTime($value);
  166. return $date->format('d/m/Y');
  167. });
  168. // define the transformer method over image
  169. $column_DataTransmissao->setTransformer( function($value, $object, $row) {
  170. $date = new DateTime($value);
  171. return $date->format('d/m/Y');
  172. });
  173. // define the transformer method over image
  174. $column_SaldoDeclarado->setTransformer( function($value, $object, $row) {
  175. return 'R$ ' . number_format($value, 2, ',', '.');
  176. });
  177. // define the transformer method over image
  178. $column_ValorCompensado->setTransformer( function($value, $object, $row) {
  179. return 'R$ ' . number_format($value, 2, ',', '.');
  180. });
  181. // define the transformer method over image
  182. $column_CreditoOriginalInicial->setTransformer( function($value, $object, $row) {
  183. return 'R$ ' . number_format($value, 2, ',', '.');
  184. });
  185. // define the transformer method over image
  186. $column_CreditoOriginalUtilizadoCompensacoes->setTransformer( function($value, $object, $row) {
  187. return 'R$ ' . number_format($value, 2, ',', '.');
  188. });
  189. // define the transformer method over image
  190. $column_CreditoOriginalDisponivel->setTransformer( function($value, $object, $row) {
  191. return 'R$ ' . number_format($value, 2, ',', '.');
  192. });
  193. // define the transformer method over image
  194. $column_CreditoOriginalTransmissao->setTransformer( function($value, $object, $row) {
  195. return 'R$ ' . number_format($value, 2, ',', '.');
  196. });
  197. // define the transformer method over image
  198. $column_CreditoAtualizado->setTransformer( function($value, $object, $row) {
  199. return 'R$ ' . number_format($value, 2, ',', '.');
  200. });
  201. // define the transformer method over image
  202. $column_DebitosDocumento->setTransformer( function($value, $object, $row) {
  203. return 'R$ ' . number_format($value, 2, ',', '.');
  204. });
  205. // define the transformer method over image
  206. $column_CreditoOriginalUtilizadoDocumento->setTransformer( function($value, $object, $row) {
  207. return 'R$ ' . number_format($value, 2, ',', '.');
  208. });
  209. // define the transformer method over image
  210. $column_SaldoCreditoOriginal->setTransformer( function($value, $object, $row) {
  211. return 'R$ ' . number_format($value, 2, ',', '.');
  212. });
  213. // create EDIT action
  214. $action_edit = new TDataGridAction(array('PerdcompForm', 'onEdit'));
  215. $action_edit->setButtonClass('btn btn-default');
  216. $action_edit->setLabel(_t('Edit'));
  217. $action_edit->setImage('fa:pencil-square-o blue fa-lg');
  218. $action_edit->setField('perdcomp_id');
  219. $this->datagrid->addAction($action_edit);
  220. // create DELETE action
  221. $action_del = new TDataGridAction(array($this, 'onDelete'));
  222. $action_del->setButtonClass('btn btn-default');
  223. $action_del->setLabel(_t('Delete'));
  224. $action_del->setImage('fa:trash-o red fa-lg');
  225. $action_del->setField('perdcomp_id');
  226. $this->datagrid->addAction($action_del);
  227. // create the datagrid model
  228. $this->datagrid->createModel();
  229. // create the page navigation
  230. $this->pageNavigation = new TPageNavigation;
  231. $this->pageNavigation->setAction(new TAction(array($this, 'onReload')));
  232. $this->pageNavigation->setWidth($this->datagrid->getWidth());
  233. $this->datagrid->disableDefaultClick();
  234. // put datagrid inside a form
  235. $this->formgrid = new TForm;
  236. $this->formgrid->add($this->datagrid);
  237. // creates the delete collection button
  238. $this->deleteButton = new TButton('delete_collection');
  239. $this->deleteButton->setAction(new TAction(array($this, 'onDeleteCollection')), AdiantiCoreTranslator::translate('Delete selected'));
  240. $this->deleteButton->setImage('fa:remove red');
  241. $this->formgrid->addField($this->deleteButton);
  242. $gridpack = new TVBox;
  243. $gridpack->style = 'width: 100%';
  244. $gridpack->add($this->formgrid);
  245. $gridpack->add($this->deleteButton)->style = 'background:whiteSmoke;border:1px solid #cccccc; padding: 3px;padding: 5px;';
  246. $this->transformCallback = array($this, 'onBeforeLoad');
  247. // vertical box container
  248. $container = new TVBox;
  249. $container->style = 'width: 90%';
  250. // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  251. $container->add($this->form);
  252. // $container->add($this->datagrid);
  253. $container->add($gridpack);
  254. $container->add($this->pageNavigation);
  255. parent::add($container);
  256. }
  257. public function onBeforeLoad($objects, $param)
  258. {
  259. // update the action parameters to pass the current page to action
  260. // without this, the action will only work for the first page
  261. $deleteAction = $this->deleteButton->getAction();
  262. $deleteAction->setParameters($param); // important!
  263. $gridfields = array( $this->deleteButton );
  264. foreach ($objects as $object)
  265. {
  266. $object->check = new TCheckButton('check' . $object->perdcomp_id);
  267. $object->check->setIndexValue('on');
  268. $gridfields[] = $object->check; // important
  269. }
  270. $this->formgrid->setFields($gridfields);
  271. }
  272. }
  273. </your></your>
ST

Marcelo,

O usuário está gravando no banco de dados, apenas a unidade não está gravando.
MG

Bom dia.

Dá uma olhada no seu código.

O "userid" está errado quando tentar buscar os dados, veja parte do seu código abaixo, você usou "userod".

 
  1. <?php
  2. $object->system_user_id = TSession::getvalue('userid');
  3. $user = new SystemUser(TSession::getValue('userod')); // <==== correto é "userid"
  4. $object->system_unit_id = $user->system_unit_id;
  5. ?>
ST

Marcelo,

Problema resolvido. Muitíssimo obrigado.

Gostaria de filtrar os dados do datagrid pela unidade, como faço isto?
MG

Você usa TCriteria no método onReload.

Quando você cria um TDataGrid pelo Adianti Studio ele cria um método onReload.

Neste método existe alguns filtros que podem vir da tela de pesquisa básica que ele criar.

Modifique este método e adicione os critérios desejados.
ST

Marcelo,
Este é o meu primeiro projeto.
Não sei ainda como utilizar o Tcriteria.
Poderia, por favor, me passaram um exemplo.
MG

Sebastião, vai um trecho de código a respeito deste assunto.
Trata-se de um método onReload().

Neste caso seu model contém o campo "system_group_id", correto e tão vamos ao método e uso do TCriteria.

 
  1. <?php
  2. /**
  3. * Load the datagrid with data
  4. */
  5. public function onReload($param = NULL)
  6. {
  7. try
  8. {
  9. // open a transaction with database 'moto'
  10. TTransaction::open('moto');
  11. // creates a repository for TipoDespesas
  12. $repository = new TRepository('TipoDespesas');
  13. $limit = 10;
  14. // creates a criteria
  15. $criteria = new TCriteria;
  16. // default order
  17. if (empty($param['order']))
  18. {
  19. $param['order'] = 'id';
  20. $param['direction'] = 'asc';
  21. }
  22. $criteria->setProperties($param); // order, offset
  23. $criteria->setProperty('limit', $limit);
  24. if (TSession::getValue('TipoDespesas_filter'))
  25. {
  26. // add the filter stored in the session to the criteria
  27. $criteria->add(TSession::getValue('TipoDespesas_filter'));
  28. }
  29. // filtra por grupo
  30. $criteria-add("system_group_id","=",$param['system_group_id']); // aqui vc adiciona o TCriteria que deve valer para todo o TDataGrid
  31. // load the objects according to criteria
  32. $objects = $repository->load($criteria, FALSE);
  33. $this->datagrid->clear();
  34. if ($objects)
  35. {
  36. // iterate the collection of active records
  37. foreach ($objects as $object)
  38. {
  39. // add the object inside the datagrid
  40. $this->datagrid->addItem($object);
  41. }
  42. }
  43. // reset the criteria for record count
  44. $criteria->resetProperties();
  45. $count= $repository->count($criteria);
  46. $this->pageNavigation->setCount($count); // count of records
  47. $this->pageNavigation->setProperties($param); // order, page
  48. $this->pageNavigation->setLimit($limit); // limit
  49. // close the transaction
  50. TTransaction::close();
  51. $this->loaded = true;
  52. }
  53. catch (Exception $e) // in case of exception
  54. {
  55. // shows the exception error message
  56. new TMessage('error', '<b>Error</b> ' . $e->getMessage());
  57. // undo all pending operations
  58. TTransaction::rollback();
  59. }
  60. }
  61. ?>
MG

Veja na linha 35.
Vc deve localizar seu método onReload e implementar o TCriteria.
ST

Marcelo,
No formulário do datagrid não tem o método on Reload.
Tem o método onBeforeLoad.
MG

Implemente nele.
Literalmente o método diz "Antes de Ler".
ST

Problema resolvido.
Obrigado Marcelo.