Hi I'm trying to insert API response into my MySQL database. i have converted the data into json format and I'm passing the data to mysql db using the code below each time I try to run the code 0 are inserted to mydb instead of real values
<?php
class MagnusBilling
{
protected $api_key;
protected $api_secret;
public $public_url;
public $filter = [];
public $result = [];
public function __construct($api_key, $api_secret)
{
$this->api_key = $api_key;
$this->api_secret = $api_secret;
}
public function query(array $req = array())
{
// API settings
$key = $this->api_key;
$secret = $this->api_secret;
$trading_url = $this->public_url;
$module = $req['module'];
$action = $req['action'];
// generate a nonce to avoid problems with 32bit systems
$mt = explode(' ', microtime());
$req['nonce'] = $mt[1] . substr($mt[0], 2, 6);
// generate the POST data string
$post_data = http_build_query($req, '', '&');
$sign = hash_hmac('sha512', $post_data, $secret);
// generate the extra headers
$headers = array(
'Key: ' . $key,
'Sign: ' . $sign,
);
static $ch = null;
if (is_null($ch)) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt(
$ch,
CURLOPT_USERAGENT,
'Mozilla/4.0 (compatible; MagnusBilling PHP bot; ' . php_uname('a') . '; PHP/' . phpversion() . ')'
);
}
curl_setopt($ch, CURLOPT_URL, $trading_url . '/index.php/' . $module . '/' . $action);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// run the query
$res = curl_exec($ch);
if ($res === false) {
throw new Exception('Curl error: ' . curl_error($ch));
}
$dec = json_decode($res, true);
if (!$dec) {
print_r($res);
exit;
} else {
return $dec;
}
}
public function create($module, $data = [])
{
$data['module'] = $module;
$data['action'] = 'save';
$data['id'] = 0;
return $this->query($data);
}
public function update($module, $id, $data)
{
$data['module'] = $module;
$data['action'] = 'save';
$data['id'] = $id;
return $this->query($data);
}
public function destroy($module, $id)
{
return $this->query(
array(
'module' => $module,
'action' => 'destroy',
'id' => $id,
)
);
}
public function read($module, $page = 1, $action = 'read')
{
return $this->query(
array(
'module' => $module,
'action' => $action,
'page' => $page,
'start' => $page == 1 ? 0 : ($page - 1) * 25,
'limit' => 25,
'filter' => json_encode($this->filter),
'filter' => json_encode($this->result),
)
);
}
public function buyDID($id_did, $id_user)
{
return $this->query(
array(
'module' => 'did',
'action' => 'buy',
'id' => $id_did,
'id_user' => $id_user,
)
);
}
public function getFields($module)
{
return $this->query(
array(
'module' => $module,
'getFields' => 1,
)
);
}
public function createUser($data)
{
$data['createUser'] = 1;
$data['id'] = 0;
return $this->query($data);
}
public function getModules()
{
return $this->query(
array(
'getModules' => 1,
)
);
}
public function getMenu($username)
{
return $this->query(
array(
'username' => $username,
'getMenu' => 1,
)
);
}
public function getId($module, $filed, $value)
{
$this->setFilter($filed, $value, 'eq');
$query = $this->query([
'module' => $module,
'action' => 'read',
'page' => 1,
'start' => 0,
'limit' => 1,
'filter' => json_encode($this->filter),
]);
$this->filter = [];
if (isset($query['rows'][0])) {
return $query['rows'][0]['id'];
}
}
public function clearFilter()
{
$this->filter = [];
}
public function setFilter($field, $value, $comparison = 'st', $type = 'string')
{
$this->filter[] = (object) [
'type' => $type,
'field' => $field,
'value' => $value,
'comparison' => $comparison,
];
}
}
$connect = mysqli_connect("localhost", "root", "", "api");
$magnusBilling = new MagnusBilling('92b1c021402efd293fd4b3fd0', ' 1178f001b001e29c9b7a15a1f');
$magnusBilling->public_url = "http://voip/mbilling"; // Your MagnusBilling URL
$result = $magnusBilling->read('callerid');
// Convert the JSON String into PHP Array
$array = json_decode($result, true);
// Extracting row by row
foreach($array as $row) {
// Database query to insert data
// into database Make Multiple
// Insert Query
$query .=
"INSERT INTO account VALUES
('".$row["id"]."', '".$row["cid"]."',
'".$row["name"]."'); ";
$table_data .= '
<tr>
<td>'.$row["id"].'</td>
<td>'.$row["cid"].'</td>
<td>'.$row["name"].'</td>
</tr>
'; // Data for display on Web page
}
if(mysqli_multi_query($connect, $query)) {
echo '<h3>Inserted JSON Data</h3><br />';
echo '
<table class="table table-bordered">
<tr>
<th width="45%">id</th>
<th width="10%">cid</th>
<th width="45%">name</th>
</tr>
';
echo $table_data;
echo '</table>';
}
?>
this is the response am trying to insert into mysql db
{ "rows": [ { "id": "1", "cid": "25411188205", "name": "Nairobi
Muslim Academy", "description": "", "id_user": "3", "activated": "1",
"idUserusername": "67800" } ], "count": "1", "sum": false }
In your case your $result is {"rows":....}, so you should not use foreach($array ...), you should use foreach($array['rows'] as $row) instead.
Related
I want to write function which receive me path to top element, but I can't figure out how it should work..
My example data:
$data = array(
3546456 => array(
5345345,
12312312,
56456546,
),
12312312 => array(
34534534,
5675675,
8678678,
),
567978 => array(
234,
756756,
8678678,
),
);
//I have function to return parent.
$parents = getParents(8678678); // eg. $object_id = 8678678 - return [12312312, 567978] , $object_id = 12312312 - return [3546456]
// and my recursion function I tried.
function getObjectPath($object_id) {
if ($object_id == null) {
return [];
}
$parents = getObjectParents($object_id);
foreach ($parents as $parent) {
return array($object_id => getObjectPath($parent->nid));
}
}
It doesn't work way I need, on the return in getObjectPath(8678678) I'd like to have return array like that:
array(
3546456 => array(
12312312 => array(
8678678
)
),
567978 => array(
8678678
)
);
I think you almost got it, need to have some other check before returning
$data = array(
3546456 => array(
5345345,
12312312,
56456546,
),
12312312 => array(
34534534,
5675675,
8678678,
),
567978 => array(
234,
756756,
8678678,
),
);
//I have function to return parent.
$parents = getObjectPath(8678678, $data); // eg. $object_id = 8678678 - return [12312312, 567978] , $object_id = 12312312 - return [3546456]
echo "<pre>";
print_r($parents);
// and my recursion function I tried.
function getParents($object_id, $data) {
$return = [];
foreach($data as $key => $value) {
if(in_array($object_id, $value)) {
$return[] = $key;
}
}
return $return;
}
// and my recursion function I tried.
function getObjectPath($object_id, $data) {
$return = [];
$parents = getParents($object_id, $data);
foreach($parents as $parent) {
$temp = getObjectPath($parent, $data);
if(!empty($temp)) {
$return[key($temp)][$parent] = $object_id;
} else {
$return[$parent] = $object_id;
}
}
return $return;
}
I'm trying to get the response of A SOAP Service, but I can't get the subcollections data.
When I call the ws method using a soap client software I get the next response:
<WSGLMSuit.METHODNAME xmlns="http://tempuri.org/">
<Sdtpolizadetalle>
<Empresa>1</Empresa>
<DscEmpresa>TEST</DscEmpresa>
<Rama>22</Rama>
<DscRama>COMBINADO FAMILIAR</DscRama>
<Poliza>000000</Poliza>
<DscRiesgo/>
<InicioVigencia>2019-03-18</InicioVigencia>
<FinVigencia>2019-09-18</FinVigencia>
<Productor>3311</Productor>
<NombreProductor>TEST</NombreProductor>
<Tomador>
<CodTomador>336028</CodTomador>
<NombreTomador>TEST</NombreTomador>
<Domicilio>SAAVEDRA 1174 Dpto. 0</Domicilio>
<Localidad>TRES ARROYOS</Localidad>
<CodigoPostal>7500</CodigoPostal>
</Tomador>
<DscMoneda>PESOS</DscMoneda>
<CantidadCuotas>3</CantidadCuotas>
<Suplementos>
<Suplemento>
<Suplemento>0</Suplemento>
<TipoOperacion>02</TipoOperacion>
<SubTipoOperacion>000</SubTipoOperacion>
<DscOperacion>GENERAL</DscOperacion>
<InicioVigencia>2019-03-18</InicioVigencia>
<FinVigencia>2019-09-18</FinVigencia>
<Prima>2515.95</Prima>
<Premio>3104.68</Premio>
<Cuotas>
<Cuota>
<NroCuota>1</NroCuota>
<Vencimiento>2019-03-18</Vencimiento>
<Estado>Pagada</Estado>
<Importe>519.68</Importe>
<NroCupon>1</NroCupon>
</Cuota>
<Cuota>
<NroCuota>2</NroCuota>
<Vencimiento>2019-04-18</Vencimiento>
<Estado>Vencida</Estado>
<Importe>517.00</Importe>
<NroCupon>2</NroCupon>
</Cuota>
<Cuota>
<NroCuota>3</NroCuota>
<Vencimiento>2019-05-18</Vencimiento>
<Estado>Impaga</Estado>
<Importe>517.00</Importe>
<NroCupon>3</NroCupon>
</Cuota>
</Cuotas>
</Suplemento>
</Suplementos>
</Sdtpolizadetalle>
<Sesionexpirada>false</Sesionexpirada>
</WSGLMSuit.METHODNAMEResponse>
So, I made a function in PHP with SoapClient class to make same request and get the result parsed as JSON but it doesn't giving me the "Suplementos" collection and its data.
{
"Sdtpolizadetalle": {
"Empresa": 1,
"DscEmpresa": "TEST",
"Rama": 22,
"DscRama": "COMBINADO FAMILIAR",
"Poliza": 129031,
"DscRiesgo": "",
"InicioVigencia": "2019-03-18",
"FinVigencia": "2019-09-18",
"Productor": 3311,
"NombreProductor": "TEST",
"Tomador": {
"CodTomador": 336028,
"NombreTomador": "TEST",
"Domicilio": "SAAVEDRA 1174 Dpto. 0",
"Localidad": "TRES ARROYOS",
"CodigoPostal": "7500"
},
"DscMoneda": "PESOS",
"CantidadCuotas": 3,
"Suplementos": {} // <--- HERE IS THE ISSUE
},
"Sesionexpirada": false
}
The PHP function is:
$wsdl = "http://wsdlservice.org?wsdl";
$params = $request->getParsedBody();
$options = array(
'soap_version' => SOAP_1_2,
'style' => SOAP_DOCUMENT,
'use' => SOAP_LITERAL,
'exceptions' => true,
'trace' => 1,
'cache_wsdl' => WSDL_CACHE_NONE,
'encoding' => 'UTF-8'
);
$soap = new SoapClient($wsdl, $options);
$clientRes = $soap->METHODNAME($params);
return json_encode($clientRes, JSON_PRETTY_PRINT);
Finally I got a solution. I found a function for parsing XML string to Array. So what I do is get the response as XML, save it into a file and parse it with that function. Code better than words:
function xmlToArray($xml, $options = array())
{
$defaults = array(
'namespaceSeparator' => ':',
'attributePrefix' => '#',
'alwaysArray' => array(),
'autoArray' => true,
'textContent' => '$',
'autoText' => true,
'keySearch' => false,
'keyReplace' => false
);
$options = array_merge($defaults, $options);
$namespaces = $xml->getDocNamespaces();
$namespaces[''] = null;
$attributesArray = array();
foreach ($namespaces as $prefix => $namespace) {
foreach ($xml->attributes($namespace) as $attributeName => $attribute) {
if ($options['keySearch']) $attributeName =
str_replace($options['keySearch'], $options['keyReplace'], $attributeName);
$attributeKey = $options['attributePrefix']
. ($prefix ? $prefix . $options['namespaceSeparator'] : '')
. $attributeName;
$attributesArray[$attributeKey] = (string)$attribute;
}
}
$tagsArray = array();
foreach ($namespaces as $prefix => $namespace) {
foreach ($xml->children($namespace) as $childXml) {
$childArray = xmlToArray($childXml, $options);
list($childTagName, $childProperties) = each($childArray);
if ($options['keySearch'])
$childTagName = str_replace($options['keySearch'], $options['keyReplace'], $childTagName);
if ($prefix)
$childTagName = $prefix . $options['namespaceSeparator'] . $childTagName;
if (!isset($tagsArray[$childTagName])) {
$tagsArray[$childTagName] =
in_array($childTagName, $options['alwaysArray']) || !$options['autoArray']
? array($childProperties)
: $childProperties;
} elseif (
is_array($tagsArray[$childTagName]) && array_keys($tagsArray[$childTagName])
=== range(0, count($tagsArray[$childTagName]) - 1)
) {
$tagsArray[$childTagName][] = $childProperties;
} else {
$tagsArray[$childTagName] = array($tagsArray[$childTagName], $childProperties);
}
}
}
$textContentArray = array();
$plainText = trim((string)$xml);
if ($plainText !== '') $textContentArray[$options['textContent']] = $plainText;
$propertiesArray = !$options['autoText'] || $attributesArray || $tagsArray || ($plainText === '')
? array_merge($attributesArray, $tagsArray, $textContentArray) : $plainText;
return array(
$xml->getName() => $propertiesArray
);
}
$params = array('key' => 'value') // params needed to make the request
$options = array(
'trace' => 1,
'exceptions' => true
);
try {
$soap = new SoapClient($url, $options);
$soap->method($params); // replace method name
$xmlResponse = $soap->__getLastResponse();
} catch (Exception $e) {
die(
json_encode(
[
'error' => 'Cannot request to WS. ' . $e->getMessage()
]
)
);
// save the response into an xml file for parse
// it and return its content as json
if (file_put_contents('response.xml', $xmlResponse)) {
$xmlNode = simplexml_load_file($this->tempPath);
$arrayData = xmlToArray($xmlNode);
unlink('response.xml');
return json_encode($arrayData, JSON_PRETTY_PRINT);
} else {
return json_encode(['error' => 'Error saving the response into file.']);
}
i have written this code to receive data from the Android device. it was inserted just one customer data I need to receive multiple customer details if app goes offline. but it was inserting one data into DB in offline mode also.how can i change this for multiple customer data insertions.
function index_post($customerID = false) {
if ($customerID) {
//update the record
$updateData = array();
$allowedparams = array('streetid' => 'streetid', 'name' => 'name', 'mobile' => 'mobile', 'adhaar' => 'adhaar', 'profession' => 'profession', 'address' => 'address', 'pincode' => 'pincode', 'nearby' => 'nearby', 'paddress' => 'paddress', 'isOwned' => 'isOwned');
foreach ($allowedparams as $k => $v) {
if (!$this->IsNullOrEmptyString($this->post($k, true))) {
$updateData[$v] = $this->post($k, true);
}
}
if ($this->model_customer->update($customerID, $updateData)) {
$data = array('status' => true, 'messsage' => 'cusotmer updated succesfully');
$http_code = REST_Controller::HTTP_OK;
} else {
$data = array('status' => false, 'messsage' => 'cusotmer failed to update.');
$http_code = REST_Controller::HTTP_INTERNAL_SERVER_ERROR;
}
} else {
//insert the record
$allowedparams = array('streetid' => 'streetid', 'name' => 'name', 'mobile' => 'mobile', 'adhaar' => 'adhaar', 'profession' => 'profession', 'address' => 'address', 'pincode' => 'pincode', 'cycle' => 'cycle', 'nearby' => 'nearby', 'paddress' => 'paddress', 'isOwned' => 'isOwned');
$requiredParam = array('streetid', 'name', 'mobile', 'cycle');
$insertdata = array();
foreach ($allowedparams as $k => $v) {
if (in_array($k, $requiredParam)) {
//check if its not null
if ($this->post($k) == null || trim($this->post($k)) == '') {
$data = array('status' => false, 'message' => $k . ' parameter missing or empty');
$http_code = REST_Controller::HTTP_BAD_REQUEST;
break;
}
}
$insertData[$v] = $this->post($k, true);
}
if ($customerID = $this->model_customer->create($insertData)) {
$data['customerID'] = $this->_frameCustomer2($this->model_customer->get($customerID)); //you need to put
$http_code = REST_Controller::HTTP_OK;
} else {
$data = array('status' => false, 'message' => 'unable to create customer');
$http_code = REST_Controller::HTTP_INTERNAL_SERVER_ERROR;
}
}
$this->response($data, $http_code);
}
private function _frameCustomer2($c) { //get value from index_get
$data = array();
$data['id'] = $c->id;
$data['name'] = $c->name;
$data['street'] = array('id' => $c->streetid);
$data['creationDate'] = $c->creationdate;
$data['mobile'] = $c->mobile;
$data['adhaar'] = $c->adhaar;
$data['profession'] = $c->profession;
$data['isOwned'] = ($c->isOwned == 1) ? true : false;
$data['address'] = $c->address;
$data['pincode'] = $c->pincode;
$data['status'] = $c->status;
$data['cycle'] = $c->cycle;
$data['balance'] = $c->balance;
$data['creditAvailable'] = $c->creditbalance;
$data['nearby'] = $c->nearby;
$data['accountNumber'] = $c->accountnumber;
$data['permanentAddress'] = $c->paddress;
$data['lastVisit'] = $this->model_customer->lastVisit($c->id);
return $data;
}
and my part of model function is
function create($insertdata = array()) { //new customer insert
if ($this->db->insert('customer', $insertdata)) {
return $this->db->insert_id();
} else {
return false;
}
}
function update($customerID = 0, $updateData = array()) {
$this->db->where('id', $customerID);
if ($this->db->update('customer', $updateData) && $this->db->affected_rows() == 1) {
return true;
} else {
return false;
}
Instead of customer Id, you can ask the mobile developers to send data in the form of array. In both online and offline. In case of online there will be just one element in the request array.
function index_post() {
$request_data = $this->request->body;
foreach($request_data as $key => $value)
{
//Check if customer id is present
if(Customer present)
{
Update the record
} else {
Insert the record
}
}
}
Good Afternoon
I am using the pdfGrid extension in Yii in which i am using the class EPDFGrid..
I am really confused on how to make the orientation in PORTRAIT mode. currently the rendered PDF file is in Landscape.. i tried changing this line public $orientation = 'L'; to 'P' but it did nothing..
i followed it here..
http://www.yiiframework.com/extension/pdf-grid/
is there an option in config that dictates the orientation into PORTRAIT.?
can anybody help me..
this is the code in my EPDFGrid.php
<?php
Yii::import('zii.widgets.grid.CDataColumn');
Yii::import('ext.pdfGrid.fpdf.PDF');
class EPDFGrid extends CWidget {
private $_debug = false;
protected $_pdf;
protected $_fill = false;
protected $_columnWidths = array();
protected $_visibleColumns = 0;
public $dataProvider;
public $fileName;
public $config = array();
public $columns = array();
public $labels = array();
public $orientation = 'L';
public $showTableOnEmpty = true;
public $nullDisplay = ' ';
public $emptyText;
public $hideHeader = false;
public function init() {
if ($this->columns === array()) {
if ($this->dataProvider instanceof CActiveDataProvider)
$this->columns = $this->dataProvider->model->attributeNames();
else if ($this->dataProvider instanceof IDataProvider) {
// use the keys of the first row of data as the default columns
$data = $this->dataProvider->getData();
if (isset($data[0]) && is_array($data[0]))
$this->columns = array_keys($data[0]);
}
}
$id = $this->getId();
foreach ($this->columns as $i => $column) {
if (is_string($column))
$column = $this->createDataColumn($column);
else {
if (!isset($column['class']))
$column['class'] = 'CDataColumn';
$column = Yii::createComponent($column, $this);
}
if (!$column->visible) {
unset($this->columns[$i]);
continue;
}
$this->_visibleColumns++;
if ($column->id === null)
$column->id = $id . '_c' . $i;
$this->columns[$i] = $column;
}
$default = array(
'pdfSize' => 'A4',
'title' => '',
'subTitle' => '',
'headTitle' => '',
'amount' => '',
'tableWidth' => 275,
'rowHeight' => 6,
'colAligns' => null,
'colWidths' => null,
'showLogo' => false,
'imagePath' => YiiBase::getPathOfAlias('webroot') . '/images/logo.jpg',
'headerDetails' => false,
);
$this->config = array_merge($default, $this->config);
$this->_pdf = new PDF('L', 'mm', $this->config['pdfSize']);
$this->_pdf->title = $this->config['title'];
$this->_pdf->subTitle = $this->config['subTitle'];
$this->_pdf->headTitle = $this->config['headTitle'];
$this->_pdf->amount = $this->config['amount'];
$this->_pdf->tableWidth = $this->config['tableWidth'];
$this->_pdf->rowHeight = $this->config['rowHeight'];
$this->_pdf->imagePath = $this->config['imagePath'];
$this->_pdf->showLogo = $this->config['showLogo'];
$this->_pdf->headerDetails = $this->config['headerDetails'];
$this->_pdf->SetAligns($this->config['colAligns']);
$this->_pdf->SetFont('Arial', 'B', 10);
$this->_pdf->SetLineWidth(0.5);
$this->_columnWidths = $this->_calcWidths();
$this->_pdf->SetWidths($this->_columnWidths);
$this->_pdf->AliasNbPages();
$this->_pdf->AddPage();
foreach ($this->columns as $column)
$column->init();
$this->renderItems();
}
protected function createDataColumn($text) {
if (!preg_match('/^([\w\.]+)(:(\w*))?(:(.*))?$/', $text, $matches))
throw new CException(Yii::t('zii', 'The column must be specified in the format of "Name:Type:Label",
where "Type" and "Label" are optional.'));
$column = new CDataColumn($this);
$column->name = $matches[1];
if (isset($matches[3]) && $matches[3] !== '')
$column->type = $matches[3];
if (isset($matches[5]))
$column->header = $matches[5];
return $column;
}
protected function renderItems() {
if ($this->dataProvider->getItemCount() > 0 || $this->showTableOnEmpty) {
$this->renderTableHeader();
$this->renderTableBody();
}
else
$this->_renderEmptyText();
if ($this->_debug)
Yii::app()->end();
else {
// $this->_pdf->Output($this->fileName . ' (' . date('Y-m-d') . ').pdf', 'D');
$this->_pdf->Output($this->fileName . '.pdf', 'D');
exit();
}
}
protected function renderTableHeader() {
if (!$this->hideHeader) {
// Colores y fuente en negrita
$this->_pdf->SetFillColor(245, 185, 120);
$this->_pdf->SetTextColor(0);
$this->_pdf->SetBold();
$rowHeader = array();
if ($this->labels != array()) {
$rowHeader = $this->labels;
} else {
foreach ($this->columns as $i => $column) {
if ($column->name == 'Id') {
$rowHeader[] = strtoupper($column->name);
} else {
$rowHeader[] = $column->name;
}
// $rowHeader[] = $column->grid->dataProvider->model->getAttributeLabel($column->name);
//$this->_pdf->Cell($this->_columnWidths[$i],$this->headerHeight,$data,0,0,'C',true);
}
}
$this->_pdf->Row($rowHeader, array('fill' => true, 'header' => true));
}
}
protected function renderTableBody() {
$data = $this->dataProvider->getData();
$n = count($data);
// Restauraci�n de colores y fuentes
$this->_pdf->SetFillColor(255, 242, 208);
$this->_pdf->SetTextColor(0);
$this->_pdf->SetFont('');
if ($n > 0) {
for ($row = 0; $row < $n; ++$row)
$this->renderTableRow($row);
}
else
$this->_renderEmptyText();
}
protected function renderTableRow($row) {
//var_dump($this->dataProvider);
$rowData = array();
foreach ($this->columns as $i => $column) {
$data = $this->dataProvider->data[$row];
if ($column->value !== null)
$value = $column->evaluateExpression($column->value, array('data' => $data, 'row' => $row));
else if ($column->name !== null)
$value = CHtml::value($data, $column->name);
// $rowData[] = $value===null ? $this->nullDisplay : $this->_formatString($value);
$rowData[] = $value === null ? $this->nullDisplay : utf8_decode($value);
}
$this->_pdf->Row($rowData, array('fill' => $this->_fill));
$this->_fill = !$this->_fill;
}
protected function _renderEmptyText() {
$emptyText = $this->emptyText === null ? Yii::t('zii', 'No results found.') : $this->emptyText;
$this->_pdf->Cell(array_sum($this->_columnWidths), $this->config['rowHeight'], $emptyText, 0, 0, 'L');
}
protected function _calcWidths() {
$widths = array();
$params = $this->config['colWidths'];
$visibleCols = $this->_visibleColumns;
if (!$params) {
$w = $this->_pdf->tableWidth / $visibleCols;
for ($i = 0; $i < $visibleCols; $i++)
$widths[] = $w;
} else if (is_array($params)) {
if (count($params) > $visibleCols)
throw new Exception('La cantidad de parametros supera a las columnas visibles');
if (array_sum($params) > $this->_pdf->tableWidth)
throw new Exception('La suma de los parametros supera a la longitud max de la tabla');
$nulls = 0;
$confWidth = 0;
for ($i = 0; $i < $visibleCols; $i++) {
if (empty($params[$i]))
$nulls++;
else
$confWidth += $params[$i];
}
$w = $nulls ? ($this->_pdf->tableWidth - $confWidth) / $nulls : 0;
for ($i = 0; $i < $visibleCols; $i++) {
$widths[] = empty($params[$i]) ? $w : $params[$i];
}
}
else
throw new Exception('El parametro $config[widths] debe ser un array');
return $widths;
}
protected function _formatString($string) {
$string = strtolower(utf8_decode($string));
return ucwords($string);
}
protected function _combineColumns($print = '', $config = array()) {
$default = array(
'from' => 0,
'to' => $this->_visibleColumns - 1,
'border' => 0,
'align' => 'L',
'fill' => $this->_fill,
'ln' => 1,
);
$config = array_merge($default, $config);
$b = $this->$config['border'];
$a = $this->$config['align'];
$f = $this->$config['fill'];
$ln = $this->$config['ln'];
$w = 0;
for ($i = $this->$config['from']; $i <= $this->$config['to']; $i++) {
$w += $this->_columnWidths[$i];
}
$this->_pdf->Cell($w, $this->config['rowHeight'], $print, $b, $ln, $a, $f);
if ($f)
$this->_fill = !$this->_fill;
}
}
this is the generated pdf file.
<?php
$data_provider = $model->viewEmployees($search, $from, $to);
$data_provider->pagination = false;
$this->widget('ext.pdfGrid.EPDFGrid', array(
'id' => 'employee-pdf',
'fileName' => 'Employees',
'dataProvider' => $model->viewEmployees($search, $from, $to),
'columns' => array(
array('name' => 'ID Number','value' => '$data->company_id', 'htmlOptions'=>array('width'=>'10%'),),
array('name' => 'Name', 'header' => 'Name', 'value' => '$data->getNameWithMiddleInitial()', 'htmlOptions' => array('width'=>'10%')),
array('name' => 'Date Employed', 'value' => '$data->date_employed' ,'htmlOptions'=>array('width'=>'10%')),
),
'config' => array(
'title' => 'Sprasia Philippines Information Management System',
'subTitle' => 'List of Employees',
'headerDetails' => true,
'showLogo' => true,
'colAligns' => array('C', 'C', 'C'),
),
));
?>
please help..
so silly of me..
i have found it. in this line..
$this->_pdf->AddPage();
i indicated P for portrait.. in which i have solved it by using this
$this->_pdf->AddPage('P');
Merged with multicheckboxes zend form multi populate.
i did do the form with multicheckboxs and it works fine when insert or update but the my problem is how to populate all the multi boxes that is checked form the database this is the code but it doesn't show just one checkbox is checked
$id = (int) $this->_request->getParam('id');
//The incoming request
$request = $this->getRequest();
//initialize form
$form = new Admin_Form_DownFooterTab();
//instance of db
$db = Zend_Db_Table::getDefaultAdapter();
if ($this->getRequest()->isPost()) {
if ($form->isValid($request->getPost())) {
if (isset($id) && $id != "") {
$gettag = $form->getValue('tag_id');
$gettags = count($gettag);
try {
//shift the orders to
$select = $db->select()->from(array('t' => 'tab'), array('t.id',
't.title',
't.tab_position',
't.order',
't.is_active',
't.is_deleted'))->where('id = ?', $id);
$currentTab = $db->fetchRow($select);
$var3 = array('tab.order' => new Zend_Db_Expr('tab.order - 1'));
$var4 = array('tab.order >= ' . $currentTab['order'], 'is_active=1', 'is_deleted=0', 'tab_position=4');
$db->update('tab', $var3, $var4);
$var = array('tab.order' => new Zend_Db_Expr('tab.order + 1'));
$var2 = array('tab.order >= ' . $form->getValue('order'), 'is_active=1', 'is_deleted=0', 'tab_position=4');
$db->update('tab', $var, $var2);
$db->delete('tab_tag', array('tab_id = ?' => $id));
foreach ($gettag as $value) {
$db->insert('tab_tag',
array(
'tag_id' => $value,
'tab_id' => $id
));
}
$db->update('tab', array(
'title' => $form->getValue('title'),
'body' => $form->getValue('body'),
'is_active' => $form->getValue('is_active'),
'banner_link' => $form->getValue('banner_link'),
'tab_path' => $form->getValue('tab_path'),
'link_open' => $form->getValue('link_open'),
'tab_position' => $form->getValue('tab_position'),
'tab_parent' => $form->getValue('tab_parent')
),
array('id =?' => $id));
$this->flash('Tab Updated', 'admin/tab');
} catch (Exception $e) {
$this->flash($e->getMessage(), 'admin/tab');
}
} else {
try {
$formValues = $form->getValues();
$formValues['created_by'] = 1;
$formValues['created_date'] = date('Y/m/d H:i:s');
$formValues['is_deleted'] = 0;
$var = array('tab.order' => new Zend_Db_Expr('tab.order + 1'));
$var2 = array('tab.order >= ' . $form->getValue('order'), 'is_active=1', 'is_deleted=0', 'tab_position=4');
$db->update('tab', $var, $var2);
foreach ($gettag as $value) {
$db->insert('tab_tag',
array(
'tag_id' => $value,
'tab_id' => $id
));
}
$db->insert('tab', array(
'title' => $form->getValue('title'),
'body' => $form->getValue('body'),
'is_active' => $form->getValue('is_active'),
'banner_link' => $form->getValue('banner_link'),
'tab_path' => $form->getValue('tab_path'),
'link_open' => $form->getValue('link_open'),
'tab_position' => $form->getValue('tab_position'),
'tab_parent' => $form->getValue('tab_parent')
));
$this->flash('Tab inserted', 'admin/tab');
} catch (Exception $e) {
$this->flash($e->getMessage(), 'admin/tab');
}
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
if (isset($id) && $id != "") {
$values = $db->fetchRow("SELECT * FROM tab WHERE id = ?", $id);
$form->populate($values);
}
$this->view->form = $form;
}
$ddlCat_parent->setMultiOptions($cats);
$this->view->form = $form;
}