Cálculo entre duas datas Pessoal, Tenho um campo de DATA INICIAL ($safinicial), um de DATA FINAL ($saffinal) e um outro que vai receber o RESULTADO ($safdia), sendo este último um TEntry (ver o código PHP abaixo). Criei o método abaixo e no momento de executar a aplicação está mostrando um erro na tela e também um erro de PHP. Alguém pode me ajudar? ...
HB
Cálculo entre duas datas  
Pessoal,
Tenho um campo de DATA INICIAL ($safinicial), um de DATA FINAL ($saffinal) e um outro que vai receber o RESULTADO ($safdia), sendo este último um TEntry (ver o código PHP abaixo).
Criei o método abaixo e no momento de executar a aplicação está mostrando um erro na tela e também um erro de PHP.
Alguém pode me ajudar?

 
  1. <?php
  2. public static function onDiaSafra($param)
  3. {
  4. try
  5. {
  6. if ($param['key'])
  7. {
  8. TTransaction::open('safra');
  9. $safra = new Safra ($param['key']);
  10. TTransaction::close();
  11. }
  12. if ($safra) // NESTE PONTO É A LINHA 105 DO ERRO PHP.
  13. {
  14. $safinicial = new DateTime($param['safinicial']);
  15. $saffinal = new DateTime($param['saffinal']);
  16. $object = new stdClass();
  17. $object->safdia = $safinicial->diff($saffinal);
  18. TForm::sendData(self::$formName, $object);
  19. }
  20. }
  21. catch (Exception $e)
  22. {
  23. new TMessage('error', $e->getMessage());
  24. }
  25. }
  26. ?>


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


MG

Tem algo estranho no fechamento dos b locos!
Veja que você isola a variável $safra na condição de existir um $param['key'].
Se não existir, então a variável $safra não existe, dando o erro na linha mencionada.
Eu arrumaria tudo da seguinte forma:

 
  1. <?php
  2. public static function onDiaSafra($param)
  3. {
  4. try
  5. {
  6. if ($param['key'])
  7. {
  8. TTransaction::open('safra');
  9. $safra = new Safra ($param['key']);
  10. TTransaction::close();
  11. if ($safra) // NESTE PONTO É A LINHA 105 DO ERRO PHP.
  12. {
  13. $safinicial = new DateTime($param['safinicial']);
  14. $saffinal = new DateTime($param['saffinal']);
  15. $object = new stdClass();
  16. $object->safdia = $safinicial->diff($saffinal);
  17. TForm::sendData(self::$formName, $object);
  18. }
  19. }
  20. }
  21. catch (Exception $e)
  22. {
  23. new TMessage('error', $e->getMessage());
  24. }
  25. }
  26. ?>

HB

Marcelo, agradeço pela ajuda.
Em relação ao erro PHP, você está certo, fiz o fechamento da chave erro, e tem hora que passa o "olho" tantas vezes no código que não consegue enxergar o óbvio, mais uma vez obrigado.

A action fica no campo de DATA FINAL ($saffinal), e quando seleciono a data, emite a mensagem de exceção tratada pelo próprio framework abaixo:
Objeto 31/01/2018 não encontrado em safra
Sabe o que pode ser?
MG

Faz o seguinte.
Dá um var_dump no $param, no início da action.
Veja que valor está vindo em "key"!
HB

Marcelo, dá uma olhada aí

/var/www/controle_de_safra/app/control/cadastros/SafraForm.php:101:
array (size=18)
'class' => string 'SafraForm' (length=9)
'method' => string 'onDiaSafra' (length=10)
'static' => string '1' (length=1)
'id' => string '' (length=0)
'safra' => string '2017' (length=4)
'descricao' => string '2017/2017' (length=9)
'safinicial' => string '01/01/2018' (length=10)
'saffinal' => string '22/01/2018' (length=10)
'safdia' => string '' (length=0)
'indireta' => string '' (length=0)
'encerrada' => string '' (length=0)
'_field_value' => string '22/01/2018' (length=10)
'_field_id' => string 'tdate_1875487402' (length=16)
'_field_name' => string 'saffinal' (length=8)
'_form_name' => string 'list_Safra' (length=10)
'_field_data' => string 'plugin_bootstrapMaterialDatePicker=%5Bobject%20Object%5D&dtp=dtp_pSUZg' (length=70)
'key' => string '22/01/2018' (length=10)
'ajax_lookup' => string '1' (length=1)
MG

