cakephp 2.X override table prefix dynamically on join action - sql

I a cakephp setup to manage multiple web-sites in which they a number of common models, with the table prefix 'main_'. And there's common model Fbuser is using a table 'main_fb_users'
And now, I have a web-site, and its table prefix is 'myweb_', and I have a model, Mymodel, which have to be left-join with Fbuser.
$this->Mymodel->find('all', array(
'joins' => array(
'table' => 'main_fb_users',
'alias' => 'Fbuser',
'type' => 'LEFT',
'conditions' => array('Mymodel.field01 = Fbuser.field02')
));
and here's the error message I have got
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dbserver.myweb_main_fb_users' doesn't exist
obviously, it's due to the different in the table prefix, and I can't change the default table prefix set in the database.php.
so how can I override the table prefix inside the join query?

Pass the model object instead of the table name as a string:
$this->Mymodel->find('all', array(
'joins' => array(
'table' => $this->Mymodel->FbUser,
'alias' => 'Fbuser',
'type' => 'LEFT',
'conditions' => array('Mymodel.field01 = Fbuser.field02')
));
Seems to work for me.

Hacked Method (for version 2.x)
Go to - /lib/Cake/Model/Datasource/DboSource.php line #942
Modify the function fullTableName as below:
public function fullTableName($model, $quote = true, $schema = true, $prefix = true) {
if (is_object($model)) {
$schemaName = $model->schemaName;
$table = $model->tablePrefix . $model->table;
} elseif (!empty($this->config['prefix']) && strpos($model, $this->config['prefix']) !== 0) {
$table = (((!empty($prefix) && $prefix !== true)?$prefix:(($prefix === false)?'':$this->config['prefix'] ))). strval($model);
} else {
$table = strval($model);
}
if ($schema && !isset($schemaName)) {
$schemaName = $this->getSchemaName();
}
if ($quote) {
if ($schema && !empty($schemaName)) {
if (strstr($table, '.') === false) {
return $this->name($schemaName) . '.' . $this->name($table);
}
}
return $this->name($table);
}
if ($schema && !empty($schemaName)) {
if (strstr($table, '.') === false) {
return $schemaName . '.' . $table;
}
}
return $table;
}
Now go to line #1881 on same page and modify the function buildJoinStatement as:
public function buildJoinStatement($join) {
$data = array_merge(array(
'type' => null,
'alias' => null,
'table' => 'join_table',
'conditions' => '',
), $join);
if (!empty($data['alias'])) {
$data['alias'] = $this->alias . $this->name($data['alias']);
}
if (!empty($data['conditions'])) {
$data['conditions'] = trim($this->conditions($data['conditions'], true, false));
}
if (!empty($data['table']) && (!is_string($data['table']) || strpos($data['table'], '(') !== 0)) {
$data['table'] = (isset($data['prefix']))?$this->fullTableName($data['table'],true,true,$data['prefix']):$this->fullTableName($data['table']);
}
return $this->renderJoinStatement($data);
}
thats it...
now if you provide a prefix element in joins array then it will use the same prefix for that table.
Example
'joins'=>array(
array(
'table'=>'GDN_Comment',
'type'=>'LEFT',
'prefix'=>false,
'alias'=>'Comment',
'conditions'=>array('MyPost.DiscussionID = 2'),
),
),
Then it will use "GDN_Comment as Comment" in sql query
OR
'joins'=>array(
array(
'table'=>'GDN_Comment',
'type'=>'LEFT',
'prefix'=>'ds_',
'alias'=>'Comment',
'conditions'=>array('MyPost.DiscussionID = 2'),
),
),
Then it will use "ds_GDN_Comment as Comment" in sql query

You can adjust the table prefix on the fly in the controller:
$this->loadModel('MainFbUser');
$this->MainFbUser->tablePrefix = '';
In the documentation:
http://book.cakephp.org/2.0/en/models/model-attributes.html#tableprefix

Related

Prestashop 1.7.4.x - Missing variables values when using order_conf as new email template

I have missing variables when using a new email template.
I have not changed any core code for this email template.
Is anyone can help me on this ?
[ I'm using Prestashop 1.7.4.x ]
Finally i found one solution for this. Maybe someone will get help from my solution.
I've modified classes/order/OrderHistory.php and replace following code.
$data = array(
'{lastname}' => $result['lastname'],
'{firstname}' => $result['firstname'],
'{id_order}' => (int)$this->id_order,
'{order_name}' => $order->getUniqReference()
);
Replaced above code with following one.
/*----------------------
-START OF INSERTED CODE-
----------------------*/
/* GET THE PRODUCTS */
$order_details = $order->getProducts();
$product_var_tpl_list = array();
foreach ($order_details as $id => &$order_detail) {
$product_var_tpl = array(
'reference' => $order_detail['product_reference'],
'name' => $order_detail['product_name'].(isset($order_detail['product_attributes']) ? ' - '.$order_detail['product_attributes'] : ''),
'unit_price' => Tools::displayPrice($order_detail['unit_price_tax_incl'], $this->context->currency, false),
'price' => Tools::displayPrice($order_detail['total_price_tax_incl'], $this->context->currency, false),
'quantity' => $order_detail['product_quantity'],
'customization' => $order_detail['customizedDatas']
);
$product_var_tpl_list[] = $product_var_tpl;
} // end foreach ($order_detail)
$product_list_txt = '';
$product_list_html = '';
if (count($product_var_tpl_list) > 0) {
$product_list_txt = $this->getEmailTemplateContent('order_conf_product_list.txt', Mail::TYPE_TEXT, $product_var_tpl_list);
$product_list_html = $this->getEmailTemplateContent('order_conf_product_list.tpl', Mail::TYPE_HTML, $product_var_tpl_list);
}
/* GET THE DISCOUNTS */
$cart_rules = $order->getCartRules();
foreach ($cart_rules as $id => &$cart_rule) {
$cart_rules_list[] = array(
'voucher_name' => $cart_rule['name'],
'voucher_reduction' => ($cart_rule['value'] != 0.00 ? '-' : '').Tools::displayPrice($cart_rule['value'], $this->context->currency, false)
);
}
$cart_rules_list_txt = '';
$cart_rules_list_html = '';
if (count($cart_rules_list) > 0) {
$cart_rules_list_txt = $this->getEmailTemplateContent('order_conf_cart_rules.txt', Mail::TYPE_TEXT, $cart_rules_list);
$cart_rules_list_html = $this->getEmailTemplateContent('order_conf_cart_rules.tpl', Mail::TYPE_HTML, $cart_rules_list);
}
/* GET ORDER DETAILS, delivery, invoice, amount... etc */
$invoice_address = new Address((int)$order->id_address_invoice);
$invoiceAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_INVOICE_ADDR_RULES'), true);
$deliveryAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_DELIVERY_ADDR_RULES'), true);
$country = new Country((int)$invoice_address->id_country);
$delivery_address = null;
$formatted_delivery_address = '';
if (isset($order->id_address_delivery) && $order->id_address_delivery) {
$delivery_address = new Address((int)$order->id_address_delivery);
}
$carrier = new Carrier((int)($order->id_carrier), $order->id_lang);
/* ATTACH INFORMATION TO SMARTY VARIABLE*/
$data = array(
'{lastname}' => $result['lastname'],
'{firstname}' => $result['firstname'],
'{id_order}' => (int)$this->id_order,
'{delivery_block_txt}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, ', ', ' '),
'{invoice_block_txt}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, ', ', ' '),
'{delivery_block_html}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{invoice_block_html}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{delivery_company}' => $delivery_address->company,
'{delivery_firstname}' => $delivery_address->firstname,
'{delivery_lastname}' => $delivery_address->lastname,
'{delivery_address1}' => $delivery_address->address1,
'{delivery_address2}' => $delivery_address->address2,
'{delivery_city}' => $delivery_address->city,
'{delivery_postal_code}' => $delivery_address->postcode,
'{delivery_country}' => $delivery_address->country,
'{delivery_state}' => $delivery_address->id_state ? $delivery_state->name : '',
'{delivery_phone}' => ($delivery_address->phone) ? $delivery_address->phone : $delivery_address->phone_mobile,
'{delivery_other}' => $delivery_address->other,
'{invoice_company}' => $invoice_address->company,
'{invoice_vat_number}' => $invoice_address->vat_number,
'{invoice_firstname}' => $invoice_address->firstname,
'{invoice_lastname}' => $invoice_address->lastname,
'{invoice_address2}' => $invoice_address->address2,
'{invoice_address1}' => $invoice_address->address1,
'{invoice_city}' => $invoice_address->city,
'{invoice_postal_code}' => $invoice_address->postcode,
'{invoice_country}' => $invoice_address->country,
'{invoice_state}' => $invoice_address->id_state ? $invoice_state->name : '',
'{invoice_phone}' => ($invoice_address->phone) ? $invoice_address->phone : $invoice_address->phone_mobile,
'{invoice_other}' => $invoice_address->other,
'{order_name}' => $order->getUniqReference(),
'{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1),
'{carrier}' => (!isset($carrier->name)) ? Tools::displayError('No carrier') : $carrier->name,
'{payment}' => Tools::substr($order->payment, 0, 32),
'{products}' => $product_list_html,
'{products_txt}' => $product_list_txt,
'{discounts}' => $cart_rules_list_html,
'{discounts_txt}' => $cart_rules_list_txt,
'{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false),
'{total_products}' => Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $order->total_products : $order->total_products_wt, $this->context->currency, false),
'{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false),
'{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false),
'{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false),
'{total_tax_paid}' => Tools::displayPrice(($order->total_products_wt - $order->total_products) + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false)
);
/*---------------------
!-END OF INSERTED CODE-
---------------------*/
I have also added following function to current class file.
protected function getEmailTemplateContent($template_name, $mail_type, $var)
{
$email_configuration = Configuration::get('PS_MAIL_TYPE');
if ($email_configuration != $mail_type && $email_configuration != Mail::TYPE_BOTH) {
}
$theme_template_path = _PS_THEME_DIR_.'mails'.DIRECTORY_SEPARATOR.Context::getContext()->language->iso_code.DIRECTORY_SEPARATOR.$template_name;
$default_mail_template_path = _PS_MAIL_DIR_.Context::getContext()->language->iso_code.DIRECTORY_SEPARATOR.$template_name;
if (Tools::file_exists_cache($theme_template_path)) {
$default_mail_template_path = $theme_template_path;
}
if (Tools::file_exists_cache($default_mail_template_path)) {
Context::getContext()->smarty->assign('list', $var);
return Context::getContext()->smarty->fetch($default_mail_template_path);
}
return ' ';
}
Bit late in the game, but I found this thread trying to do the same thing: use the "order_conf" template in a state where order details are not available.
Based on #viral answer to his own question, I had a few problems, so here is what I did to get things working in Presta Shop V1.7.3.2
Create file [WEBROOT]/override/classes/order/OrderHistory.php
Doing this, rather than changing core code will allow you to update Presta Shop without loosing your changes.
In that file I added the following content:
<?php
/**
* Make complete Order details available to email templates
*/
use PrestaShop\PrestaShop\Core\Stock\StockManager;
use PrestaShop\PrestaShop\Adapter\StockManager as StockManagerAdapter;
class OrderHistory extends OrderHistoryCore {
public function sendEmail($order, $template_vars = false)
{
$result = Db::getInstance()->getRow('
SELECT osl.`template`, c.`lastname`, c.`firstname`, osl.`name` AS osname, c.`email`, os.`module_name`, os.`id_order_state`, os.`pdf_invoice`, os.`pdf_delivery`
FROM `'._DB_PREFIX_.'order_history` oh
LEFT JOIN `'._DB_PREFIX_.'orders` o ON oh.`id_order` = o.`id_order`
LEFT JOIN `'._DB_PREFIX_.'customer` c ON o.`id_customer` = c.`id_customer`
LEFT JOIN `'._DB_PREFIX_.'order_state` os ON oh.`id_order_state` = os.`id_order_state`
LEFT JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = o.`id_lang`)
WHERE oh.`id_order_history` = '.(int)$this->id.' AND os.`send_email` = 1');
if (isset($result['template']) && Validate::isEmail($result['email'])) {
ShopUrl::cacheMainDomainForShop($order->id_shop);
$topic = $result['osname'];
// JOHN
$this->context = Context::getContext();
/* GET THE PRODUCTS */
$order_details = $order->getProducts();
$product_var_tpl_list = array();
foreach ($order_details as $id => &$order_detail) {
$product_var_tpl = array(
'reference' => $order_detail['product_reference'],
'name' => $order_detail['product_name'].(isset($order_detail['product_attributes']) ? ' - '.$order_detail['product_attributes'] : ''),
'unit_price' => Tools::displayPrice($order_detail['unit_price_tax_incl'], $this->context->currency, false),
'price' => Tools::displayPrice($order_detail['total_price_tax_incl'], $this->context->currency, false),
'quantity' => $order_detail['product_quantity'],
'customization' => $order_detail['customizedDatas']
);
$product_var_tpl_list[] = $product_var_tpl;
} // end foreach ($order_detail)
$product_list_txt = '';
$product_list_html = '';
if (count($product_var_tpl_list) > 0) {
$product_list_txt = $this->getEmailTemplateContent('order_conf_product_list.txt', Mail::TYPE_TEXT, $product_var_tpl_list);
$product_list_html = $this->getEmailTemplateContent('order_conf_product_list.tpl', Mail::TYPE_HTML, $product_var_tpl_list);
}
/* GET THE DISCOUNTS */
$cart_rules_list = array();
$cart_rules = $order->getCartRules();
foreach ($cart_rules as $id => &$cart_rule) {
$cart_rules_list[] = array(
'voucher_name' => $cart_rule['name'],
'voucher_reduction' => ($cart_rule['value'] != 0.00 ? '-' : '').Tools::displayPrice($cart_rule['value'], $this->context->currency, false)
);
}
$cart_rules_list_txt = '';
$cart_rules_list_html = '';
if (count($cart_rules_list) > 0) {
$cart_rules_list_txt = $this->getEmailTemplateContent('order_conf_cart_rules.txt', Mail::TYPE_TEXT, $cart_rules_list);
$cart_rules_list_html = $this->getEmailTemplateContent('order_conf_cart_rules.tpl', Mail::TYPE_HTML, $cart_rules_list);
}
/* GET ORDER DETAILS, delivery, invoice, amount... etc */
$invoice_address = new Address((int)$order->id_address_invoice);
$invoiceAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_INVOICE_ADDR_RULES'), true);
$deliveryAddressPatternRules = Tools::jsonDecode(Configuration::get('PS_INVCE_DELIVERY_ADDR_RULES'), true);
$country = new Country((int)$invoice_address->id_country);
$delivery_address = null;
$formatted_delivery_address = '';
if (isset($order->id_address_delivery) && $order->id_address_delivery) {
$delivery_address = new Address((int)$order->id_address_delivery);
}
$carrier = new Carrier((int)($order->id_carrier), $order->id_lang);
$invoice = new Address((int)$order->id_address_invoice);
$delivery = new Address((int)$order->id_address_delivery);
$delivery_state = $delivery->id_state ? new State((int)$delivery->id_state) : false;
$invoice_state = $invoice->id_state ? new State((int)$invoice->id_state) : false;
/* ATTACH INFORMATION TO SMARTY VARIABLE*/
$data = array(
'{lastname}' => $result['lastname'],
'{firstname}' => $result['firstname'],
'{id_order}' => (int)$this->id_order,
'{delivery_block_txt}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, ', ', ' '),
'{invoice_block_txt}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, ', ', ' '),
'{delivery_block_html}' => AddressFormat::generateAddress($delivery_address, $deliveryAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{invoice_block_html}' => AddressFormat::generateAddress($invoice_address, $invoiceAddressPatternRules, '<br />',' ', array(
'firstname' => '<span style="font-weight:bold;">%s</span>',
'lastname' => '<span style="font-weight:bold;">%s</span>'
)),
'{delivery_company}' => $delivery_address->company,
'{delivery_firstname}' => $delivery_address->firstname,
'{delivery_lastname}' => $delivery_address->lastname,
'{delivery_address1}' => $delivery_address->address1,
'{delivery_address2}' => $delivery_address->address2,
'{delivery_city}' => $delivery_address->city,
'{delivery_postal_code}' => $delivery_address->postcode,
'{delivery_country}' => $delivery_address->country,
'{delivery_state}' => $delivery_address->id_state ? $delivery_state->name : '',
'{delivery_phone}' => ($delivery_address->phone) ? $delivery_address->phone : $delivery_address->phone_mobile,
'{delivery_other}' => $delivery_address->other,
'{invoice_company}' => $invoice_address->company,
'{invoice_vat_number}' => $invoice_address->vat_number,
'{invoice_firstname}' => $invoice_address->firstname,
'{invoice_lastname}' => $invoice_address->lastname,
'{invoice_address2}' => $invoice_address->address2,
'{invoice_address1}' => $invoice_address->address1,
'{invoice_city}' => $invoice_address->city,
'{invoice_postal_code}' => $invoice_address->postcode,
'{invoice_country}' => $invoice_address->country,
'{invoice_state}' => $invoice_address->id_state ? $invoice_state->name : '',
'{invoice_phone}' => ($invoice_address->phone) ? $invoice_address->phone : $invoice_address->phone_mobile,
'{invoice_other}' => $invoice_address->other,
'{order_name}' => $order->getUniqReference(),
'{date}' => Tools::displayDate(date('Y-m-d H:i:s'), null, 1),
'{carrier}' => (!isset($carrier->name)) ? Tools::displayError('No carrier') : $carrier->name,
'{payment}' => Tools::substr($order->payment, 0, 32),
'{products}' => $product_list_html,
'{products_txt}' => $product_list_txt,
'{discounts}' => $cart_rules_list_html,
'{discounts_txt}' => $cart_rules_list_txt,
'{total_paid}' => Tools::displayPrice($order->total_paid, $this->context->currency, false),
'{total_products}' => Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $order->total_products : $order->total_products_wt, $this->context->currency, false),
'{total_discounts}' => Tools::displayPrice($order->total_discounts, $this->context->currency, false),
'{total_shipping}' => Tools::displayPrice($order->total_shipping, $this->context->currency, false),
'{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $this->context->currency, false),
'{total_tax_paid}' => Tools::displayPrice(($order->total_products_wt - $order->total_products) + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $this->context->currency, false)
);
// END JOHN
if ($result['module_name']) {
$module = Module::getInstanceByName($result['module_name']);
if (Validate::isLoadedObject($module) && isset($module->extra_mail_vars) && is_array($module->extra_mail_vars)) {
$data = array_merge($data, $module->extra_mail_vars);
}
}
if ($template_vars) {
$data = array_merge($data, $template_vars);
}
$data['{total_paid}'] = Tools::displayPrice((float)$order->total_paid, new Currency((int)$order->id_currency), false);
if (Validate::isLoadedObject($order)) {
// Attach invoice and / or delivery-slip if they exists and status is set to attach them
if (($result['pdf_invoice'] || $result['pdf_delivery'])) {
$context = Context::getContext();
$invoice = $order->getInvoicesCollection();
$file_attachement = array();
if ($result['pdf_invoice'] && (int)Configuration::get('PS_INVOICE') && $order->invoice_number) {
Hook::exec('actionPDFInvoiceRender', array('order_invoice_list' => $invoice));
$pdf = new PDF($invoice, PDF::TEMPLATE_INVOICE, $context->smarty);
$file_attachement['invoice']['content'] = $pdf->render(false);
$file_attachement['invoice']['name'] = Configuration::get('PS_INVOICE_PREFIX', (int)$order->id_lang, null, $order->id_shop).sprintf('%06d', $order->invoice_number).'.pdf';
$file_attachement['invoice']['mime'] = 'application/pdf';
}
if ($result['pdf_delivery'] && $order->delivery_number) {
$pdf = new PDF($invoice, PDF::TEMPLATE_DELIVERY_SLIP, $context->smarty);
$file_attachement['delivery']['content'] = $pdf->render(false);
$file_attachement['delivery']['name'] = Configuration::get('PS_DELIVERY_PREFIX', Context::getContext()->language->id, null, $order->id_shop).sprintf('%06d', $order->delivery_number).'.pdf';
$file_attachement['delivery']['mime'] = 'application/pdf';
}
} else {
$file_attachement = null;
}
if (!Mail::Send(
(int)$order->id_lang,
$result['template'],
$topic,
$data,
$result['email'],
$result['firstname'].' '.$result['lastname'],
null,
null,
$file_attachement,
null,
_PS_MAIL_DIR_,
false,
(int)$order->id_shop
)) {
return false;
}
}
ShopUrl::resetMainDomainCache();
}
return true;
}
/**
* Added by John
*/
protected function getEmailTemplateContent($template_name, $mail_type, $var) {
$email_configuration = Configuration::get('PS_MAIL_TYPE');
if ($email_configuration != $mail_type && $email_configuration != Mail::TYPE_BOTH) {
return '';
}
$pathToFindEmail = array(
_PS_THEME_DIR_.'mails'.DIRECTORY_SEPARATOR.$this->context->language->iso_code.DIRECTORY_SEPARATOR.$template_name,
_PS_THEME_DIR_.'mails'.DIRECTORY_SEPARATOR.'en'.DIRECTORY_SEPARATOR.$template_name,
_PS_MAIL_DIR_.$this->context->language->iso_code.DIRECTORY_SEPARATOR.$template_name,
_PS_MAIL_DIR_.'en'.DIRECTORY_SEPARATOR.$template_name,
);
foreach ($pathToFindEmail as $path) {
if (Tools::file_exists_cache($path)) {
$this->context->smarty->assign('list', $var);
return $this->context->smarty->fetch($path);
}
}
return 'Template Not Found';
}
}
f you search for "John" in that code, you will find the modifications from the standard "sendEmail" function and the over-ridden version.
Hope it's of help to someone.
Can't seem to make it work in 1.7.5.2..
Placed in /override/classes/order .
Erase the cache after that, every time you made changes. In prod/class_index.php. I made it work under 1.7.3.3
I was able to bring the variables to the shipped.html email template. The only problem is that the variables: {products} and {discounts} are not being displayed. Do you guys have any suggestion?
I´m using warehouse as theme and prestashop version is 1.7.8.7
HTML Preview: https://ibb.co/X8x91K6
Email Result: https://ibb.co/xSx5Pwb
As you can see in email result the variables aren´t fullfilled.

