Lançado Adianti Framework 7.6!
Clique aqui para saber mais
Ajuda no relatório tabular Bom dia Amigos, estou tentando criar um relatório, onde usei o relatório padrão , acrescentei algumas mudanças e esta dando erro se poderem me ajudar, pois não estou conseguindo resolver , ja estou 3 dias e não consigo, segue abai xo meu código e o erro que esta sendo apresentado. ...
AM
Ajuda no relatório tabular  
Bom dia Amigos, estou tentando criar um relatório, onde usei o relatório padrão , acrescentei algumas mudanças e esta dando erro se poderem me ajudar, pois não estou conseguindo resolver , ja estou 3 dias e não consigo, segue abai xo meu código e o erro que esta sendo apresentado.
  1. <?php
  2. /**
  3.  * NotasfornecedoresReport Report
  4.  * @author  <your name here>
  5.  */
  6. class NotasfornecedoresReport extends TPage {
  7.     protected $form// form
  8.     private static $paginas 2;
  9.     /**
  10.      * Class constructor
  11.      * Creates the page and the registration form
  12.      */
  13.     function __construct() {
  14.         parent::__construct();
  15.         // creates the form
  16.         $this->form = new BootstrapFormBuilder('form_NotasfornecedoresModel_report');
  17.         $this->form->setFormTitle('NotasfornecedoresModel Report');
  18.         // create the form fields
  19.         $tbl_NotasEmissao = new TDate('tbl_NotasEmissao''conexao''NotasfornecedoresModel''idtbl_Notas''tbl_NotasTipo');
  20.         $tbl_NotasRecebimento = new TDate('tbl_NotasRecebimento''conexao''NotasfornecedoresModel''idtbl_Notas''tbl_NotasTipo');
  21.         $tbl_fornecedores_idtbl_Fornecedores = new TDBCombo('tbl_fornecedores_idtbl_Fornecedores''conexao''FornecedoresModel''idtbl_Fornecedores''tbl_FornecedoresNome');
  22.         $tbl_fornecedores_tbl_Empresa_idtbl_Empresa = new TDBCombo('tbl_fornecedores_tbl_Empresa_idtbl_Empresa''conexao''EmpresaModel''idtbl_Empresa''tbl_EmpresaNome');
  23.         $output_type = new TRadioGroup('output_type');
  24.         $tbl_NotasEmissao->setMask('dd/mm/yyyy');
  25.         $tbl_NotasRecebimento->setMask('dd/mm/yyyy');
  26.         // add the fields
  27.         $this->form->addFields([new TLabel('Emissão :')], [$tbl_NotasEmissao]);
  28.         $this->form->addFields([new TLabel('Recebimento :')], [$tbl_NotasRecebimento]);
  29.         $this->form->addFields([new TLabel('Fornecedores :')], [$tbl_fornecedores_idtbl_Fornecedores]);
  30.         $this->form->addFields([new TLabel(' Empresa :')], [$tbl_fornecedores_tbl_Empresa_idtbl_Empresa]);
  31.         $this->form->addFields([new TLabel('Output')], [$output_type]);
  32.         $output_type->addValidation('Output', new TRequiredValidator);
  33.         // set sizes
  34.         $tbl_NotasEmissao->setSize('100%');
  35.         $tbl_NotasRecebimento->setSize('100%');
  36.         $tbl_fornecedores_idtbl_Fornecedores->setSize('100%');
  37.         $tbl_fornecedores_tbl_Empresa_idtbl_Empresa->setSize('100%');
  38.         $output_type->setSize('100%');
  39.         $output_type->addItems(array('html' => 'HTML''pdf' => 'PDF''rtf' => 'RTF''xls' => 'XLS'));
  40.         $output_type->setLayout('horizontal');
  41.         $output_type->setUseButton();
  42.         $output_type->setValue('pdf');
  43.         $output_type->setSize(70);
  44.         // add the action button
  45.         $btn $this->form->addAction(_t('Generate'), new TAction(array($this'onGenerate')), 'fa:cog');
  46.         $btn->class 'btn btn-sm btn-primary';
  47.         // vertical box container
  48.         $container = new TVBox;
  49.         $container->style 'width: 90%';
  50.         // $container->add(new TXMLBreadCrumb('menu.xml', __CLASS__));
  51.         $container->add($this->form);
  52.         parent::add($container);
  53.     }
  54.     public function getNativeWriter() {
  55.         return $this->pdf;
  56.     }
  57.     public function Cabecalho($pdf) {
  58.         try {
  59.             // open a transaction with database 'conexao'
  60.             TTransaction::open('conexao');
  61.             // get the form data into an active record
  62.             $data $this->form->getData();
  63.             $this->form->validate();
  64.             $repository1 = new TRepository('FornecedoresModel');
  65.             $criteria1 = new TCriteria;
  66.             $objectos $repository1->load($criteria1FALSE);
  67.             foreach ($objectos as $objecto) {
  68.                 $empresa $objecto->empresa_model->tbl_EmpresaNome;
  69.             }
  70.             // fill the form with the active record data
  71.             $this->form->setData($data);
  72.             // close the transaction
  73.             TTransaction::close();
  74.         } catch (Exception $e) { // in case of exception
  75.             // shows the exception error message
  76.             new TMessage('error'$e->getMessage());
  77.             // undo all pending operations
  78.             TTransaction::rollback();
  79.         }
  80.         $numeroPagina self::$paginas;
  81.         $pdf->SetFont('Arial''I'8);
  82.         // TITULO 
  83.         $pdf->Cell(00"LIVRO FISCAL"00);
  84.         $pdf->Cell(80);
  85.         $pdf->PageNo();
  86.         $pdf->Cell(00, ("FL: {$numeroPagina} /{nb}"), 00'R');
  87.         $pdf->Ln(20);
  88.         $pdf->Cell(00"REGISTRO DE ENTRADAS"00'C');
  89.         $pdf->Ln(20);
  90.         $pdf->Cell(1000, ( "EMPRESA : {$empresa}"), 00);
  91.         // Line break 
  92.         $pdf->Ln(20);
  93.         self::$paginas++;
  94.     }
  95.     /**
  96.      * Generate the report
  97.      */
  98.     function onGenerate() {
  99.         try {
  100.             // open a transaction with database 'conexao'
  101.             TTransaction::open('conexao');
  102.             // get the form data into an active record
  103.             $data $this->form->getData();
  104.             $this->form->validate();
  105.             $repository = new TRepository('NotasfornecedoresModel');
  106.             $criteria = new TCriteria;
  107.             if ($data->tbl_NotasEmissao) {
  108.                 $criteria->add(new TFilter('tbl_NotasEmissao''like'"%{$data->tbl_NotasEmissao}%"));
  109.             }
  110.             if ($data->tbl_NotasRecebimento) {
  111.                 $criteria->add(new TFilter('tbl_NotasRecebimento''like'"%{$data->tbl_NotasRecebimento}%"));
  112.             }
  113.             if ($data->tbl_fornecedores_idtbl_Fornecedores) {
  114.                 $criteria->add(new TFilter('tbl_fornecedores_idtbl_Fornecedores''like'"%{$data->tbl_fornecedores_idtbl_Fornecedores}%"));
  115.             }
  116.             if ($data->tbl_fornecedores_tbl_Empresa_idtbl_Empresa) {
  117.                 $criteria->add(new TFilter('tbl_fornecedores_tbl_Empresa_idtbl_Empresa''like'"%{$data->tbl_fornecedores_tbl_Empresa_idtbl_Empresa}%"));
  118.             }
  119.             $objects $repository->load($criteriaFALSE);
  120.             $format $data->output_type;
  121.             if ($objects) {
  122.                 $widths = array(5050100100);
  123.                 switch ($format) {
  124.                     case 'html':
  125.                         $tr = new TTableWriterHTML($widths);
  126.                         break;
  127.                     case 'pdf':
  128.                         $tr = new TTableWriterPDF($widths);
  129.                         $fpdf $tr->getNativeWriter();
  130.                         $fpdf->setHeaderCallback(array($this'Cabecalho'));
  131.                         $this->Cabecalho($fpdf);
  132.                         break;
  133.                     case 'xls':
  134.                         $tr = new TTableWriterXLS($widths);
  135.                         break;
  136.                     case 'rtf':
  137.                         $tr = new TTableWriterRTF($widths);
  138.                         break;
  139.                 }
  140.                 // create the document styles
  141.                 $tr->addStyle('title''Arial''10''B''#ffffff''#A3A3A3');
  142.                 $tr->addStyle('datap''Arial''10''''#000000''#EEEEEE');
  143.                 $tr->addStyle('datai''Arial''10''''#000000''#ffffff');
  144.                 $tr->addStyle('header''Arial''12''I''#ffffff''#6B6B6B');
  145.                 $tr->addStyle('footer''Times''10''I''#000000''#A3A3A3');
  146.                 // add titles row
  147.                 $tr->addRow();
  148.                 $tr->addCell('Emissão :''left''title');
  149.                 $tr->addCell('Recebimento :''left''title');
  150.                 $tr->addCell('Fornecedores :''right''title');
  151.                 $tr->addCell(' Empresa :''right''title');
  152.                 // controls the background filling
  153.                 $colour FALSE;
  154.                 // data rows
  155.                 foreach ($objects as $object) {
  156.                     $style $colour 'datap' 'datai';
  157.                     $tr->addRow();
  158.                     $tr->addCell($object->tbl_NotasEmissao'left'$style);
  159.                     $tr->addCell($object->tbl_NotasRecebimento'left'$style);
  160.                     $tr->addCell($object->tbl_fornecedores_idtbl_Fornecedores'right'$style);
  161.                     $tr->addCell($object->tbl_fornecedores_tbl_Empresa_idtbl_Empresa'right'$style);
  162.                     $colour = !$colour;
  163.                 }
  164.                 // footer row
  165.                 $tr->addRow();
  166.                 $tr->addCell(date('Y-m-d h:i:s'), 'center''footer'4);
  167.                 // stores the file
  168.                 if (!file_exists("app/output/NotasfornecedoresModel.{$format}") OR is_writable("app/output/NotasfornecedoresModel.{$format}")) {
  169.                     $tr->save("app/output/NotasfornecedoresModel.{$format}");
  170.                 } else {
  171.                     throw new Exception(_t('Permission denied') . ': ' "app/output/NotasfornecedoresModel.{$format}");
  172.                 }
  173.                 // open the report file
  174.                 parent::openFile("app/output/NotasfornecedoresModel.{$format}");
  175.                 // shows the success message
  176.                 new TMessage('info''Report generated. Please, enable popups.');
  177.             } else {
  178.                 new TMessage('error''No records found');
  179.             }
  180.             // fill the form with the active record data
  181.             $this->form->setData($data);
  182.             // close the transaction
  183.             TTransaction::close();
  184.         } catch (Exception $e) { // in case of exception
  185.             // shows the exception error message
  186.             new TMessage('error'$e->getMessage());
  187.             // undo all pending operations
  188.             TTransaction::rollback();
  189.         }
  190.     }
  191. }
  192. ?>


