error in creating more charts in looping - php - php

I'm trying to create country based charts. i'm using pchart for this, because it will create charts as image by default.
I've created a function which creates barchart. I'm selecting countries and its stats and passing it to the barchart function which creates a chart as a flat file.
When i pass a single a country stats it is creating chart. the problem is when i try to post more than one country, it is creating only one country image not more than that. i don't know where the issue exists? Help appreciated.
sample code is here:
<?php
$con=mysql_connect("localhost","root","");
$ln=mysql_select_db("conif_new",$con);
$qry="select country from chart group by country limit 2";
$cnlist=mysql_query($qry);
while($row=mysql_fetch_row($cnlist)){
$cn=$row[0];
$nqry="select server,count(*) from chart where country='$cn' group by server";
$dset=mysql_query($nqry);
$x="";
$xt="";
while($crow=mysql_fetch_row($dset)){
$x.=$crow[1].",";
$xt.=$crow[0].",";
}
$x=substr($x,0,strlen($x)-1);
$xt=substr($xt,0,strlen($xt)-1);
//echo "$x**$xt<br>";
if(barChart($x,$xt,$cn)){}
}
function barChart($x,$xt,$name){
$x=explode(",",$x);
$xt=explode(",",$xt);
/* CAT:Bar Chart */
/* pChart library inclusions */
include("class/pData.class.php");
include("class/pDraw.class.php");
include("class/pImage.class.php");
/* Create and populate the pData object */
$MyData = new pData();
$MyData->addPoints($x,"Server A");
$MyData->setAxisName(0,"Hits");
$MyData->addPoints($xt,"Months");
$MyData->setSerieDescription("Months","Month");
$MyData->setAbscissa("Months");
/* Create the pChart object */
$myPicture = new pImage(700,230,$MyData);
$myPicture->drawGradientArea(0,0,700,230,DIRECTION_VERTICAL,array("StartR"=>240,"StartG"=>240,"StartB"=>240,
"EndR"=>180,"EndG"=>180,"EndB"=>180,"Alpha"=>100));
$myPicture->drawGradientArea(0,0,700,230,DIRECTION_HORIZONTAL,array("StartR"=>240,"StartG"=>240,"StartB"=>240,
"EndR"=>180,"EndG"=>180,"EndB"=>180,"Alpha"=>20));
$myPicture->setFontProperties(array("FontName"=>"fonts/verdana.ttf","FontSize"=>9));
/* Draw the scale */
$myPicture->setGraphArea(50,30,680,200);
$myPicture->drawScale(array("CycleBackground"=>TRUE,"DrawSubTicks"=>TRUE,"GridR"=>0,"GridG"=>0,"GridB"=>0,
"GridAlpha"=>10));
/* Turn on shadow computing */
$myPicture->setShadow(TRUE,array("X"=>1,"Y"=>1,"R"=>0,"G"=>0,"B"=>0,"Alpha"=>10));
/* Draw the chart */
$settings = array("Gradient"=>TRUE,"DisplayPos"=>LABEL_POS_INSIDE,"DisplayValues"=>TRUE,"DisplayR"=>255,
"DisplayG"=>255,"DisplayB"=>255,"DisplayShadow"=>TRUE,"Surrounding"=>10);
$myPicture->drawBarChart($settings);
/* Write the chart legend */
$myPicture->drawLegend(580,12,array("Style"=>LEGEND_NOBORDER,"Mode"=>LEGEND_HORIZONTAL));
/* Render the picture (choose the best way) */
//$myPicture->autoOutput("pictures/example.drawBarChart.shaded.png");
if($myPicture->render("C:/wamp/www/chart/".$name.".png"))
echo "true";
else
echo "false";
}
?>

I found an answer!!!, just noticed "include statements" inside barchart function. Removed it, Thats it!
I should've placed "include_once" instead of "include" or should've moved the "include" statements outside the function to make it work.

Related

Change charts title by PhpOffice\PhpSpreadsheet in template