José
Se sua chave é uma data, ela está no formato errado, deveria ser "2018-01-22".
Geralmente "key" deveria vir a primary key da tabela.
Sua primary key é a data?
HB

Não. É o próprio id gerado pelo framework. Veja minha model Safra.class.php

 
  1. <?php
  2. class Safra extends TRecord
  3. {
  4. const TABLENAME = 'safra';
  5. const PRIMARYKEY = 'id';
  6. const IDPOLICY = 'serial'; // {max, serial}
  7. /**
  8. * Constructor method
  9. */
  10. public function __construct($id = NULL, $callObjectLoad = TRUE)
  11. {
  12. parent::__construct($id, $callObjectLoad);
  13. parent::addAttribute('safra');
  14. parent::addAttribute('descricao');
  15. parent::addAttribute('safinicial');
  16. parent::addAttribute('saffinal');
  17. parent::addAttribute('indireta');
  18. parent::addAttribute('safdia');
  19. parent::addAttribute('encerrada');
  20. }
  21. /**
  22. * Method getDespesas
  23. */
  24. public function getDespesas()
  25. {
  26. $criteria = new TCriteria;
  27. $criteria->add(new TFilter('safra_id', '=', $this->id));
  28. return Despesa::getObjects( $criteria );
  29. }
  30. }
  31. ?>
MG

José
Tudo bem, mas algo no seu "__construct" mudou isso.
Pois é possível definir no construct os parâmetros enviados para uma action.
Vasculhe seu "__construct" ou poste para podermos ajudar.
HB