o erro apresentado na tela
Fatal error: Uncaught Error: Call to a member function addRow() on null in C:xampphtdocsAdiantiProjetosUnitSoftwareLivrosapplibpdfFPDF.php:385 Stack trace: #0 C:xampphtdocsAdiantiProjetosUnitSoftwareLivrosapplibpdfFPDF.php(342): FPDF->Header() #1 C:xampphtdocsAdiantiProjetosUnitSoftwareLivrosapplibpdfFPDF.php(619): FPDF->AddPage('P', Array, 0) #2 C:xampphtdocsAdiantiProjetosUnitSoftwareLivrosapplibreportsTTableWriterPDF.class.php(172): FPDF->Cell(50, 15, '2018-10-04', 1, 0, 'L', true) #3 C:xampphtdocsAdiantiProjetosUnitSoftwareLivrosappcontrolsistemarelatoriosfornecedoresNotasfornecedoresReport.class.php(213): TTableWriterPDF->addCell('2018-10-04', 'left', 'datap') #4 [internal function]: NotasfornecedoresReport->onGenerate(Array) #5 C:xampphtdocsAdiantiProjetosUnitSoftwareLivroslibadianticontrolTPage.php(51): call_user_func(Array, Array) #6 C:xampphtdocsAdiantiProjetosUnitSoftwareLivroslibadianticontrolTPage.php(205): AdiantiControlTPage->run() #7 C:xamp in C:xampphtdocsAdiantiProjetosUnitSoftwareLivrosapplibpdfFPDF.php on line 385