I try to change chart title in .xlsx template
I open template, change cels ,write to output.
Q: How to change chart title....
$reader = IOFactory::createReader( 'Xlsx' );
$reader->setIncludeCharts( true );
$spreadsheet = $reader->load( storage_path( 'app/template.xlsx' ) );
$spreadsheet->getActiveSheet()->setCellValue( 'B3', 'Blabla' );
//create new from template
$writer = new Xlsx( $spreadsheet );
$writer->setPreCalculateFormulas( true );
$writer->setIncludeCharts( true );
##how to change title in all/first charts in template?
I finally found the method. There are a few things to understand.
chartIndex - In an excel file, an id assigned to the chart based on the total number of charts starting from the first left most chart on a sheetA incrementing to the last right most chart on SheetC. This index is the entire collection of all charts on all sheets starting with chart1 and ending with chartX. If you have ten charts chart1,chart2,...chart10 and delete chart5, you will then have a new index of chart1,chart2....chart9, where the orig chart6-10 are all redindexed as chart5-9. In phpspreadsheet, this index appears to be represented with $chart->getName() ;, There is no corresponding setName() that would allow you to change/alter the index.
chartName - In an excel file, if you highlight a chart, in the upper left corner of the cells, above the A column, is a "chart name" drop down. You can name your charts for organization purposes. In excel, this field can be edited. In phpspreadsheet, I have yet to have find what object can get/set this field.
chartTitle - the in chart name of a chart, IE: "Annual Revenue Projections". In phpspreadsheet, this field is represented with $chart->getTitle->get/setCaptionText
So in order to find the chart you are looking to modify, you either must already know the chart index (ie: getName()) OR the chart visual title (ie: getCaptionText() ).
Because of adding deleting moving charts, I found it easier, in the excel template, to add visual titles to your charts then search for those titles/captionText in your code. This way you don't have to have worry about tracking which chart is which index. Use the getCaptionText to then get the getName() index.
foreach ($spreadsheet->getSheetByName("SheetName")->getChartCollection() as $chart) {
// if you know TITLE of the chart
// TITLE is the visible title in the chart
// Easy to know if you set the titles yourself in the template chart
// A template chart TITLE cannot be a cell reference, will cause an error on file import
if ($chart->getTitle()->getCaptionText() == "Chart_12") {
$curIndex = $chart->getName() ; // = "chart3"
$curTitle = $chart->getTitle()->getCaptionText() ; // "Chart_12"
$chart->getTitle()->setCaption("Quarterly Revenue Chart") ;
break ;
}
// if you know the NAME (chart id) the chart
// NAME is like the hidden chart index
if ($chart->getName() == "chart12") {
$chart->getTitle()->setCaption("New Chart Title") ;
break ;
}
}

organic group drupal 7 views_get_views

Trying to use views_get_views on the organic groups view OG all user group content to programmatically access the view using php. I am unable to set the parameter properly. I would like to get an example of working call.
Thanks,
Olivier
Try This:
/* load view object */
$views = views_get_view('og_all_user_group_content');
/* set default display */
$views->set_display('default');
/* pass group id as argument value */
$group_id =''; //set your group id here
$views->set_arguments(array($group_id));
/* execute view */
$views->execute();
/* result object */
if (!empty($views->result)) {
if (count($views->result) > 0) {
foreach ($views->result as $result) {
//$result contain array of data.
}
}
}

SetSerieDescription - pChart not working