Prestashop 1.7 - Overriding module class

i try to overriding a module in my custom themes, so I have copy past the original folder (from module folder in my themes > themename > modules folder)
but its not working
I have in my module folder from my theme :
ps_sharebuttons > views
and
ps_sharebuttons > ps_sharebuttons.php
which contains
<?php
if (!defined('_PS_VERSION_')) {
exit;
}
class Ps_SharebuttonsOverride extends Ps_Sharebuttons
{
public function renderWidget($hookName, array $params)
{
var_dump($params);
exit;
$key = 'ps_sharebuttons|' . $params['product']['id_product'];
if (!empty($params['product']['id_product_attribute'])) {
$key .= '|' . $params['product']['id_product_attribute'];
}
if (!$this->isCached($this->templateFile, $this->getCacheId($key))) {
$this->smarty->assign($this->getWidgetVariables($hookName, $params));
}
return $this->fetch($this->templateFile, $this->getCacheId($key));
}
public function getWidgetVariables($hookName, array $params)
{
if (!isset($this->context->controller->php_self) || $this->context->controller->php_self != 'product') {
return;
}
$product = $this->context->controller->getProduct();
if (!Validate::isLoadedObject($product)) {
return;
}
$social_share_links = [];
$sharing_url = addcslashes($this->context->link->getProductLink($product), "'");
$sharing_name = addcslashes($product->name, "'");
$image_cover_id = $product->getCover($product->id);
if (is_array($image_cover_id) && isset($image_cover_id['id_image'])) {
$image_cover_id = (int)$image_cover_id['id_image'];
} else {
$image_cover_id = 0;
}
$sharing_img = addcslashes($this->context->link->getImageLink($product->link_rewrite, $image_cover_id), "'");
if (Configuration::get('PS_SC_FACEBOOK')) {
$social_share_links['facebook'] = array(
'label' => $this->trans('Share', array(), 'Modules.Sharebuttons.Shop'),
'class' => 'facebook',
'url' => 'http://www.facebook.com/sharer.php?u='.$sharing_url,
);
}
if (Configuration::get('PS_SC_TWITTER')) {
$social_share_links['twitter'] = array(
'label' => $this->trans('Tweet', array(), 'Modules.Sharebuttons.Shop'),
'class' => 'twitter',
'url' => 'https://twitter.com/intent/tweet?text='.$sharing_name.' '.$sharing_url,
);
}
if (Configuration::get('PS_SC_GOOGLE')) {
$social_share_links['googleplus'] = array(
'label' => $this->trans('Google+', array(), 'Modules.Sharebuttons.Shop'),
'class' => 'googleplus',
'url' => 'https://plus.google.com/share?url='.$sharing_url,
);
}
if (Configuration::get('PS_SC_PINTEREST')) {
$social_share_links['pinterest'] = array(
'label' => $this->trans('Pinterest', array(), 'Modules.Sharebuttons.Shop'),
'class' => 'pinterest',
'url' => 'http://www.pinterest.com/pin/create/button/?media='.$sharing_img.'&url='.$sharing_url,
);
}
return array(
'social_share_links' => $social_share_links,
);
}
}
But prestashop still use the orignal file module because i get this error :
'Undefined index: product', '/home/xxxxxxxx/www/modules/ps_sharebuttons/ps_sharebuttons.php',
I've already clear cache
Thanks for help
Ok im stupid, the override view goes to theme > module folder but the class should be in override > module folder

