LC
Incrementar um mês numa data e salvar no banco de dados.
Boa tarde.
Estou desenvolvendo um sistema para emissão de boletos, mas infelizmente não estou conseguindo incrementar um mês na data de vencimento de um boleto para outro. Já tentei utilizar o método pelo exemplo aqui no fórum mas infelizmente não consegui enviar a data para o banco. Segue o código.
Estou desenvolvendo um sistema para emissão de boletos, mas infelizmente não estou conseguindo incrementar um mês na data de vencimento de um boleto para outro. Já tentei utilizar o método pelo exemplo aqui no fórum mas infelizmente não consegui enviar a data para o banco. Segue o código.
- <?php
- /**
- * CadastroBoletos Form
- * @author Leildon S Carvalho
- */
- class CadastroBoletos extends TPage
- {
- protected $form; // form
- private $datagrid;
- /**
- * Form constructor
- * @param $param Request
- */
- public function __construct( $param )
- {
- parent::__construct();
-
- // creates the form
- $this->form = new TQuickForm('form_BoletosHonorarios');
- $this->form->class = 'tform'; // change CSS class
-
- $this->form->style = 'display: table;width:100%'; // change style
-
- // define the form title
- $this->form->setFormTitle('BoletosHonorarios');
-
- // create the form fields
- $id = new TEntry('id');
- //$idclienteboleto = new TEntry('idclienteboleto');
- $idclienteboleto = new ">TDBSeekButton('idclienteboleto','conexao','form_BoletosHonorarios','Clientes','NomeRazao','idclienteboleto','nomecliente');
- $nomecliente = new TEntry('nomecliente');
- $valor = new TEntry('valor');
- //$tipo = new TEntry('tipo');
- $dataemissao = new TDate('dataemissao');
- $datavencimento = new TDate('datavencimento');
- $numdocumento = new TEntry('numdocumento');
- $observacao = new TText('observacao');
-
- // add the fields
- $this->form->addQuickField('Id', $id, 100 );
- $this->form->addQuickFields('Cliente', array ($idclienteboleto, $nomecliente ));
- $this->form->addQuickField('Valor', $valor, 100 );
- //$this->form->addQuickField('Tipo', $tipo, 200 );
- $this->form->addQuickField('Emissão', $dataemissao, 80 );
- $this->form->addQuickField('Vencimento', $datavencimento, 80 );
- $this->form->addQuickField('Nº Documento', $numdocumento, 80 );
- $this->form->addQuickField('Observação', $observacao, 200);
- $nomecliente->setEditable(FALSE);
- $idclienteboleto->setSize(50);
- $nomecliente->setSize(400);
-
-
- if (!empty($id))
- {
- $id->setEditable(FALSE);
- }
-
- /** samples
- $this->form->addQuickFields('Date', array($date1, new TLabel('to'), $date2)); // side by side fields
- $fieldX->addValidation( 'Field X', new TRequiredValidator ); // add validation
- $fieldX->setSize( 100, 40 ); // set size
- **/
-
- // create the form actions
- $this->form->addQuickAction(_t('Save'), new TAction(array($this, 'onSave')), 'fa:floppy-o');
- $this->form->addQuickAction(_t('New'), new TAction(array($this, 'onClear')), 'bs:plus-sign green');
-
- //CRIA O DATAGRID QUE IRÁ MOSTRAR OS BOLETOS GERADOS
-
- $this->datagrid = new TQuickGrid;
- $this->datagrid->addQuickColumn('ID', 'id', 'center', 50);
- $this->datagrid->addQuickColumn('Nº Parcela', 'parcela', 'center', 100);
- $this->datagrid->addQuickColumn('Referência', 'referencia', 'right', 80);
- $this->datagrid->addQuickColumn('Vencimento', 'vencimento','center', 80);
- $this->datagrid->addQuickColumn('Valor', 'valor','rigth', 80);
- $this->datagrid->createModel();
-
- // vertical box container
- $container = new TVBox;
- $container->style = 'width: 90%';
- // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
- $container->add($this->form);
- $container->add($this->datagrid);
-
- parent::add($container);
- }
- /**
- * Save form data
- * @param $param Request
- */
- public function onSave( $param )
- {
- try
- {
- TTransaction::open('conexao'); // 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 BoletosHonorarios; // 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
-
- //GERAÇÃO DE VÁRIOS BOLETOS
- $boleto = new BoletosHonorarios;
- $data = $this->form->getData(); // get form data as array
- $date = TDate::date2us(date($data->datavencimento));
- $date = new DateTime( $data );
- //$date = new TDate ('date');
- //$date->$data->datavencimento;
- $date->format('Y-m-d');
-
- for ($i=1;$i<=12;$i++){
- $boleto = new BoletosHonorarios;
- $boleto->idclienteboleto = $data->idclienteboleto;
- $boleto->valor = $data->valor;
- $boleto->tipo = 'C';
- $boleto->dataemissao = $data->dataemissao;
- $boleto->datavencimento = $date;
- $boleto->numdocumento = $data->numdocumento;
- $boleto->numparcela = $i.'/12';
- $boleto->status = 'A';
- $boleto->observacao = $data->observacao;
- $boleto->store();//salva o registro
-
- //INCREMENTA UM MÊS AO VENCIMENTO
- $date->add(new DateInterval('P1M'));
- }
-
- TTransaction::close(); // close the transaction
-
- //LIBERA AS VARIÁVEIS DA MEMÓRIA
- unset($date);
-
- 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->getData() ); // keep 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
- {
- if (isset($param['key']))
- {
- $key = $param['key']; // get the parameter $key
- TTransaction::open('conexao'); // open a transaction
- $object = new BoletosHonorarios($key); // instantiates the Active Record
- $this->form->setData($object); // fill the form
- TTransaction::close(); // close the transaction
- }
- else
- {
- $this->form->clear(TRUE);
- }
- }
- catch (Exception $e) // in case of exception
- {
- new TMessage('error', $e->getMessage()); // shows the exception error message
- TTransaction::rollback(); // undo all pending operations
- }
- }
- }
- ?>
Com esse código está dando este erro: DateTime::__construct() expects parameter 1 to be string, object given
Se for data da emissão +30 +60 +120... até completar um ano, tenta algo assim dentro do for:
$boleto->datavencimento = date('Y-m-d', strtotime( $data->dataemissao . '+'.$i.' months'));
Não li muito teu código, mas acho que tem que comentar a linha 124 porque já estava convertendo a data ali.
Ainda está dando o erro DateTime::__construct() expects parameter 1 to be string, object given
Ao criar o DateTime você deve passar a data em formato americano e não o objeto $data(contém todos os dados do formulário):
E dentro do loop, como $date é um objeto, precisa alterar o seguinte:
Fiz as alterações conforme abaixo:
<php
$data = $this->form->getData(); // get form data as array
$date = TDate::date2us(date($data->datavencimento));
$date = new DateTime( $date );
//$date = new TDate ($date);
for ($i=1;$i<=12;$i++){
$boleto = new BoletosHonorarios;
$boleto->idclienteboleto = $data->idclienteboleto;
$boleto->valor = $data->valor;
$boleto->tipo = 'C';
$boleto->dataemissao = $data->dataemissao;
$boleto->datavencimento = $date->format('Y-m-d');;
$boleto->numdocumento = $data->numdocumento;
$boleto->numparcela = $i.'/12';
$boleto->status = 'A';
$boleto->observacao = $data->observacao;
$boleto->store();//salva o registro
//INCREMENTA UM MÊS AO VENCIMENTO
$datev->add(new DateInterval('P1M'));
}
?>
Mas agora está aparecendo essa mensagem de erro: DateTime::__construct(): Failed to parse time string (1-31-7--20) at position 0 (1): Unexpected character
Desculpe o código não ficou colorido
Como precisamos utilizar muito esse tipo de método sempre procuro criar fora do código principal para poder utilizar em separado.
Criei uma classe onde coloco todos os métodos que preciso para uso geral. Não vou passar todas mas segue as que vc precisa:
Aproveitando... qual biblioteca está utilizado para gerar os boletos ?
Já está atualizada para funcionar com o registro dos boletos emitidos?
Qual biblioteca utiliza para tratar os retornos ?
Consegui resolver usando o código
Obrigado a todos.
Júnior, por enquanto ele só gera boletos estilo carnê. Ainda não utilizo o boleto bancário mas futuramente vou implantar. O pessoal usa muito essa biblioteca boletophp.com.br/