Add data to file in Prestashop Feeder - php

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

Related

opencart category api return {"category":null} error

I created api to fetch category list from opencart to use for android application. There are many category list already available but when I tried to hit api getting error message "{"category":null}"
catalog->controller->api
Following are the code:
<?php
class ControllerApicategory extends Controller
{
public function index()
{
$this->load->model('catalog/category');
$this->load->model('tool/image');
$json = array();
$json['category'] = array();
$filter_data = array();
$results = $this->model_catalog_category->getCategory($filter_data);
# -- $_GET params ------------------------------
if (isset($this->request->get['id'])) {
$category_id = $this->request->get['id'];
} else {
$category_id = 0;
}
# -- End $_GET params --------------------------
$json['category'] = array(
'id' => $category['category_id'],
'name' => $category['name'],
'description' => $category['description'],
'href' => $this->url->link('product/category', 'category_id=' . $result['category_id'])
);
$json['category'] = $data['category'];
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}
Please solve this problem.
There are two Mistakes
getCategory function accept integer parameter
$json[‘category’]= $data[‘category’];
public function index()
{
$this->load->model('catalog/category');
$this->load->model('tool/image');
$json = array();
$json['category'] = array();
if (isset($this->request->get['id'])) {
$category_id = $this->request->get['id'];
} else {
$category_id = 0;
}
$category = $this->model_catalog_category->getCategory($category_id);
$json['category'] = array(
'id' => $category['category_id'],
'name' => $category['name'],
'description' => $category['description'],
'href' => $this->url->link('product/category', 'category_id=' . $category['category_id'])
);
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
}

Prestashop custom module draggable sort/order

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)

Display product price when searching

I purchased a search module that displays a popup and would like to add the price of the product I searched for in it, I found the file that I should make the changes, but what should I add to display the product price
This is the responsible function for displaying the product characteristics
protected function _prepareProducts()
{
$isEnabledImage = (bool) Mage::getStoreConfig(self::ENABLE_IMAGE_CONFIG);
$imageHeight = (int) Mage::getStoreConfig(self::IMAGE_HEIGHT_CONFIG);
$imageWidth = (int) Mage::getStoreConfig(self::IMAGE_WIDTH_CONFIG);
$isEnabledDescription = (bool) Mage::getStoreConfig(self::ENABLE_DESCRIPTION_CONFIG);
$lengthDescription = (int) Mage::getStoreConfig(self::DESCRIPTION_LENGTH_CONFIG);
$collection = $this->_getAlternativeProductCollection();
// $this->_prepareQueryPopularity($collection->getSize());
$toolbar = $this->getToolbarBlock();
$toolbar->setCollection($collection);
$size = (int) Mage::getStoreConfig(self::RESULT_SIZE_CONFIG);
$collection->setPageSize($size);
// $collection->getSelect()->limit($size);
$sortOrder = Mage::getStoreConfig(self::SORT_ORDER_PRODUCT);
if (0 < count($collection)) {
$this->_suggestions[$sortOrder][] = array('html' =>
'<p class="headercategorysearch">' . $this->__("") . '</p>'
);
}
if ($isEnabledImage) {
$helper = Mage::helper('catalog/image');
}
foreach ($collection as $_row) {
$_product = Mage::getModel('catalog/product')
->setStoreId($this->getStoreId())
->load($_row->getId());
$_image = $_srcset = $_description = '';
if ($isEnabledImage) {
$_image = (string) $helper->init($_product, 'thumbnail')->resize($imageWidth, $imageHeight);
$_srcset = (string) $helper->init($_product, 'thumbnail')->resize($imageWidth * 2, $imageHeight * 2);
$_srcset .= ' 2x';
}
if ($isEnabledDescription) {
$_description = strip_tags($this->_trim(
$_product->getShortDescription(),
$lengthDescription
));
}
// $store = Mage::app()->getStore();
// $path = Mage::getResourceModel('core/url_rewrite')
// ->getRequestPathByIdPath('product/' . $_product->getId(), $store);
// // $url = $store->getBaseUrl($store::URL_TYPE_WEB) . $path;
// $url = rtrim(Mage::getUrl($path, array('_store' => $store->getStoreId())), '/');
$url = $_product->getProductUrl();
$this->_suggestions[$sortOrder][] = array(
'name' => $_product->getName(),
'url' => $url,
'image' => $_image,
'srcset' => $_srcset,
'description' => $_description,
);
}
}
Simply add this line
'price' => $_product->getPrice() in suggestions array
$this->_suggestions[$sortOrder][] = array(
'name' => $_product->getName(),
'price' => $_product->getPrice(),
'url' => $url,
'image' => $_image,
'srcset' => $_srcset,
'description' => $_description,
);
you may use
$_product->getFinalPrice()
inside this _suggestions property, but i guess there is also a template or a bit of js responsible for output of all this.