Pacotão Dominando o Adianti Framework 7
O material mais completo de treinamento do Framework.
Curso em vídeo aulas + Livro completo + Códigos fontes do projeto ERPHouse.
Conteúdo Atualizado! Versão 7.4


Dominando o Adianti 7 Quero me inscrever agora!

Comentários (14)


NR

Qual a versão do Adianti? Executei seu código e gerou o pdf sem problemas
AM

Oi Nataniel a versão é o 5 , meu problema está apartir da segunda folha, na primeira ele gera direito , quando tem mais de uma folha ele dá este erro. Talvez por não conseguir duplicar o header, pois sem ele funciona.
NR

Chame a função setHeaderCallback sobre a variável com a instância da classe TTableWriterPDF ao invés de usar sobre a instância da FPDF:
  1. <?php
  2. $tr = new TTableWriterPDF($widths);
  3. $fpdf $tr->getNativeWriter();
  4. //$fpdf->setHeaderCallback(array($this, 'Cabecalho'));
  5. $tr->setHeaderCallback(array($this'Cabecalho'));
  6. ?>

Provavelmente você vai ter que fazer outros ajustes, mas é por aí...
AM

Obrigado Nataniel, fiz a modificação e mais alguns ajustes , esta funcionando perfeito, um abraço.
PN