Veja o código Marcelo.

 
  1. <?php
  2. /**
  3. * SafraForm Form
  4. * @author <your name here>
  5. */
  6. class SafraForm extends TPage
  7. {
  8. protected $form; // form
  9. private $formFields = [];
  10. private static $database = 'safra';
  11. private static $activeRecord = 'Safra';
  12. private static $primaryKey = 'id';
  13. private static $formName = 'list_Safra';
  14. /**
  15. * Form constructor
  16. * @param $param Request
  17. */
  18. public function __construct( $param )
  19. {
  20. parent::__construct();
  21. // creates the form
  22. $this->form = new BootstrapFormBuilder(self::$formName);
  23. // define the form title
  24. $this->form->setFormTitle('Cadastro de Safra');
  25. $id = new TEntry('id');
  26. $safra = new TEntry('safra');
  27. $descricao = new TEntry('descricao');
  28. $safinicial = new TDate('safinicial');
  29. $saffinal = new TDate('saffinal');
  30. $safdia = new TEntry('safdia');
  31. $indireta = new TNumeric('indireta', '2', ',', '.' );
  32. $encerrada = new TCombo('encerrada');
  33. $saffinal->setExitAction(new TAction([$this,'onDiaSafra']));
  34. $safra->addValidation('Safra', new TRequiredValidator());
  35. $descricao->addValidation('Descrição', new TRequiredValidator());
  36. $safinicial->addValidation('Início de Safra', new TRequiredValidator());
  37. $saffinal->addValidation('Final de Safra', new TRequiredValidator());
  38. $encerrada->addValidation('Safra Encerrada', new TRequiredValidator());
  39. $descricao->forceUpperCase();
  40. $encerrada->addItems(['1'=>'Sim','2'=>'Não']);
  41. $id->setEditable(false);
  42. $safdia->setEditable(false);
  43. $saffinal->setDatabaseMask('yyyy-mm-dd');
  44. $safinicial->setDatabaseMask('yyyy-mm-dd');
  45. $encerrada->setTip("Indique se a safra está encerrada.");
  46. $indireta->setTip("Informe o percentual de acréscimo para despesa indireta.");
  47. $safra->setMask('9999');
  48. $safdia->setMask('99999');
  49. $saffinal->setMask('dd/mm/yyyy');
  50. $safinicial->setMask('dd/mm/yyyy');
  51. $id->setSize(70);
  52. $safra->setSize('25%');
  53. $saffinal->setSize(150);
  54. $safdia->setSize('42%');
  55. $safinicial->setSize(150);
  56. $indireta->setSize('40%');
  57. $encerrada->setSize('26%');
  58. $descricao->setSize('100%');
  59. $this->form->addFields([new TLabel('Id')],[$id]);
  60. $this->form->addFields([new TLabel('Safra')],[$safra],[],[]);
  61. $this->form->addFields([new TLabel('Descrição')],[$descricao],[],[]);
  62. $this->form->addFields([new TLabel('Início da Safra')],[$safinicial],[new TLabel('Final da Safra')],[$saffinal]);
  63. $this->form->addFields([new TLabel('Dias de Safra')],[$safdia],[new TLabel('Despesa Indireta')],[$indireta]);
  64. $this->form->addFields([new TLabel('Safra Encerrada')],[$encerrada],[],[]);
  65. // create the form actions
  66. $btn_onsave = $this->form->addAction('Salvar', new TAction([$this, 'onSave']), 'fa:floppy-o #000000');
  67. $btn_onclear = $this->form->addAction('Novo', new TAction([$this, 'onClear']), 'fa:edit #000000');
  68. $btn_onshow = $this->form->addAction('Retornar', new TAction(['SafraList', 'onShow']), 'fa:reply #000000');
  69. // vertical box container
  70. $container = new TVBox;
  71. $container->style = 'width: 100%';
  72. $container->class = 'form-container';
  73. // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  74. $container->add($this->form);
  75. parent::add($container);
  76. }
  77. public static function onDiaSafra($param = null)
  78. {
  79. try
  80. {
  81. if ($param['key'])
  82. {
  83. var_dump ($param);
  84. TTransaction::open('safra');
  85. $safra = new Safra ($param['key']);
  86. TTransaction::close();
  87. if ($safra)
  88. {
  89. $safinicial = new DateTime($param['safinicial']);
  90. $saffinal = new DateTime($param['saffinal']);
  91. $object = new stdClass();
  92. $object->safdia = $safinicial->diff($saffinal);
  93. TForm::sendData(self::$formName, $object);
  94. }
  95. }
  96. //</autoCode>
  97. }
  98. catch (Exception $e)
  99. {
  100. new TMessage('error', $e->getMessage());
  101. }
  102. }
  103. public function onSave($param = null)
  104. {
  105. try
  106. {
  107. TTransaction::open(self::$database); // open a transaction
  108. /**
  109. // Enable Debug logger for SQL operations inside the transaction
  110. TTransaction::setLogger(new TLoggerSTD); // standard output
  111. TTransaction::setLogger(new TLoggerTXT('log.txt')); // file
  112. **/
  113. $messageAction = null;
  114. $this->form->validate(); // validate form data
  115. $object = new Safra(); // create an empty object
  116. $data = $this->form->getData(); // get form data as array
  117. $object->fromArray( (array) $data); // load the object with data
  118. $object->store(); // save the object
  119. // get the generated {PRIMARY_KEY}
  120. $data->id = $object->id;
  121. $this->form->setData($data); // fill form data
  122. TTransaction::close(); // close the transaction
  123. /**
  124. // To define an action to be executed on the message close event:
  125. $messageAction = new TAction(['className', 'methodName']);
  126. **/
  127. new TMessage('info', AdiantiCoreTranslator::translate('Record saved'), $messageAction);
  128. }
  129. catch (Exception $e) // in case of exception
  130. {
  131. new TMessage('error', $e->getMessage()); // shows the exception error message
  132. $this->form->setData( $this->form->getData() ); // keep form data
  133. TTransaction::rollback(); // undo all pending operations
  134. }
  135. }
  136. /**
  137. * Clear form data
  138. * @param $param Request
  139. */
  140. public function onClear( $param )
  141. {
  142. $this->form->clear();
  143. }
  144. public function onEdit( $param )
  145. {
  146. try
  147. {
  148. if (isset($param['key']))
  149. {
  150. $key = $param['key']; // get the parameter $key
  151. TTransaction::open(self::$database); // open a transaction
  152. $object = new Safra($key); // instantiates the Active Record
  153. $this->form->setData($object); // fill the form
  154. TTransaction::close(); // close the transaction
  155. }
  156. else
  157. {
  158. $this->form->clear();
  159. }
  160. }
  161. catch (Exception $e) // in case of exception
  162. {
  163. new TMessage('error', $e->getMessage()); // shows the exception error message
  164. TTransaction::rollback(); // undo all pending operations
  165. }
  166. }
  167. public function onShow()
  168. {
  169. }
  170. }
  171. ?>
