How to call an array outside a class using PHP and Codeigniter? - php

hello guys i just need a little help here about accessing a data array outside a class i'm so confused on how to show the variable outside the class
Here's my code below:
<?php
date_default_timezone_set('Asia/Manila');
require('resources/fpdf/fpdf.php');
class PDF extends FPDF {
function Header(){
//HERE IS THE PLACE WHERE SHOULD I PUT THE ARRAY, BUT I CANT ACCESS IT INSIDE
$this->SetFont('Arial','B',10);
$this->Cell(180,5,'PURCHASE ORDER',0,0,'C');
$this->Ln();
$this->SetFont('Arial','',9);
$this->Cell(40,5,'Suppliers Name:'.$data['spname'].' ');
$this->Ln();
$this->SetFont('Arial','',9);
$this->Ln(20);
}
}
$query = "SELECT * FROM po_order_details WHERE order_code = '".$code."'";
$result = $this->db->query($query);
foreach($result->result_array() as $row){
$data[] = array($row['item_qty'], //THIS IS THE ARRAY THAT I NEED TO GET
$row['spname'],
$row['spaddress'],
);
}
$this->session->set_userdata('session_data',$data);
//Column titles
$pdf = new PDF();
$header = array('QTY','ITEM / DESCRIPTION' , 'UNIT PRICE', 'TOTAL AMOUNT'); // CHANGE THIS ALSO
$pdf->SetFillColor(255,0,0);
$pdf->Ln();
$pdf->AddPage();
$pdf->BuildTable($header,$data);
$pdf->Ln();
$pdf->Output();
?>
that's all i hope you can help me

Why not just change the prototype of your Header method and pass the array as a parameter like this.
<?php
date_default_timezone_set('Asia/Manila');
require('resources/fpdf/fpdf.php');
class PDF extends FPDF {
function Header( &$titles, &$data ){
//HERE IS THE PLACE WHERE SHOULD I PUT THE ARRAY, BUT I CANT ACCESS IT INSIDE
// use $titles and $data as you like here
$this->SetFont('Arial','B',10);
$this->Cell(180,5,'PURCHASE ORDER',0,0,'C');
$this->Ln();
$this->SetFont('Arial','',9);
$this->Cell(40,5,'Suppliers Name:'.$data['spname'].' ');
$this->Ln();
$this->SetFont('Arial','',9);
$this->Ln(20);
}
}
$query = "SELECT * FROM po_order_details WHERE order_code = '".$code."'";
$result = $this->db->query($query);
foreach($result->result_array() as $row){
$data[] = array($row['item_qty'], //THIS IS THE ARRAY THAT I NEED TO GET
$row['spname'],
$row['spaddress'],
);
}
$this->session->set_userdata('session_data',$data);
//Column titles
$pdf = new PDF();
$header = array('QTY','ITEM / DESCRIPTION' , 'UNIT PRICE', 'TOTAL AMOUNT'); // CHANGE THIS ALSO
$pdf->Header( $header, $data );
$pdf->SetFillColor(255,0,0);
$pdf->Ln();
$pdf->AddPage();
$pdf->BuildTable($header,$data);
$pdf->Ln();
$pdf->Output();
?>

Could you just pass it as a parameter and then return the result?
Like:
function Header($param_array = array()) {
// ... modifications, bla bla
return $result_array;
}
And then look up the function which calls that Header() and pass that array parameter all the way through that function.
Of course, the drawback here is that you would modify FPDF class and would not be able to properly update to an newer version, if you need it at some point in the future.

Related

Dynamically compose the name of function to call on php