Prestashop: How to filter in HelperList

Hello I try to filter a List in the Backoffice. It shows the filter, it also saves it after clicking on search, but nothing is happening. Same with pagination.
$schueler = $this->getAllSchuelerbyDiplom($id_diplom);
$diplom_name = $this->getDiplomNamebyID($id_diplom);
$fields_list = array(
'id_schueler' => array(
'title' => 'ID',
'align' => 'center',
'class' => 'fixed-width-xs',
'search' => true),
'customer_name' => array(
'title' => $this->l('ID Customer')),
'id_gruppe' => array(
'title' => $this->l('ID Gruppe')),
'name' => array(
'title' => $this->l('Name'),
'filter_key' => 'name'.$diplom_name),
'vorname' => array(
'title' => $this->l('Vorname')),
'punkte' => array(
'title' => $this->l('Punkte')),
'bestanden' => array(
'title' => $this->l('Bestanden'),
'active' => 'toggle',
'class' => 'fixed-width-xs',
'type' => 'bool'),
'date_added' => array(
'title' => $this->l('Datum'),
'class' => 'fixed-width-xs',
'type' => 'date'),
);
$helper = new HelperList();
$helper->table = 'no-idea-what-this-is-for';
$helper->title = $diplom_name;
$helper->shopLinkType = '';
$helper->actions = array('view', 'edit', 'delete');
$helper->listTotal = count($schueler);
$helper->identifier = 'id_schueler';
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) . '&configure=' . $this->name .'&diplom_name=' . $diplom_name;
return $helper->generateList($schueler, $fields_list);
What is wrong with my code? What is $helper->table for? I tried different things there, but nothing helps...
EDIT
public function getAllSchuelerbyDiplom($id_diplom) {
$query = new DbQuery();
$query->select('s.*, CONCAT(c.firstname,\' \',c.lastname) AS customer_name');
$query->from($this->table_name.'_schueler', 's');
$query->leftJoin('customer', 'c', 's.id_customer = c.id_customer');
$query->where('s.id_diplom = ' . (int)$id_diplom);
return Db::getInstance()->ExecuteS($query);
}
The problem is that HelperList object itself will only display filters being used but won't filter the actual data list for you.
In your $this->getAllSchuelerbyDiplom($id_diplom); method I assume you execute SQL query to retrieve all rows, however you need modify it to account for any filters, paginations (page number and rows per page) or ordering. You have to check GET/POST values or values set in cookie to detect them.
$helper->table sets the table name and list actions are prepended with that name so they are distinct from any other lists you might have on the page.
Edit:
Example of setting pagination and page
public function getPage()
{
// $tableName must be equal to what you set in $helper->table
// Check if page number was selected and return it
if (Tools::getIsset('submitFilter'.$tableName)) {
return (int)Tools::getValue('submitFilter'.$tableName);
}
else {
// Check if last selected page is stored in cookie and return it
if (isset($this->context->cookie->{'submitFilter'.$tableName})) {
return (int)$this->context->cookie->{'submitFilter'.$tableName};
}
else {
// Page was not set so we return 1
return 1;
}
}
}
public function getRowsPerPage()
{
// $tableName must be equal to what you set in $helper->table
// Check if number of rows was selected and return it
if (Tools::getIsset($tableName. '_pagination')) {
return (int)Tools::getValue($tableName. '_pagination');
}
else {
// Check if number of rows is stored in cookie and return it
if (isset($this->context->cookie->{$tableName. '_pagination'})) {
return (int)$this->context->cookie->{$tableName. '_pagination'};
}
else {
// Return 20 rows per page as default
return 20;
}
}
}
public function getAllSchuelerbyDiplom($id_diplom) {
$query = new DbQuery();
$query->select('s.*, CONCAT(c.firstname,\' \',c.lastname) AS customer_name');
$query->from($this->table_name.'_schueler', 's');
$query->leftJoin('customer', 'c', 's.id_customer = c.id_customer');
$query->where('s.id_diplom = ' . (int)$id_diplom);
// Limit the result based on page number and rows per page
$query->limit($this->getRowsPerPage(), ($this->getPage() - 1) * $this->getRowsPerPage());
return Db::getInstance()->ExecuteS($query);
}
You can place a p(Tools::getAllValues()); d($this->context->cookie->getAll(); after you generate a list then set a filter in your list and it will show you all the variables you need to create filters and ordering.

Yii select2 - returned data cannot be selected

I have been looking into select2 and yii and have managed to load data via json request/response.
The issue I'm faced with is when I try to select an entry of the returned data, I can not.
Where am I going wrong ? The data returnd by the action is json formatted as CustomerCode and Name
Widget code in form
$this->widget('bootstrap.widgets.TbSelect2', array(
'asDropDownList' => false,
'name' => 'CustomerCode',
'options' => array(
'placeholder' => 'Type a Customer Code',
'minimumInputLength' => '2',
'width' => '40%',
'ajax' => array(
//'url'=> 'http://api.rottentomatoes.com/api/public/v1.0/movies.json',
'url'=> Yii::app()->getBaseUrl(true).'/customer/SearchCustomer',
'dataType' => 'jsonp',
'data' => 'js: function (term,page) {
return {
term: term, // Add all the query string elements here seperated by ,
page_limit: 10,
};
}',
'results' => 'js: function (data,page) {return {results: data};}',
),
'formatResult' => 'js:function(data){
var markup = data.CustomerCode + " - ";
markup += data.Name;
return markup;
}',
'formatSelection' => 'js: function(data) {
return data.CustomerCode;
}',
)));
code snipped from controller action SearchCustomer
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
$this->renderJSON(Customer::model()->searchByCustomer($term));
renderJSON function from base controller class
protected function renderJSON($data)
{
header('Content-type: application/json');
echo $_GET['callback'] . "(";
echo CJSON::encode($data);
echo ")";
foreach (Yii::app()->log->routes as $route) {
if($route instanceof CWebLogRoute) {
$route->enabled = false; // disable any weblogroutes
}
}
Yii::app()->end();
}
Appreciate any help on this
i try.
change
'dataType' => 'jsonp' to 'dataType' => 'json'
and check json format
https://github.com/ivaynberg/select2/issues/920