MG

José,
Este form é chamado de um "list", certo?
Como está sendo passado o "key" do list para o "form"?
HB

Dá uma olhada na List

 
  1. <?php
  2. /**
  3. * SafraList Listing
  4. * @author <your name here>
  5. */
  6. class SafraList extends TPage
  7. {
  8. private $form; // form
  9. private $datagrid; // listing
  10. private $pageNavigation;
  11. private $formgrid;
  12. private $loaded;
  13. private $deleteButton;
  14. private static $database = 'safra';
  15. private static $activeRecord = 'Safra';
  16. private static $primaryKey = 'id';
  17. private static $formName = 'form_Safra';
  18. /**
  19. * Class constructor
  20. * Creates the page, the form and the listing
  21. */
  22. public function __construct()
  23. {
  24. parent::__construct();
  25. // creates the form
  26. $this->form = new BootstrapFormBuilder(self::$formName);
  27. // define the form title
  28. $this->form->setFormTitle('Safra');
  29. $id = new TEntry('id');
  30. $safra = new TEntry('safra');
  31. $descricao = new TEntry('descricao');
  32. $encerrada = new TCombo('encerrada');
  33. $encerrada->addItems(['1'=>'Sim','2'=>'Não']);
  34. $id->setSize('30%');
  35. $safra->setSize('30%');
  36. $encerrada->setSize('25%');
  37. $descricao->setSize('100%');
  38. $this->form->addFields([new TLabel('Id')],[$id],[],[]);
  39. $this->form->addFields([new TLabel('Safra')],[$safra],[],[]);
  40. $this->form->addFields([new TLabel('Descrição')],[$descricao],[],[]);
  41. $this->form->addFields([new TLabel('Safra Encerrada')],[$encerrada],[],[]);
  42. // keep the form filled during navigation with session data
  43. $this->form->setData( TSession::getValue(__CLASS__.'_filter_data') );
  44. $btn_onsearch = $this->form->addAction('Buscar', new TAction([$this, 'onSearch']), 'fa:search #000000');
  45. $btn_onexportcsv = $this->form->addAction('Exportar CSV', new TAction([$this, 'onExportCsv']), 'fa:file-excel-o #000000');
  46. $btn_onshow = $this->form->addAction('Cadastrar', new TAction(['SafraForm', 'onShow']), 'fa:plus #000000');
  47. // creates a Datagrid
  48. $this->datagrid = new TDataGrid;
  49. $this->datagrid = new BootstrapDatagridWrapper($this->datagrid);
  50. $this->datagrid->style = 'width: 100%';
  51. $this->datagrid->setHeight(320);
  52. $column_id = new TDataGridColumn('id', 'Id', 'center' , '110.25px');
  53. $column_safra = new TDataGridColumn('safra', 'Safra', 'center');
  54. $column_descricao = new TDataGridColumn('descricao', 'Descrição', 'left');
  55. $column_safinicial_transformed = new TDataGridColumn('safinicial', 'Início da Safra', 'center');
  56. $column_saffinal_transformed = new TDataGridColumn('saffinal', 'Final da Safra', 'center');
  57. $column_safdia = new TDataGridColumn('safdia', 'Dias de Safra', 'center');
  58. $column_indireta_transformed = new TDataGridColumn('indireta', 'Desp. Indireta', 'center');
  59. $column_encerrada_transformed = new TDataGridColumn('encerrada', 'Encerrada', 'center');
  60. $column_safinicial_transformed->setTransformer(function($value, $object, $row)
  61. {
  62. if($value)
  63. {
  64. $date = new DateTime($value);
  65. return $date->format("d/m/Y");
  66. }
  67. });
  68. $column_saffinal_transformed->setTransformer(function($value, $object, $row)
  69. {
  70. if($value)
  71. {
  72. $date = new DateTime($value);
  73. return $date->format("d/m/Y");
  74. }
  75. });
  76. $column_indireta_transformed->setTransformer(function($value, $object, $row)
  77. {
  78. if($value)
  79. {
  80. return number_format($value, 2, ',', '.');
  81. }
  82. });
  83. $column_encerrada_transformed->setTransformer(function($value, $object, $row)
  84. {
  85. if($value === true || $value === 't' || $value === 1 || $value === '1')
  86. {
  87. return 'Sim';
  88. }
  89. return 'Não';
  90. });
  91. $order_id = new TAction(array($this, 'onReload'));
  92. $order_id->setParameter('order', 'id');
  93. $column_id->setAction($order_id);
  94. $this->datagrid->addColumn($column_id);
  95. $this->datagrid->addColumn($column_safra);
  96. $this->datagrid->addColumn($column_descricao);
  97. $this->datagrid->addColumn($column_safinicial_transformed);
  98. $this->datagrid->addColumn($column_saffinal_transformed);
  99. $this->datagrid->addColumn($column_safdia);
  100. $this->datagrid->addColumn($column_indireta_transformed);
  101. $this->datagrid->addColumn($column_encerrada_transformed);
  102. $action_onEdit = new TDataGridAction(array('SafraForm', 'onEdit'));
  103. $action_onEdit->setUseButton(false);
  104. $action_onEdit->setButtonClass('btn btn-default btn-sm');
  105. $action_onEdit->setLabel('Editar');
  106. $action_onEdit->setImage('fa:pencil-square-o #478fca');
  107. $action_onEdit->setField(self::$primaryKey);
  108. $this->datagrid->addAction($action_onEdit);
  109. $action_onDelete = new TDataGridAction(array('SafraList', 'onDelete'));
  110. $action_onDelete->setUseButton(false);
  111. $action_onDelete->setButtonClass('btn btn-default btn-sm');
  112. $action_onDelete->setLabel('Excluir');
  113. $action_onDelete->setImage('fa:trash-o #dd5a43');
  114. $action_onDelete->setField(self::$primaryKey);
  115. $this->datagrid->addAction($action_onDelete);
  116. // create the datagrid model
  117. $this->datagrid->createModel();
  118. // creates the page navigation
  119. $this->pageNavigation = new TPageNavigation;
  120. $this->pageNavigation->setAction(new TAction(array($this, 'onReload')));
  121. $this->pageNavigation->setWidth($this->datagrid->getWidth());
  122. $panel = new TPanelGroup;
  123. $panel->add($this->datagrid);
  124. $panel->addFooter($this->pageNavigation);
  125. // vertical box container
  126. $container = new TVBox;
  127. $container->style = 'width: 100%';
  128. // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  129. $container->add($this->form);
  130. $container->add($panel);
  131. parent::add($container);
  132. }
  133. public function onExportCsv($param = null)
  134. {
  135. try
  136. {
  137. $this->onSearch();
  138. TTransaction::open(self::$database); // open a transaction
  139. $repository = new TRepository(self::$activeRecord); // creates a repository for Customer
  140. $criteria = new TCriteria; // creates a criteria
  141. if($filters = TSession::getValue(__CLASS__.'_filters'))
  142. {
  143. foreach ($filters as $filter)
  144. {
  145. $criteria->add($filter);
  146. }
  147. }
  148. $records = $repository->load($criteria); // load the objects according to criteria
  149. if ($records)
  150. {
  151. $file = 'tmp/'.uniqid().'.csv';
  152. $handle = fopen($file, 'w');
  153. $columns = $this->datagrid->getColumns();
  154. $csvColumns = [];
  155. foreach($columns as $column)
  156. {
  157. $csvColumns[] = $column->getLabel();
  158. }
  159. fputcsv($handle, $csvColumns, ';');
  160. foreach ($records as $record)
  161. {
  162. $csvColumns = [];
  163. foreach($columns as $column)
  164. {
  165. $name = $column->getName();
  166. $csvColumns[] = $record->{$name};
  167. }
  168. fputcsv($handle, $csvColumns, ';');
  169. }
  170. fclose($handle);
  171. TPage::openFile($file);
  172. }
  173. else
  174. {
  175. new TMessage('info', _t('No records found'));
  176. }
  177. TTransaction::close(); // close the transaction
  178. }
  179. catch (Exception $e) // in case of exception
  180. {
  181. new TMessage('error', $e->getMessage()); // shows the exception error message
  182. TTransaction::rollback(); // undo all pending operations
  183. }
  184. }
  185. public function onDelete($param = null)
  186. {
  187. if(isset($param['delete']) && $param['delete'] == 1)
  188. {
  189. try
  190. {
  191. // get the paramseter $key
  192. $key = $param['key'];
  193. // open a transaction with database
  194. TTransaction::open(self::$database);
  195. // instantiates object
  196. $object = new Safra($key, FALSE);
  197. // deletes the object from the database
  198. $object->delete();
  199. // close the transaction
  200. TTransaction::close();
  201. // reload the listing
  202. $this->onReload( $param );
  203. // shows the success message
  204. new TMessage('info', AdiantiCoreTranslator::translate('Record deleted'));
  205. }
  206. catch (Exception $e) // in case of exception
  207. {
  208. // shows the exception error message
  209. new TMessage('error', $e->getMessage());
  210. // undo all pending operations
  211. TTransaction::rollback();
  212. }
  213. }
  214. else
  215. {
  216. // define the delete action
  217. $action = new TAction(array($this, 'onDelete'));
  218. $action->setParameters($param); // pass the key paramseter ahead
  219. $action->setParameter('delete', 1);
  220. // shows a dialog to the user
  221. new TQuestion(AdiantiCoreTranslator::translate('Do you really want to delete ?'), $action);
  222. }
  223. }
  224. /**
  225. * Register the filter in the session
  226. */
  227. public function onSearch()
  228. {
  229. // get the search form data
  230. $data = $this->form->getData();
  231. $filters = [];
  232. TSession::setValue(__CLASS__.'_filter_data', NULL);
  233. TSession::setValue(__CLASS__.'_filters', NULL);
  234. if (isset($data->id) AND ($data->id))
  235. {
  236. $filters[] = new TFilter('id', '=', $data->id);// create the filter
  237. }
  238. if (isset($data->safra) AND ($data->safra))
  239. {
  240. $filters[] = new TFilter('safra', '=', $data->safra);// create the filter
  241. }
  242. if (isset($data->descricao) AND ($data->descricao))
  243. {
  244. $filters[] = new TFilter('descricao', 'like', "%{$data->descricao}%");// create the filter
  245. }
  246. if (isset($data->encerrada) AND ($data->encerrada))
  247. {
  248. $filters[] = new TFilter('encerrada', '=', $data->encerrada);// create the filter
  249. }
  250. // fill the form with data again
  251. $this->form->setData($data);
  252. // keep the search data in the session
  253. TSession::setValue(__CLASS__.'_filter_data', $data);
  254. TSession::setValue(__CLASS__.'_filters', $filters);
  255. $param=array();
  256. $param['offset'] =0;
  257. $param['first_page']=1;
  258. $this->onReload($param);
  259. }
  260. /**
  261. * Load the datagrid with data
  262. */
  263. public function onReload($param = NULL)
  264. {
  265. try
  266. {
  267. // open a transaction with database 'safra'
  268. TTransaction::open(self::$database);
  269. // creates a repository for Safra
  270. $repository = new TRepository(self::$activeRecord);
  271. $limit = 20;
  272. // creates a criteria
  273. $criteria = new TCriteria;
  274. if (empty($param['order']))
  275. {
  276. $param['order'] = 'id';
  277. }
  278. if (empty($param['direction']))
  279. {
  280. $param['direction'] = 'desc';
  281. }
  282. $criteria->setProperties($param); // order, offset
  283. $criteria->setProperty('limit', $limit);
  284. if($filters = TSession::getValue(__CLASS__.'_filters'))
  285. {
  286. foreach ($filters as $filter)
  287. {
  288. $criteria->add($filter);
  289. }
  290. }
  291. // load the objects according to criteria
  292. $objects = $repository->load($criteria, FALSE);
  293. $this->datagrid->clear();
  294. if ($objects)
  295. {
  296. // iterate the collection of active records
  297. foreach ($objects as $object)
  298. {
  299. // add the object inside the datagrid
  300. $this->datagrid->addItem($object);
  301. }
  302. }
  303. // reset the criteria for record count
  304. $criteria->resetProperties();
  305. $count= $repository->count($criteria);
  306. $this->pageNavigation->setCount($count); // count of records
  307. $this->pageNavigation->setProperties($param); // order, page
  308. $this->pageNavigation->setLimit($limit); // limit
  309. // close the transaction
  310. TTransaction::close();
  311. $this->loaded = true;
  312. }
  313. catch (Exception $e) // in case of exception
  314. {
  315. // shows the exception error message
  316. new TMessage('error', $e->getMessage());
  317. // undo all pending operations
  318. TTransaction::rollback();
  319. }
  320. }
  321. public function onShow()
  322. {
  323. }
  324. /**
  325. * method show()
  326. * Shows the page
  327. */
  328. public function show()
  329. {
  330. // check if the datagrid is already loaded
  331. if (!$this->loaded AND (!isset($_GET['method']) OR !(in_array($_GET['method'], array('onReload', 'onSearch')))) )
  332. {
  333. if (func_num_args() > 0)
  334. {
  335. $this->onReload( func_get_arg(0) );
  336. }
  337. else
  338. {
  339. $this->onReload();
  340. }
  341. }
  342. parent::show();
  343. }
  344. }
  345. ?>
