Prestashop custom module draggable sort/order - php

Please tell me why I have a " Declaration of BlockRealization::updatePosition($way, $position, $id) should be compatible with ModuleCore::updatePosition($id_hook, $way, $position = NULL)"
I have this code in module.php
A similar question was here
Prestashop custom admin module draggable sort/order not working?
Under my code in module.php
<?php
if (!defined('_PS_VERSION_')) exit;
class BlockRealization extends Module {
protected $_html = '';
public function __construct() {
$this->name = 'blockrealization';
$this->tab = 'front_office_features';
$this->version = '1.0.0';
$this->author = 'XXX';
$this->need_instance = 0;
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Module realization');
$this->description = $this->l('Display realization on homepage.');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall?');
}
public function install() {
if (!parent::install() ||
!$this->registerHook('displayHeader') ||
!$this->registerHook('home') ||
!$this->createTables()
)
return false;
return true;
}
public function uninstall() {
if (!parent::uninstall() ||
!$this->removeTable())
return false;
return true;
}
protected function createTables() {
/* Realization */
$res = (bool)Db::getInstance()->execute('
CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'realization` (
`id_realization_slides` int(10) unsigned NOT NULL AUTO_INCREMENT,
`image_realization` varchar(255) NOT NULL,
`position` int(10) unsigned NOT NULL,
PRIMARY KEY (`id_realization_slides`, `image_realization`)
) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=UTF8;
');
return $res;
}
protected function removeTable() {
if (!Db::getInstance()->Execute('DROP TABLE `'. _DB_PREFIX_ . 'realization`'))
return false;
return true;
}
public function getContent() {
$output = null;
if (Tools::isSubmit('submit'.$this->name)) {
$errors = '';
if ($_FILES) {
$helper = new HelperImageUploader('realization_img');
$files = $helper->process();
if ($files) {
foreach ($files as $file) {
if (isset($file['save_path'])) {
if (!ImageManager::checkImageMemoryLimit($file['save_path']))
$errors = Tools::displayError('Limit');
if (!$errors) {
if (!ImageManager::resize($file['save_path'], dirname(__FILE__) . '/img/' . $file['name']))
$errors = Tools::displayError('error');
else {
$previous_file = Configuration::get('realization_img');
$file_path = dirname(__FILE__) . '/img/' . $previous_file;
if (file_exists($file_path))
unlink($file_path);
$realization['image_realization'] = $file['name'];
$realization['position'] = count($this->getAll());
if (!Db::getInstance()->insert('realization', $realization))
$errors = Tools::displayError('error');
}
}
unlink($file['save_path']);
}
}
}
}
if ($errors)
$output .= $this->displayError($errors);
else
$output .= $this->displayConfirmation($this->l('Settings updated'));
}
$output .= $this->generateList();
$output .= $this->displayForm();
return $output;
}
public function displayForm() {
// Init Fields form array
$fields_form[0]['form'] = array(
'legend' => array(
'title' => $this->l('Add the realization'),
),
'input' => array(
array(
'type' => 'file',
'label' => $this->l('Image:'),
'name' => 'realization_img',
'hint' => $this->l('Upload image for contact:'),
)
),
'submit' => array(
'title' => $this->l('Save'),
'class' => 'btn btn-default pull-right'
)
);
$helper = new HelperForm();
// Module, token and currentIndex
$helper->module = $this;
$helper->name_controller = $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
// Title and toolbar
$helper->title = $this->displayName;
$helper->show_toolbar = true; // false -> remove toolbar
$helper->toolbar_scroll = true; // yes - > Toolbar is always visible on the top of the screen.
$helper->submit_action = 'submit'.$this->name;
$helper->toolbar_btn = array(
'save' =>
array(
'desc' => $this->l('Save'),
'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name.
'&token='.Tools::getAdminTokenLite('AdminModules'),
),
'back' => array(
'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
'desc' => $this->l('Back to list')
)
);
// Load current value
$helper->tpl_vars = array(
'fields_value' => array(
'realization_img' => Configuration::get('realization_img')
)
);
return $helper->generateForm($fields_form);
}
public function generateList() {
$content = $this->getAll();
$fields_list = array(
'id_realization_slides' => array(
'title' => 'ID',
'align' => 'center',
'class' => 'fixed-width-xs',
),
'image_realization' => array(
'title' => $this->l('Image'),
'orderby' => false,
'search' => false
),
'position' => array(
'title' => $this->l('Position'),
'position' => 'position' ,
'orderby' => false,
'search' => false
),
);
$helper = new HelperList();
$helper->shopLinkType = '';
$helper->actions = array('edit', 'delete');
$helper->module = $this;
$helper->listTotal = count($content);
$helper->identifier = 'id_realization_slides';
$helper->title = $this->l('Realizations');
$helper->table = $this->name;
$helper->imageType = 'jpg';
$helper->orderBy = 'position';
$helper->orderWay = 'asc';
$helper->position_identifier = 'id_realization_slides';
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
return $helper->generateList($content, $fields_list);
}
public function getAll() {
return Db::getInstance()->ExecuteS('
SELECT *
FROM '._DB_PREFIX_.'realization
');
}
public function ajaxProcessUpdatePositions()
{
$way = (int)Tools::getValue('way');
$id_quicklinks = (int)Tools::getValue('id');
$positions = Tools::getValue('realization_slides');
if (is_array($positions))
foreach ($positions as $position => $value)
{
$pos = explode('_', $value);
if (isset($pos[2]) && (int)$pos[2] === $id_velcroquicklinks)
{
if (isset($position) && $this->updatePosition($way, $position, $id_quicklinks))
echo 'ok position '.(int)$position.' for id '.(int)$pos[1].'\r\n';
else
echo '{"hasError" : true, "errors" : "Can not update id '.(int)$id_quicklinks.' to position '.(int)$position.' "}';
break;
}
}
}
public function updatePosition($way, $position, $id)
{
if (!$res = Db::getInstance()->executeS('
SELECT `id_realization_slides`, `position`
FROM `'._DB_PREFIX_.'realization`
ORDER BY `position` ASC'
))
return false;
foreach ($res as $quicklinks)
if ((int)$quicklinks['id_realization_slides'] == (int)$id)
$moved_quicklinks = $quicklinks;
if (!isset($moved_quicklinks) || !isset($position))
return false;
return (Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'realization`
SET `position`= `position` '.($way ? '- 1' : '+ 1').'
WHERE `position`
'.($way
? '> '.(int)$moved_quicklinks['position'].' AND `position` <= '.(int)$position
: '< '.(int)$moved_quicklinks['position'].' AND `position` >= '.(int)$position.'
'))
&& Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'realization`
SET `position` = '.(int)$position.'
WHERE `id_realization_slides` = '.(int)$moved_quicklinks['id_quicklinks']));
}
public function hookHome($params) {
return $this->display(__FILE__, "views/templates/hook/realization.tpl");
}

Because you extend the class Module and it already has the same method which you basically override. And in PHP 7+ if you want to override or extend method you have to declare the same parameters(even if they have default values in the parent class method) and the same access level. So you just need to follow the rule and use the same declaration or you can rename your method if it's not necessary to override/extend the parent class one(and it seems so)

Related

Add data to file in Prestashop Feeder

I'm trying to add this code:
$date = date('r', strtotime($product['date_add'])); echo '<pubdate>'.$date.'</pubdate>';
to rss.php file in Prestashop Feeder module https://github.com/PrestaShop/feeder
in order to have all products in Mailchimp rss email (now it shows just one because is missing date reference)
But I don't know where to add it.
class Ps_FeederrssModuleFrontController extends ModuleFrontController
{
private function getProducts($idCategory, $nProducts, $orderBy, $orderWay)
{
$category = new Category($idCategory);
...
);
}
}
return $productsForTemplate;
}
private function getSmartyVariables()
{
$id_category = (int)Tools::getValue('id_category');
$id_category = $id_category ? $id_category : Configuration::get('PS_HOME_CATEGORY');
$number = (int)Tools::getValue('n', 4);
$number = $number > 4 ? 4 : $number;
$orderBy = Tools::getProductsOrder('by', Tools::getValue('orderby'));
$orderWay = Tools::getProductsOrder('way', Tools::getValue('orderway'));
$products = $this->getProducts($id_category, $number, $orderBy, $orderWay);
return array(
'products' => $products,
'currency' => new Currency((int)$this->context->currency->id),
'affiliate' => (Tools::getValue('ac') ? '?ac=' . (int)Tools::getValue('ac') : ''),
'metas' => Meta::getMetaByPage('index', (int)$this->context->language->id),
'shop_uri' => Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__,
'shop_name' => Configuration::get('PS_SHOP_NAME'),
'shop_email' => Configuration::get('PS_SHOP_EMAIL'),
'language_iso' => $this->context->language->iso_code,
'logo' => $this->context->link->getMediaLink(_PS_IMG_ . Configuration::get('PS_LOGO')),
);
}
public function initContent()
{
parent::initContent();
$this->context->smarty->assign($this->getSmartyVariables());
header("Content-Type:text/xml; charset=utf-8");
$this->setTemplate('module:ps_feeder/views/template/front/rss.tpl');
}
}