Yii CForm, Nested Forms Ajax Validation

I have created the following nested forms array;
return array(
'elements' => array(
'contact' => array(
'type' => 'form',
'elements' => array(
'first_name' => array(
'type' => 'text',
),
'last_name' => array(
'type' => 'text',
)
),
),
'lead' => array(
'type' => 'form',
'elements' => array(
'primary_skills' => array(
'type' => 'textarea',
),
),
),
),
'buttons' => array(
'save-lead' => array(
'type' => 'submit',
'label' => 'Create',
'class' => 'btn'
),
)
);
i have view page like this
echo $form->renderBegin();
echo $form['lead'];
echo $form['contact'];
echo $form->buttons['save-lead'];
echo $form->renderEnd();
my actionCreate is like this
$form = new CForm('application.views.leads.register');
$form['lead']->model = new Lead;
$form['contact']->model = new Contact;
// how can i perform ajax validation only for $form['contact']
$this->performAjaxValidation($model);
//if contact form save btn is clicked
if ($form->submitted('save-lead') && $form['contact']->validate() &&
$form['lead']->validate()
) {
$contact = $form['contact']->model;
$lead = $form['lead']->model;
if ($contact->save()) {
$lead->contact_id = $contact->id;
if ($lead->save()) {
$this->redirect(array('leads/view', 'id' => $lead->id));
}
}
}
ajax validation method is
protected function performAjaxValidation($model)
{
if (isset($_POST['ajax']) && $_POST['ajax'] === 'contact') {
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
so my question is how can i perform ajax validation on $form['contact'] and $form['lead'] elements individually?
You can have several forms in a page but they should not be nested.
Nested forms are invalid.
You should make your own validation
in actionCreate and actionUpdate of your controller you must add (i have main model "Invoice" and secondary "InvoiceDetails", and there could be more than 1 form for InvoiceDetails). But of course forms cannot be nested!
public function actionCreate()
{
...
$PostVar = 'Invoices';
if (Yii::app()->request->isAjaxRequest)
{ // if ajax
$this->performAjaxValidation($model, strtolower($PostVar) . '-form');
$PostVar = ucfirst($PostVar);
if (isset($_POST[$PostVar]))
{
$model->attributes = $_POST[$PostVar];
$dynamicModel = new InvoiceDetails(); //your model
$valid = self::validate($model, $dynamicModel);
if (!isset($_POST['ajax']))
{
if (isset($_POST['InvoiceDetails']))
{
$allDetails = array();
$allDynamicModels = $_POST['InvoiceDetails'];
//your own customization
foreach ($allDynamicModels as $key => $value)
{
$InvDet = InvoiceDetails::model()->findByPk($_POST['InvoiceDetails'][$key]['id']);
if (!isset($InvDet))
{
$InvDet = new InvoiceDetails();
}
$InvDet->attributes = $_POST['InvoiceDetails'][$key];
$InvDet->save();
$allDetails[] = $InvDet;
}
}
$model->invoicedetails = $allDetails;
if ($model->save())
{
echo CJSON::encode(array('status' => 'success'));
Yii::app()->end();
}
else
{
echo CJSON::encode(array('status' => 'error saving'));
Yii::app()->end();
}
}
// Here we say if valid
if (!isset($valid))
{
echo CJSON::encode(array('status' => 'success'));
}
else
{
echo $valid;
}
Yii::app()->end();
}
else
{
$this->renderPartial('_form', ...);
}
}
else
{
// not AJAX request
$this->render('_form', ...));
}
Nested Forms are invalid. You can use scenarios to validate the form at different instances.
Example:
`if ($form->submitted('save-lead'){
$form->scenario = 'save-lead';
if($form->validate()) {
$form->save();
}
} else {
$form->scenario = 'contact';
if($form->validate()){
$form->save();
}
}
$this->render('_form', array('form'=>$form);`