Boa tarde Alexsander, como ficou o teu código, estou com o mesmo problema e não consegui resolver ainda.
AM

Boa tarde meu amigo, sim está funcionando, mas o que está acontecendo com o seu código?
PN

public function getNativeWriter() {
return $this->pdf;
}

public function Header()
{
TTransaction::open('patrimonio');
$header = new TRepository('Tbheader');
$criteria = new TCriteria;
$header = $header->load($criteria);


$this->SetXY(10,15); //SetXY - DEFINE O X E O Y NA PAGINA
$this->Rect(10,10,568,60); //CRIA UM RETÂNGULO QUE COMEÇA NO X = 10, Y = 10 E
//TEM 190 DE LARGURA E 280 DE ALTURA.
//NESTE CASO, É UMA BORDA DE PÁGINA.

//$designer->Ln(90);
$fill = TRUE;
$this->image('',15, 18, 36);
$this->SetFont('Arial','B',10); // DEFINE A FONTE ARIAL, NEGRITO (B), DE TAMANHO 8
foreach ($header as $h)
{

}
$this->setFontColorRGB( '#000000' );
$this->Setxy(55,15);
$this->Cell(185,15,utf8_decode($h->estado),0,1,'L');
$this->Setxy(55,29);
$this->Cell(170, 12, utf8_decode($h->nomeentidade), 0, 0, 'L');
$this->SetFont('Arial','I',10);
$this->Setxy(55,41);

$this->Cell(170, 12, utf8_decode($h->tipoentidade), 0, 0, 'L');
$this->Setxy(55,51);
$this->Cell(185,15,utf8_decode($h->setorpatrimonio),0,1,'L');
//$this->Ln(5);
TTransaction::close();
}