I'm trying to assign a label to the x axis of a Bar Chart, the label is a normal text string stored in an array under $gsettings['axisXlabel']. Unfortunatly pCharts SetSerieDescription doesn't seem to be working as expected.
Below is the function producing the graphs and an attachment of the current output. The part of interest is the 3 lines under /* Bind a data series to the X axis */
/**
* function to plot bar charts
*/
function cg_graphs_plot_bar_graph($gdata, $gsettings){
$graph_data = new pData();
if(isset($gdata['bar_plots2'])){ //if this is set, its a duel bar graph
$graph_data->addPoints($gdata['bar_plots'],"surgeondata");
$graph_data->addPoints(array(0,0,0,0),"surgeondatanull");
$graph_data->addPoints($gdata['bar_plots2'],"everyonedata");
$graph_data->addPoints(array(0,0,0,0),"everyonedatanull");
$graph_data->setSerieDrawable(array("everyonedatanull"), FALSE);
$graph_data->setSerieDescription("surgeondata",$gdata['surgeonname']);
$graph_data->setSerieDescription("everyonedata","All Surgeons");
$graph_data->setAxisUnit(0,"%");
$surgeon = array("R"=>21,"G"=>0,"B"=>0); //surgeon series colour
$all = array("R"=>191,"G"=>160,"B"=>36); //everyone series colour
$graph_data->setPalette("surgeondata",$surgeon);
$graph_data->setPalette("everyonedata",$all);
$graph_data->setPalette("surgeondatanull",$surgeon);
$graph_data->setPalette("everyonedatanull",$all);
} else {
$graph_data->addPoints($gdata['bar_plots'],"percentiles");
$graph_data->addPoints($gdata['surgeon_bar'],"surgeonbar");
$graph_data->setSerieDrawable(array("surgeonbar"), FALSE);
}
$graph_data->setAxisName(0,$gsettings['axisYlabel']);
/* Bind a data serie to the X axis */
$graph_data->addPoints($gdata['xaxis_names'],"Labels");
$graph_data->setSerieDescription("Labels",$gsettings['axisXlabel']);
$graph_data->setAbscissa("Labels");
$width=540;
$height=419;
$chart = new pImage($width,$height,$graph_data);
$chart->drawFromJPG(0,0,drupal_get_path('module', 'cg_graphs')."/images/graphbg.jpg");
/* Write the picture title */
$chart->setFontProperties(array("FontName"=>drupal_get_path('module', 'cg_graphs')."/pChart/fonts/ARIAL.TTF","FontSize"=>8));
$chart->setFontProperties(array("R"=>0,"G"=>0,"B"=>0));
$chart->drawText(270,70,$gsettings['title'],array("R"=>0,"G"=>0,"B"=>0,"Align"=>TEXT_ALIGN_MIDDLEMIDDLE, "FontSize" => 12));
/* Set the graph area */
$chart->setGraphArea(70,120,490,310);
/* Draw a rectangle */
$chart->drawFilledRectangle(70,120,489,309,array("R"=>255,"G"=>255,"B"=>255,"Dash"=>FALSE, "BorderR"=>201,"BorderG"=>201,"BorderB"=>201));
/* Turn on shadow computing */
$chart->setShadow(TRUE,array("X"=>1,"Y"=>1,"R"=>0,"G"=>0,"B"=>0,"Alpha"=>20));
$format = array(
"DisplayValues"=>FALSE,
"DisplayColor"=>DISPLAY_AUTO,
"Rounded"=>FALSE,
"Gradient"=>TRUE,
"GradientAlpha"=>100,
"GradientMode"=>GRADIENT_EFFECT_CAN,
"GradientStartR"=>251,
"GradientStartG"=>220,
"GradientStartB"=>96,
"GradientEndR"=>191,
"GradientEndG"=>160,
"GradientEndtB"=>36
);
if(isset($gdata['bar_plots2'])){
/* Draw the scale */
$chart->drawScale(array("XMargin"=>50, "Mode"=>SCALE_MODE_MANUAL, "ManualScale"=> $gsettings['maxmin'], "Pos" => SCALE_POS_LEFTRIGHT,'DrawXLines' => FALSE, 'GridTicks' => 500,'GridR'=>0,'GridG'=>0,'GridB'=>0, 'LabelRotation'=>0, 'AroundZero' => TRUE, 'Interleave' => 0.1));
$graph_data->setSerieDrawable(array("surgeondata"), FALSE);
$graph_data->setSerieDrawable(array("surgeondatanull"), TRUE);
} else {
/* Draw the scale*/
$chart->drawScale(array("XMargin"=>40, "Mode"=>SCALE_MODE_MANUAL, "ManualScale"=> $gsettings['maxmin'], "Pos" => SCALE_POS_LEFTRIGHT,'DrawXLines' => FALSE, 'GridTicks' => 500,'GridR'=>0,'GridG'=>0,'GridB'=>0, 'LabelRotation'=>0, 'AroundZero' => TRUE));
}
$chart->drawBarChart($format);
//draw next bar with new colour.
$format = array(
"DisplayValues"=>FALSE,
"DisplayColor"=>DISPLAY_AUTO,
"Rounded"=>FALSE,
"Gradient"=>TRUE,
"GradientAlpha"=>100,
"GradientMode"=>GRADIENT_EFFECT_CAN,
"GradientStartR"=>255,
"GradientStartG"=>230,
"GradientStartB"=>126,
"GradientEndR"=>21,
"GradientEndG"=>0,
"GradientEndtB"=>0
);
if(!isset($gdata['bar_plots2'])){ //not set? we need to draw the second one.
//set draw series to false / true here
$graph_data->setSerieDrawable(array("percentiles"), FALSE);
$graph_data->setSerieDrawable(array("surgeonbar"), TRUE);
$chart->drawBarChart($format);
} else {
$graph_data->setSerieDrawable(array("surgeondatanull", "everyonedata"), FALSE);
$graph_data->setSerieDrawable(array("surgeondata", "everyonedatanull"), TRUE);
$chart->drawBarChart($format);
$graph_data->setSerieDrawable(array("everyonedatanull"), FALSE);
$graph_data->setSerieDrawable(array("everyonedata"), TRUE);
$chart->drawLegend(190,100,array("Style"=>LEGEND_NOBORDER, "Mode" => LEGEND_HORIZONTAL)); //draw legand
}
$imagename = str_replace(' ', '-', $gdata['surgeonname']);
$chart->render(drupal_get_path('module', 'cg_graphs')."/pChart/examples/pictures/".$imagename."-".$gsettings['name'].".png");
}
And here's the output, I want to label the Xaxis, currently the label isn't showing. (sorry for removed title etc, data isn't in the public domain yet and names needed removing)
You need to use the function setAbscissaName as defined in http://wiki.pchart.net/doc.dataset.setabscissaname.html
Example:
$MyData->setAbscissaName("Months");
This will display Months in the X axis under ticks.
The pChart documentation is a mess. I've found an error or two where the documentation differs from the source code. Their naming scheme also needs work. It's unintuitive to anyone besides the creator.
I believe you are trying to add a label to the X-Axis. In order to do this, you need to use setXAxisName().
The "Temperature" that appears in the code for setSerieDescription() is a string that is used to tie that set of series data to that name. It is not actually the label that appears on the chart (which is the same name). It is the name that is used again in setAbscissa().

PHP: passing array elements into class function in fpdf

Working on a project and need to generate pdf of the product details using FPDF. The product details are passed into an array and I need the following to get each of the variable elements in the array '$prod_details' into the functions within the class 'PDF' as shown below:
Examples of how I tried passing the variable array elements:
$this->Cell(30,8,$prod_data['prod_name'],0,0,'C');
$this->Cell(30,10,$prod_data['company_name']);
$this->Cell(20,8,$prod_data['prod_cost'],0,0,'C');
I have tried running this script but I keep getting an error message 'Cannot access empty property'...
find the codes below
<?php
#include_once("includes/db.php");
require('fpdf/fpdf.php');
#include_once("includes/class_product_info.php");
$obj = new allProducts();
$prod_data = array();
if(isset($_GET['c_id'])){
$prod_data = $obj->getProdDetails($_GET['c_id']);
class PDF extends FPDF
{
public $prod_data;
public function createData($input){
$this->prod_data = $input;
}
function Header()
{
// Logo
$this->Image('big_logo.png',10,6,30);
// Arial bold 15
$this->SetFont('Arial','B',20);
// Move to the right
$this->Cell(40);
// Title
$this->Cell(30,10,$this->prod_data['company_name']);
// Draw an header line
$this->Line(10,26,200,26);
// Line break
$this->Ln(20);
}
function Footer()
{
// Position at 1.5 cm from bottom
$this->SetY(-15);
// Begin with regular font
$this->SetFont('Arial','',9);
// Then put a blue underlined link
//$this->SetTextColor(0,0,255);
$this->SetFont('','U');
$this->Write(10,$this->prod_data['company_name'],'http://www.skills.com');
// Arial italic 8
$this->SetFont('Arial','I',9);
// Page number
$this->Cell(0,10,'Page '.$this->PageNo().' ',0,0,'R');
}
function prodDetailTop()
{
// Course title cell
$this->Cell('',10,'',0,0,'C');
$this->Ln();
/* Build cells for the first row */
$this->SetFont('Arial','',10);
$this->SetY(40);
// First Row
$this->Cell(35,8,'Product Name : ',0,0,'L');
$this->Cell(30,8,$this->prod_data['prod_name'],0,0,'C');
$this->SetX(150);
$this->Cell(25,8,'Product Cost : ',0,0,'L');
$this->Cell(20,8,$this->prod_data['prod_cost'],0,0,'C');
$this->Ln();
// Second Row
$this->Cell(35,8,'Discount : ',0,0,'L');
$this->Cell(30,8,$this->prod_data['disc_amt'],0,0,'L');
$this->SetX(150);
$this->Cell(25,8,'No Purchased : ',0,0,'L');
$this->Cell(20,8,$this->prod_data['items_count'].' product(s)',0,0,'L');
$this->Ln();
}
function prodDetailBtm()
{
$this->SetY(80);
$this->Write(10,$this->prod_data['prod_desc']);
}
function generatePageData()
{
$this->AddPage();
$this->prodDetailTop();
$this->prodDetailBtm();
}
}
$pdf = new PDF();
$pdf->createData($prod_data);
//$pdf->Header();
$pdf->generatePageData();
$pdf->Output();
}
else {
?>
<script language="javascript">
window.location = "prod_invoice_err.php";
</script>
<?php
}
?>
Hope to get some help.
Your question is a little vague. It would be helpful it you asked specifically what you're trying to accomplish.
But the first thing I see is that your subclass of the fpdf class, you don't need to write functions to do each and everything you want to do with the pdf. You only need to extend the parts of the class you are overriding (or extending), like header and footer.
So extend it, manipulate header and footer, then close the class. Create your $pdf instance of your new fpdf class, then manipulate that object with your data. You don't need to 'pass in' that data at all.
for instance:
$pdf->Ln(10);
$pdf->Cell($w,9,$title,1,1,'C',true); //from fpdf tutorial
Or, if that doesn't accomplish what you want (although I can't see why it wouldn't, I've done this lots of times), you can always override the constructor. Pass in an array (or event a custom object that you create), and store that in a private variable.