getting multiple customer details In codeigniter

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
}
}
}

php Prestashop- where can I find the following functions

In a Prestashop Ecommerce website I have a module that was created specially to compare and set products price in my website,
I need some help understand some of his PHP code.
The followng code set the price of a product in my website after scanning and finding the minumum price in other website link providede at the product backend page:
My Question is: How does this code works? where is the part of the code that scan the other website and get the minumum price in it?
<?php
class ProductCMP extends Module
{
public function __construct()
{
$this->name = 'productcmp';
$this->tab = 'front_office_features';
$this->version = '1.0.0';
$this->author = 'biznesownia';
parent::__construct();
$this->displayName = $this->l('ProductCMP', FALSE, NULL);
}
public function install()
{
return parent::install()
and $this->registerHook('displayAdminProductsExtra')
and $this->registerHook('actionAdminProductsControllerSaveAfter');
}
public function hookDisplayAdminProductsExtra($params)
{
$product = new Product((int) Tools::getValue('id_product'), false);
$tpl = $this->context->smarty->createTemplate(dirname(__FILE__).'/templates/tab.tpl', $this->context->smarty);
$tpl->assign('product', $product);
return $tpl->fetch();
}
public function hookActionAdminProductsControllerSaveAfter($params)
{
# set data
$id_product = (int) Tools::getValue('id_product');
$product = new Product($id_product, false, (int) $this->context->language->id);
$product->compare_active = (bool) Tools::getValue('compare_active', false);
$product->compare_link = (string) Tools::getValue('compare_link', '');
$product->compare_price = (string) Tools::getValue('compare_price', 0);
return $product->save();
}
public function compare()
{
define('PRODUCT_COMPARE_EMAIL', 'uditools#gmail.com');
set_time_limit(60*60);
# get list
$products = Db::getInstance()->executeS("
SELECT p.`id_product`, pl.`name`
FROM `"._DB_PREFIX_."product` p
LEFT JOIN `"._DB_PREFIX_."product_lang` pl ON (p.`id_product` = pl.`id_product` ".Shop::addSqlRestrictionOnLang('pl').")
WHERE
pl.`id_lang` = ".(int)$this->context->language->id."
AND p.`compare_active`=1
ORDER BY p.`id_product`
");
# job
$report = array();
foreach($products as $p)
{
try
{
$result = $this->_compareProduct((int) $p['id_product']);
if($result && $result['changed'])
{
$result['id_product'] = $p['id_product'];
$result['name'] = $p['name'];
$report[] = $result;
}
}
catch(Exception $e)
{
$report[] = array(
'id_product' => $p['id_product'],
'name' => $p['name'],
'res' => false,
'msg' => 'Exception occured',
);
}
}
# if there is nothing to report
if(!$report)
return true;
# output
$output = '';
foreach($report as $row)
{
$link = $this->context->link->getProductLink($row['id_product']);
$output .= $row['id_product'] .' - '. $row['name'] .' '. ($row['res'] ? 'Ok!' : 'Error!') .' : '. $row['msg'] ."\r\n";
}
# send mail
$tpl_vars = array(
'{report_txt}' => strip_tags($output),
'{report_html}' => nl2br($output),
);
Mail::Send(
$this->context->language->id,
'report',
'Price update report',
$tpl_vars,
PRODUCT_COMPARE_EMAIL,
'',
Configuration::get('PS_SHOP_EMAIL'),
Configuration::get('PS_SHOP_NAME'),
null,
null,
dirname(__FILE__).'/mails/',
null,
$this->context->shop->id
);
return true;
}
public function compareTest($id_product)
{
$report = $this->_compareProduct($id_product);
var_dump($report);
die;
}
protected function _compareProduct($id_product)
{
# load product
$product = new Product($id_product, false, $this->context->language->id, $this->context->shop->id);
if(!Validate::isLoadedObject($product))
return false;
if(!$product->compare_link)
return false;
$oldPrice = (float) $product->price;
//******
# request
$data = file_get_contents($product->compare_link);
# analize price
if(!preg_match('!data-free-data=\'([^\']+)\'!i', $data, $matches))
{
return array(
'res' => false,
'msg' => 'Price not found!',
);
}
//******
$prices = json_decode($matches[1], true);
$newPrice = (float) $prices['minPrice'];
if(!$newPrice)
{
return array(
'res' => false,
'msg' => 'Zero price!',
);
}
# check change
$changed = $oldPrice != $newPrice;
if(!$changed)
{
return array(
'res' => false,
'msg' => 'The price is the same.',
);
}
$newPrice += (float) $product->compare_price;
# check change
$changed = $oldPrice != $newPrice;
if(!$changed)
{
return array(
'res' => false,
'msg' => 'The price is the same.',
);
}
# update
$product->price = $newPrice;
if(!$product->save())
{
return array(
'res' => false,
'msg' => 'Not saved!',
);
}
return array(
'res' => true,
'changed' => $changed,
'msg' => 'Updated! From: '.round($oldPrice, 2).' To: '.round($newPrice, 2),
);
}
}
There are needed function
protected function _compareProduct($id_product)
{
# load product
$product = new Product($id_product, false, $this->context->language->id, $this->context->shop->id);
if(!Validate::isLoadedObject($product))
return false;
if(!$product->compare_link)
return false;
$oldPrice = (float) $product->price;
//******
# request
$data = file_get_contents($product->compare_link);
# analize price
if(!preg_match('!data-free-data=\'([^\']+)\'!i', $data, $matches))
{
return array(
'res' => false,
'msg' => 'Price not found!',
);
}
//******
$prices = json_decode($matches[1], true);
$newPrice = (float) $prices['minPrice'];
if(!$newPrice)
{
return array(
'res' => false,
'msg' => 'Zero price!',
);
}
# check change
$changed = $oldPrice != $newPrice;
if(!$changed)
{
return array(
'res' => false,
'msg' => 'The price is the same.',
);
}
$newPrice += (float) $product->compare_price;
# check change
$changed = $oldPrice != $newPrice;
if(!$changed)
{
return array(
'res' => false,
'msg' => 'The price is the same.',
);
}
# update
$product->price = $newPrice;
if(!$product->save())
{
return array(
'res' => false,
'msg' => 'Not saved!',
);
}
return array(
'res' => true,
'changed' => $changed,
'msg' => 'Updated! From: '.round($oldPrice, 2).' To: '.round($newPrice, 2),
);
}

Save as PDF in portrait orientation using Yii pdfGrid extension

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');

zend multicheckboxes form controller

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;
}

Categories