php: additional output from foreach of array

i'm trying to refresh my memory of OO & array structure. i have,
class room{
private $people = array(
'name' => array(
'height' => null,
'age' => null
)
);
function set($list){
foreach($list as $person){
$this->people[$person['name']]['height'] = $person['height'];
$this->people[$person['name']]['age'] = $person['age'];
}
}
function print(){
foreach($this->people as $k => $v){
echo $k . "<br>";
echo $v['height'] . ":" . $v['age'] . "<br><br>";
}
}
}
$input = array( array('name' => 'John', 'height' => '6.4', 'age' => '20'),
array('name' => 'Jane', 'height' => '5.2', 'age' => '21')
);
$i = new room;
$i->set($input);
$i->print();
the output is,
name
:
John
6.4:20
Jane
5.2:21
i'm confused as why name : appears first, when the input array only contains 2 values of each person. i am unsure if i am using my arrays correctly, could someone point out my mistake?
My overall aim of this is to have correct understanding of arrays within arrays & how to best set & get the values
It's because you've initialised the $people array to contain those values
private $people = array(
'name' => array(
'height' => null,
'age' => null
)
);
Change it to:
private $people = array();
that's the good way to do it
your people class
class people {
//properties
private $name;
private $height;
private $age;
//setters
public function setName($name) {
$this->name = $name;
}
public function setHeight($height) {
$this->height = $height;
}
public function setAge($age) {
$this->age = $age;
}
//getters
public function getName() {
return $this->name;
}
public function getHeight() {
return $this->height;
}
public function getAge() {
return $this->age;
}
}
your room class
class room {
//properties
private $people = array();
//setters
public function setPeople($people) {
$this->people[] = $people;
}
//getters
public function getPeoples() {
return $this->people;
}
}
and how to control it in OOP
$people1 = new people();
$people1->setName('John');
$people1->setHeight('6.4');
$people1->setAge('20');
$people2 = new people();
$people2->setName('Jane');
$people2->setHeight('5.2');
$people2->setAge('21');
$room = new room();
$room->setPeople($people1);
$room->setPeople($people2);
// Removing people array initial data will solve the issue :)
class room{
private $people = array();
function set($list){
foreach($list as $person){
$this->people[$person['name']]['height'] = $person['height'];
$this->people[$person['name']]['age'] = $person['age'];
}
}
function print(){
foreach($this->people as $k => $v){
echo $k . "<br>";
echo $v['height'] . ":" . $v['age'] . "<br><br>";
}
}
}
$input = array( array('name' => 'John', 'height' => '6.4', 'age' => '20'),
array('name' => 'Jane', 'height' => '5.2', 'age' => '21')
);
$i = new room;
$i->set($input);
$i->print();

wordpress custom function to create table using `WP_List_Table`?