need some tips on Drupal $form value

I got dpm($form) working. Nice! This is much better way to view data. I am still trying to figure out where stuff is coming from eg: location longitude & latitude. The word 'longitude' is referenced in 20 different places. I thought this was a likely place to isolate text box for this input field. dpm($form['#field_info']['field_store_latitude']['location_settings']['form']['fields']);
Any tips on how to track down individual input elements?
** this is not an answer, but a supplement to my first question **
hi googletorp -
I am trying to modify existing forms using hook_form_alter.
After several hours of poking around, I can now turn off location (longitude/latitude) section of a form like this:
unset($form['field_store_latitude']);
However, turning off just the latitude like this, does not work:
unset($form['field_store_latitude']['0']['#location_settings']['form']['fields']['locpick']);
I cannot find a easy way to link id and names in html source with arrays produced by Krumo.
In this case id is called "edit-field-store-latitude-0-locpick-user-latitude".
I need a recipe or guidelines for identifying form elemets in Drupal form.
I think I nailed down a solution
<?php
// allows you to alter locations fields, which are tricky to access.
// this will require a patch in location module described here:
// http://drupal.org/node/381458#comment-1287362
/**
* Implementation of custom _element_alert() hook.
*/
function form_overrides_location_element_alter(&$element){
// change some location descriptions
$element['locpick']['user_latitude']['#description'] = ' ' . t('Use decimal notation.');
$element['locpick']['user_longitude']['#description'] = ' ' . t('See <a href=!url target=_blank>our help page</a> for more information.', array('!url' => url('latlon_help')));
// or make them disappear entirely
unset($element['locpick']['user_longitude']);
unset($element['locpick']['user_latitude']);
}
/**
* Implementation of form_alter hook.
*/
function form_overrides_form_alter(&$form, $form_state, $form_id) {
switch ($form_id) {
case 'user_profile_form':
// change titles in user profile form
$form['account']['name']['#title'] = t('Login Name');
$form['account']['mail']['#title'] = t('Email');
break;
case 'retailer_node_form':
// let's check what is supposed to be here...
print '<pre>';
//print_r($form);
dsm($form);
print '</pre>';
// this works to remove the city
unset($form['field_myvar_latitude']['0']['#location_settings']['form']['fields']['city']);
// let's try #after_build property
$form['#after_build'][]='mymodule_after_build_mynode';
break;
}
}
function mymodule_after_build_mynode($form, $form_values) {
// This will not work for locations fields
return $form;
}`enter code here`
So there is sneaky way to alter the location field, what you need to do is to use the #after_built callback:
/**
* Implements hook_form_alter().
*/
function mymodule_form_alter(&$form, $form_state, $form_id) {
if ($form_id == 'x_node_form') {
// alter the location field
if (isset($form['locations'])) {
$form['locations']['#after_build'][] = 'mymodule_alter_location_field';
}
}
}
/**
* Remove the delete checkbox from location element.
*/
function mymodule_alter_location_field($form_element, &$form_state) {
$location = $form_element[0]; // The location field which you can alter
return $form_element;
}

Categories