</your>
MG

José
Não consegui identificar por que está assumindo o key como a data.
Mas pude perceber que o registro é novo, pois se observar no "dump", o "id" está nulo.
Quando o método cadastrar é chamado, em aponta para onShow do form, este está vazio.
Neste método onShow, geralmente iniciamos limpando o formulário. No seu caso não faz nada.

1) Primeira tentativa de solução, mude este método para limpar o form.
2) Ao sair do campo, uma classe e um método é executado na barra de endereços do navegador, veja o que é passado depois do "&method?id=???&key=???"
NR

Ao usar a função exitAction, o atributo key é preenchido com o valor do campo ao qual a ação está vinculada, nesse caso a data final da safra.
 
  1. <?php
  2. // erro, pois vai tentar buscar pela data(where id = '31/01/2018')
  3. //$safra = new Safra ($param['key']);
  4. ?>

Mas se a ideia é só fazer um cálculo entre as datas inicial e final, qual a necessidade de instanciar uma safra? Todas as informações que você precisa estão na variável $param.
MG

Nataniel,
Eu sinceramente não sabia disso!

Grato.
HB

Nataniel e Marcelo, agradeço a vocês pela a ajuda.

Resolvi fazer este cálculo no onSave porque mais a frente vai ser mais útil pra mim e da forma abaixo deu certo, calculou corretamente.

 
  1. <?php
  2. $safinicial = new DateTime($object->safinicial);
  3. $saffinal = new DateTime($object->saffinal);
  4. $safradia = $safinicial->diff($saffinal);
  5. $object->safdia = $safradia->format("%a");
  6. $object->store();
  7. ?>