I am new to WordPress. I am trying to create a WordPress table using WP_List_Table class. I created a table but it takes a long time. So, I want to create a function that allows me to create a WordPress table, where I can pass data and column array to the function and that function will, then, create the required WordPress table. I want to create table with edit, delete and sort-able functionality.
hey try this code it dynamic function but you need to pass first argument kay and name is id.
this is my class that is dynamic create the WP_List_table.
<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Description of wplist_table
*
* #author renishkhunt
*/
if (!class_exists('WP_List_Table')) {
require_once( ABSPATH . 'wp-admin/includes/class-wp-list-table.php' );
}
class wplist_table extends WP_List_Table
{
//put your code here
var $data = array();
var $default_columns = array();
public function wplist_table($datad, $columns)
{
parent::__construct();
$this->data = $datad;
$this->default_columns = $columns;
}
function get_columns()
{
return $this->default_columns;
}
function prepare_items()
{
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
$this->_column_headers = array($columns, $hidden, $sortable);
usort($this->data, array(&$this, 'usort_recorder'));
$per_page = 10;
$current_page = $this->get_pagenum();
$total_items = count($this->data);
// only ncessary because we have sample data
$this->found_data = array_slice($this->data, (($current_page - 1) * $per_page), $per_page);
$this->set_pagination_args(array(
'total_items' => $total_items, //WE have to calculate the total number of items
'per_page' => $per_page //WE have to determine how many items to show on a page
));
$this->items = $this->found_data;
}
function column_default($item, $column_name)
{
foreach ($this->default_columns as $keys => $values) {
if ($values == $column_name) {
if(isset($item[$column_name])){
return $item[$column_name];
}
}
}
}
function get_sortable_columns()
{
$i=0;
$sortables = array();
foreach ($this->default_columns as $keys => $values) {
if($i == 0){
$i++;
//continue;
}
$sortables[$keys] = array($values,false);
}
return $sortables;
}
function usort_recorder($a, $b)
{
$orderby = (!empty($_GET['orderby'])) ? $_GET['orderby'] : 'id';
$order = (!empty($_GET['order'])) ? $_GET['order'] : 'asc';
$resutl = strcmp($a[$orderby], $b[$orderby]);
return ( $order === 'asc') ? $resutl : -$resutl;
}
function column_Name($item)
{
$action = array(
'edit' => sprintf('Edit', $_REQUEST['page'], 'edit', $item['id']),
'delete' => sprintf('Delete', $_REQUEST['page'], 'delete', $item['id'])
);
return sprintf('%1$s %2$s', $item['name'], $this->row_actions($action));
}
function get_bulk_action()
{
$actions = array(
'delete' => 'Delete '
);
return $actions;
}
function column_db($item)
{
return sprintf("<input type='checkbox' name='id[]' value='%s'", $item['id']);
}
}
?>
just you copy that code in file and pass arguments like column name and data like this.
$data = array(
array("id" => 1, "name" => "Renish Khunt", "add" => "asd"),
array("id" => 2, "name" => "Renish Khunt", "add" => "asd"),
array("id" => 3, "name" => "Renish Khunt", "add" => "asd")
);
$columns = array(
"name" => "name",
"add" => "add"
);
then after create the class object and pass the two arguments the data and column name like this.
$mylist_table = new wplist_table($data, $columns);
echo '<div class="wrap"><h2>Custome Fields<a class="add-new-h2" href="?page=' . $_REQUEST['page'] . '&action=add">Add New</a></h2>';
$mylist_table->prepare_items();
$mylist_table->display();
echo "</div>";
i hope this is used full for you that is the dynamic class you need to display more column in $column array add column name and $data array add that name of column as key or value like this.
$data = array(
array("id" => 1, "name" => "Renish Khunt", "add" => "asd","newcolumn"=>"value"),
array("id" => 2, "name" => "Renish Khunt", "add" => "asd","newcolumn"=>"value"),
array("id" => 3, "name" => "Renish Khunt", "add" => "asd","newcolumn"=>"value")
);
$columns = array(
"name" => "name",
"add" => "add",
"newcolumn"=>"New Column"
);
like this i hope this code is used full for you.
thank you.

Categories