I have csv like this.
id,startScore,endScore,total
1,12,34,46
2,10,20,30
.
.
Now I have Entity with the same column name.
So,it has the functions like these below.
setStartScore()
setEndScore()
setTotal()
For now my php code is like this below
$lines = explode('\n',$csvFile); // get CSV Content
$header = array_shift($lines); // get header
$headers = explode(",",$header)
foreach($lines as $line){ // each csv line
$table = new Table();
foreach(explodes(',',$line) as $l){
$i = 0;
foreach($headers as $h){
$table->set{$headers[$i]}($l[$i]) //how can I make dynamically make set***() function.
$i++;
}
I guess if I get doctrine setter/getter naming regulation, it works well though....
You can use a constructor to set the data.
Class Table
// ..
public function __construct($id, $startScore, $endScore, $total){
$this->id = $id;
$this->startScore = $startScore;
$this->endScore = $endScore;
$this->total = $total;
}
Then you can create the objects like:
foreach($lines as $line){ // each csv line
$data = explodes(',',$line);
$table = new Table($data[0], $data[1], $data[2], $data[3]);
$em->persist($table);
}
// ..flush

Invalid argument supplied for foreach() FPDF PHP

Here's the code for generating a PDF Table but it seems my code is not right regarding in foreach, the tutorial use file.txt. Guys its my first time using FPDF in php so i'm confused right now what i need to do with my error. Tutorials > Tutorial 4: Multi-columns FPDF Link
<?php
require('fpdf.php');
$hostname = "localhost";
$database = "brm_dbs";
$username = "root";
$password = "";
$conn = mysql_connect($hostname, $username, $password) or die(mysql_error());
mysql_select_db($database, $conn);
class PDF extends FPDF
{
// Load data
function LoadData($query)
{
// Read file lines
//$lines = file($file);
//$lines = file($query);
$result = mysql_query($query);
$data = array();
foreach($result as $line)
$data[] = explode(',',trim($line));
return $data;
}
// Simple table
function BasicTable($header, $data)
{
// Header
foreach($header as $col)
$this->Cell(40,7,$col,1);
$this->Ln();
// Data
foreach($data as $row)
{
foreach($row as $col)
$this->Cell(40,6,$row,1);
$this->Ln();
}
}
// Better table
function ImprovedTable($header, $data)
{
// Column widths
$w = array(40, 35, 40, 45);
// Header
for($i=0;$i<count($header);$i++)
$this->Cell($w[$i],7,$header[$i],1,0,'C');
$this->Ln();
// Data
foreach($data as $row)
{
$this->Cell($w[0],6,$row[0],'LR');
$this->Cell($w[1],6,$row[1],'LR');
$this->Cell($w[2],6,$row[2],'LR',0,'R');
$this->Cell($w[3],6,$row[3],'LR',0,'R');
$this->Ln();
}
// Closing line
$this->Cell(array_sum($w),0,'','T');
}
// Colored table
function FancyTable($header, $data)
{
// Colors, line width and bold font
$this->SetFillColor(255,0,0);
$this->SetTextColor(255);
$this->SetDrawColor(128,0,0);
$this->SetLineWidth(.3);
$this->SetFont('','B');
// Header
$w = array(40, 35, 40, 45);
for($i=0;$i<count($header);$i++)
$this->Cell($w[$i],7,$header[$i],1,0,'C',true);
$this->Ln();
// Color and font restoration
$this->SetFillColor(224,235,255);
$this->SetTextColor(0);
$this->SetFont('');
// Data
$fill = false;
foreach($data as $row)
{
$this->Cell($w[0],6,$row[0],'LR',0,'L',$fill);
$this->Cell($w[1],6,$row[1],'LR',0,'L',$fill);
$this->Cell($w[2],6,$row[2],'LR',0,'R',$fill);
$this->Cell($w[3],6,$row[3],'LR',0,'R',$fill);
$this->Ln();
$fill = !$fill;
}
// Closing line
$this->Cell(array_sum($w),0,'','T');
}
}
//Create new pdf file
//Select the Products you want to show in your PDF file
$query=("SELECT name,service,type,status FROM permits");
//$name = $row['name'];
//$service = $row['service'];
//$type = $row['type'];
//$status = $row['status'];
$pdf = new PDF();
// Column headings
$header = array('Resident', 'Frontline Service', 'Type', 'Status');
// Data loading
$data = $pdf->LoadData($query);
$pdf->SetFont('Arial','',14);
$pdf->AddPage();
$pdf->BasicTable($header,$data);
$pdf->AddPage();
$pdf->ImprovedTable($header,$data);
$pdf->AddPage();
$pdf->FancyTable($header,$data);
$pdf->Output();
?>
Warning: Invalid argument supplied for foreach() in
C:\xampp\htdocs\project\heldeskback\sample_pdf3.php on line 19 FPDF
error: Some data has already been output, can't send PDF file

Why doesn't my FPDF class function SetMargins() effect the first row?

I am using the FPDF class to create a pdf based on the results from a mysql query. The information was outputted in a table to pdf as expected but my problem occurred when I used SetMargins() to set the page margins. Everything except the first row is effected. The first line seems to be hardcoded to a certain position or margin definition.
Here is my code:
class Table extends FPDF
{
public function CreateTable($header, $data)
{
//Header
$this->SetFillColor(255);
$this->SetTextColor(0);
$this->SetFont('Arial','B', 12);
foreach ($header as $col) {
$this->Cell($col[1], 10, $col[0], 1, 0, 'C');
//Cell(float w [, float h [, string txt [, mixed border [, int ln [, string align [, boolean fill [, mixed link]]]]]]])
}
$this->Ln();
//Data
$this->SetFillColor(255);
$this->SetTextColor(0);
$this->SetFont('Arial', '', 8);
foreach ($data as $row) {
$i = 0;
foreach ($row as $field) {
$this->Cell($header[$i][1], 6, $field, 1, 0, 'C');
$i++;
}
$this->Ln();
}
}
}
//column headings for the department table
$dept_header = array(array('Name', 75), array('Phone', 40), array('Fax', 40));
//column headings for the team tables
$team_header = array(array('Name', 35), array('Role', 30), array('Office', 25), array('Cell', 25), array('Email', 45), array('Pager', 25));
//get data
$query = new ConnectQuery();
$dept_data = $query->all('SELECT * FROM Table');
$team_data = $query->all('SELECT CONCAT_WS(" ", FIRST_NAME, LAST_NAME), JOB_ROLE, OFFICE_PHONE, MOBILE_PHONE, EMAIL, PAGER_NUM FROM Table2');
$pdf = new Table('P', 'mm', 'Letter');
$pdf->AddPage();
$pdf->SetMargins(5, 5);
$pdf->CreateTable($team_header, $team_data);
$pdf->CreateTable($dept_header, $dept_data);
$pdf->Output();
?>
Just define the page margin BEFORE you add the first page. The position is not reset by setMargins() call, which results in the "hardcoded postition" which was set in AddPage():
$pdf = new Table('P', 'mm', 'Letter');
$pdf->SetMargins(5, 5);
$pdf->AddPage();
There's a property in the FPDF class called $cMargin, which is used to calculate the x-offset of the text before it gets printed within the cell, but there doesn't appear to be a setter for it. It's a public property, so after you've instantiated your FPDF class, just call:
$pdf = new fpdf('P','mm','A4');
$pdf->cMargin = 0;
Or you can workaround your 1st line like
$pdf->Ln(); //workaround for 1st line
$pdf->Cell(..);

How can i print an array passed from a page to FPDF

My fpdf.php file is
<?php
require('fpdf/fpdf.php');
$prod_data = array();
if($_POST['affiliate_pdf']){
$prod_data = unserialize($_POST['affiliate_pdf']);
}
class PDF extends FPDF
{
public $prod_data;
public function createData($input){
$this->prod_data = $input;
}
function Header()
{
// Page header
global $title;
$this->SetFont('Arial','B',15);
$w = $this->GetStringWidth($title)+6;
$this->SetX((210-$w)/2);
$this->SetDrawColor(0,80,180);
$this->SetFillColor(230,230,0);
$this->SetTextColor(220,50,50);
$this->SetLineWidth(1);
$this->Cell($w,9,$title,1,1,'C',true);
$this->Ln(10);
// Save ordinate
$this->y0 = $this->GetY();
}
// Load data
function LoadData($file)
{
// Read file lines
$lines = file($file);
$data = array();
foreach($lines as $line)
$data[] = explode(';',trim($line));
return $data;
}
}
$pdf = new PDF();
// Column headings
$title = 'Title';
$header = array('AFFILIATE CHANNELS', 'TOTAL CHANNEL REVENUE', 'TOTAL SHARE OF REVENUE', 'TOTAL AFFILIATE SHARE OF REVENUE');
// Data loading
$data = $pdf->LoadData('countries.txt');
$pdf->SetFont('Arial','',14);
$pdf->AddPage();
$pdf->Cell(10,10,'Affiliate Name', 0,0,'L');
$pdf->Output();
?>
affiliate_pdf is my array which i am passing to fpdf.php . Here i want to use its values. So, i just want to ask , how can i print this array in $pdf->Cell or can i write it at any other place.
Mainly i just want to print its value on this pdf. It may be in any array format.
You can use print_r(). By defaut, it print array values but you can set a param to return values.
$pdf->Cell(10,10,print_r($your_array, true), 0,0,'L');

collection not loading in pdf file in magento

I have to export data in pdf of orders in Magento
But i got this error:
Fatal error: Call to undefined method Mage_Reports_Model_Resource_Report_Collection::getSelect() in app/code/core/Mage/Adminhtml/Block/Widget/Grid.php on line 1683
my code for getpdf action
public function getPdfFile(){
$this->_isExport = true;
$this->_prepareGrid();
$this->getCollection()->getSelect()->limit();
$this->getCollection()->setPageSize(0);
$this->getCollection()->load();
$this->_afterLoadCollection();
$pdf = new Zend_Pdf();
$page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES);
$page->setFont($font, 12);
$width = $page->getWidth();
$i=0;
foreach ($this->_columns as $column) {
if (!$column->getIsSystem()) {
$i+=10;
$header = $column->getExportHeader();
$page->drawText($header, $i, $page->getHeight()-20);
$width = $font->widthForGlyph($font->glyphNumberForCharacter($header));
$i+=($width/$font->getUnitsPerEm()*12)*strlen($header)+10;
}
}
$pdf->pages[] = $page;
return $pdf->render();
}
and my controller action code is
public function exportPdfAction(){
$fileName = 'daily_orders.pdf';
$content = $this->getLayout()->createBlock('reportneworders/adminhtml_reportneworders_grid')->getPdfFile();
$this->_prepareDownloadResponse($fileName, $content);
}
grid is working proper in admin.
csv and excel data export sucessfully but pdf cannot. any one please help me.
The foreach ($this->_columns as $column) statement which you have only prints the headers of the grid.
You have to iterate through the collection of items as well. Before the $pdf->pages[] = $page; line, add something like this:
$j = 40;
foreach ($collection as $item) {
// add code here, which is printing $item information
// Example:
$y = $page->getHeight()-$j;
$page->drawText($item->getincrement_id(), 20, $y);
$page->drawText($item->getcreated_at(), 50, $y);
// etc.
$j += 20;
}
Also, in my own code, in order the PDF export to respond to the grid filters, I had to change the function exportPdfAction() code to the following (otherwise filters were ignored):
public function exportPdfAction(){
$fileName = 'daily_orders.pdf';
$grid = $this->getLayout()->createBlock('reportneworders/adminhtml_reportneworders_grid');
$this->_initReportAction($grid);
$content = $grid->getPdfFile();
$this->_prepareDownloadResponse($fileName, $content);
}
As you see, I have added the $this->_initReportAction($grid);

Categories