/**
* method onGenerate()
* Executed whenever the user clicks at the generate button
*/
function onGenerate()
{
try
{
// open a transaction with database 'patrimonio'
TTransaction::open('patrimonio');

// get the form data into an active record Customer
$object = $this->form->getData();
$repository = new TRepository('VwDepreciacaoDetalhe');
//$criteria->tbprincipal('order', 'tombo');
$criteria = new TCriteria;
$customers = $repository->load($criteria);
$format = $object->output_type;
$pdf = new FPDF('P','mm',array(100,200));

if ($customers)
{
$widths = array(30, 308, 70, 180, 50, 57, 48, 57);
switch ($format)
{
case 'html':
$tr = new TTableWriterHTML($widths);
break;
case 'pdf':
$tr = new TTableWriterPDF($widths, 'L');
$fpdf = $tr->getNativeWriter(); // ERRO AQUI*************
$fpdf->setHeaderCallback(array($this,'Header'));
$this->Header($fpdf);
break;
case 'rtf':
if (!class_exists('PHPRtfLite_Autoloader'))
{
PHPRtfLite::registerAutoloader();
}
$tr = new TTableWriterRTF($widths, 'L');
break;
}

if (!empty($tr))
{
// create the document styles
$tr->addStyle('title', 'Arial', '8', 'BI', '#000000', '#c6c4c0');
$tr->addStyle('datap', 'Arial', '7', '', '#000000', '#f2f0ed');
$tr->addStyle('datai', 'Arial', '7', '', '#000000', '#ffffff');
//$tr->addStyle('header2', 'Arial', '15', 'BI','#000000', '#ffffff');
$tr->addStyle('header', 'Arial', '14', 'I', '#000000', '#ffffff');
//$tr->addStyle('footer', 'Arial', '12', 'BI', '#2B2B2B', '#ffffff');
$tr->addStyle('total', 'Arial', '7', 'BI', '#222222', '#c6c4c0');

// add a header row
$tr->addRow();
$tr->addCell('Relação de Bens com Depreciação. (DETALHE)', 'C', 'header', 8);
//$tr->addRow();
//$tr->addCell('Relação', 'center', 'header', 6);

// add titles row
$tr->addRow();
$tr->addCell('Tombo', 'center', 'title');
$tr->addCell('Bem', 'center', 'title');
$tr->addCell('Condição', 'center', 'title');
$tr->addCell('Centro', 'center', 'title');
$tr->addCell('Inclusão', 'center', 'title');
$tr->addCell('Aquisição', 'center', 'title');
$tr->addCell('Dep', 'center', 'title');
$tr->addCell('Saldo', 'center', 'title');

// controls the background filling
$colour= FALSE;
$total = 0;
$total2 = 0;
$total3 = 0;

// data rows
foreach ($customers as $customer)
{
$style = $colour ? 'datap' : 'datai';
//$dataIinclusao=date('d/m/Y');
//$num = (2, ',', '.');
$tr->addRow();
$tr->addCell($customer->tombo, 'left', $style);
$tr->addCell($customer->nitem, 'left', $style);
$tr->addCell($customer->ncondicao, 'left', $style);
$tr->addCell($customer->ncentro, 'left', $style);
$tr->addCell(TDate::date2br($customer->dataInclusao), 'center', $style);
$tr->addCell(number_format($customer->valor_bem,2,",","."), 'rigth', $style);
$tr->addCell(number_format($customer->depreciacao_acumulada,2,",","."), 'rigth', $style);
$tr->addCell(number_format($customer->saldo_atual,2,",","."), 'rigth', $style);
$total+= $customer->valor_bem;
$total2+= $customer->depreciacao_acumulada;
$total3+= $customer->saldo_atual;

$colour = !$colour;
}
$valor_bem = number_format($total,2,',','.');
$depreciacao_acumulada = number_format($total2,2,',','.');
$saldo_atual = number_format($total3,2,',','.');
$tr->addRow();
//$tr->addCell('TOTAL: R$ ' . $saldo_atual, 'rigth', 'total', 8);
$tr->addCell('TOTAIS ', 'rigth', 'datai', 5);
$tr->addCell($valor_bem, 'rigth', 'total');
$tr->addCell($depreciacao_acumulada, 'rigth', 'total');
$tr->addCell($saldo_atual, 'rigth', 'total');

// stores the file
if (!file_exists("app/output/Bens.{$format}") OR is_writable("app/output/Bens.{$format}"))
{
$tr->save("app/output/Bens.{$format}");
}
else
{
throw new Exception(_t('Permission denied') . ': ' . "app/output/Bens.{$format}");
}

parent::openFile("app/output/Bens.{$format}");

// shows the success message
new TMessage('info', 'Relatório gerado com sucesso!');
}
}
else
{
new TMessage('error', 'Não existem registros para exibir!');
}

// fill the form with the active record data
$this->form->setData($object);

// close the transaction
TTransaction::close();
}
catch (Exception $e) // in case of exception
{
// shows the exception error message
new TMessage('error', 'Error ' . $e->getMessage());
// undo all pending operations
TTransaction::rollback();
}
}
PN

Alexsander Maciel muito obrigado, mas eu consegui resolver de outra forma aqui.
AM

Boa tarde,
peço desculpas pela demora pois estava em férias , mas para resolver a situção eu criei um topo separado , com as funções do pdf e os dados dentro do tablepdf. mas fico feliz por ter conseguido resolver. um abraço
JM

Alexsander Maciel, estou com esse mesmo problema após atualizar o framework, poderia por gentileza postar seu código aqui pra eu dar uma olhada? Não estou conseguindo resolver!
AM

Boa noite Joaby , peço desculpas , conseguiu resolver a questão ?
JM

Ainda não consegui Alexsander.
AM

Joaby vou postar o código hoje a noite, para te ajudar.
AM

Boa Noite , eu fiz algumas mudanças conforme abaixo :

chamo a função neste trecho

case 'pdf':
$tr = new TTableWriterPDF($widths);
$tr->getNativeWriter();
$tr->setHeaderCallback(array($this, 'header'));
break;

e aqui na função

$dataInicio = explode('-', $data->tbl_NotasEmissao);
list($ano, $mes, $dia) = $dataInicio;
$numeroPagina = self::$paginas + $mes;
//$pdf = new FPDF('P', 'pt', 'A4'); // instancia a classe FPDF
//$pdf->AddPage();
//$pdf->AliasNbPages();
// create the document styles
$pdf->addStyle('titulo', 'Arial', '7', 'I', 0, '#ffffff', '#CCCCCC');
$pdf->addStyle('titulo_tabela', 'Arial', '6', 'B', '#000000', '#EEEEEE');

// TITULO
$pdf->addRow();
$pdf->addCell('LIVRO FISCAL ', 'left', 'titulo');

$pdf->addCell(("FL: {$numeroPagina}"), 'right', 'titulo', 8);

lembrando fi conforme minha necessidade, espero que ajude.