Cannot add any stylesheets to module in prestashop 1.7 - php

I've encountered problem with adding any stylesheets to prestashop front office. I was reading multiple articles, tried multiple solutions and I can't get it to work. Adding styles to back office was not a problem (but that this code for adding styles to back office is workaround I think). Here is the module code. (I've added stylesheet import in multiple places to check every solution. In other modules this methods works as intended). Sorry for messy code I'm not that good in PHP.
<?php
if (!defined('_PS_VERSION_'))
exit();
class PromotionBanner extends Module
{
public function __construct()
{
$this->name = 'promotionbanner';
$this->tab = 'front_office_features';
$this->version = '1.0.0';
$this->author = 'example';
$this->author_uri = 'https://example.com';
$this->ps_versions_compliancy = array('min' => '1.7.1.0', 'max' => _PS_VERSION_);
$this->bootstrap = true;
$this->need_instance = 0;
$this->dir = '/modules/promotionbanner';
$this->css_path = Tools::getShopDomainSsl(true, true) . __PS_BASE_URI__ . 'modules/' . $this->name
. '/' . $this->_path . 'views/css/';
parent::__construct();
$this->displayName = $this->l('Promotion Banner', 'promotionbanner');
$this->description = $this->l('This module provides configurable promotion banner on your website');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall the module?', 'promotionbanner');
}
private function updateConf()
{
Configuration::updateValue('banner_text', $this->l('Wybrane produkty taƄsze o 15%! Kod rabatowy: '));
Configuration::updateValue('banner_coupon_code', $this->l('Wybierz kupon rabatowy'));
}
public function install()
{
$this->updateConf();
return parent::install() && $this -> registerHook('displayWrapperTop') && $this->registerHook('header');
}
public function uninstall()
{
if (!parent::uninstall() || !Configuration::deleteByName('promotionbanner_module') &&
!Configuration::deleteByName('banner_coupon_code'))
return false;
return true;
}
public function hookDisplayWrapperTop($params)
{
$this->context->smarty->assign(
array(
'banner_text' => Configuration::get('banner_text'),
'banner_coupon_code' => Configuration::get('banner_coupon_code')
)
);
$this->context->controller->registerStylesheet(
'modules-promotion-banner2', //This id has to be unique
'modules/'.$this->name.'/views/css/front.css',
array('media' => 'all', 'priority' => 150)
);
return $this->display(__FILE__, 'promotionbanner.tpl');
}
public function hookHeader() {
$this->context->controller->addCSS($this->_path . 'views/css/front.css', 'all');
$this->context->controller->registerStylesheet(
'modules-promotion-banner', //This id has to be unique
'modules/'.$this->name.'/views/css/front.css',
array('media' => 'all', 'priority' => 150)
);
}
public function hookActionFrontControllerSetMedia($params) {
$this->context->controller->registerStylesheet(
'module-promotionbanner-style',
'modules/'.$this->name.'/views/css/front.css',
[
'media' => 'all',
'priority' => 200,
]
);
}
public function getPromotions()
{
$cart_rule = _DB_PREFIX_ . 'cart_rule';
$request = "SELECT $cart_rule.id_cart_rule, " . _DB_PREFIX_ . "cart_rule_lang.name, $cart_rule.code " .
"FROM $cart_rule INNER JOIN " . _DB_PREFIX_ . 'cart_rule_lang ON ' . _DB_PREFIX_ . 'cart_rule.id_cart_rule='
. _DB_PREFIX_ . 'cart_rule_lang.id_cart_rule WHERE ' . _DB_PREFIX_ . 'cart_rule.code IS NOT NULL';
$db = Db::getInstance();
$cupons = $db->executeS($request);
$parsedCupons = array();
foreach ($cupons as $cupon) {
array_push($parsedCupons, array(
'code' => $cupon['code'],
'name' => $cupon['name']
));
}
return $parsedCupons;
}
public function displayForm()
{
$form = $this->renderForm();
$this->context->smarty->assign(array(
'banner_text' => Configuration::get('banner_text'),
'banner_coupon_code' => Configuration::get('banner_coupon_code'),
'form_url' => AdminController::$currentIndex . '&configure=' . $this->name . '&token=' . Tools::getAdminTokenLite('AdminModules'),
'name' => $this->name,
'form_tpl' => $form,
'coupon_codes' => $this->getPromotions()
));
$this->context->controller->addCSS(array(
$this->css_path . 'fontawesome-all.min.css',
$this->css_path . 'module.css'
));
$this->output = $this->context->smarty->fetch($this->local_path . 'views/templates/admin/menu.tpl');
return $this->output;
}
public function renderForm()
{
$helper = new HelperForm();
$helper->module = $this;
$helper->name_controller = $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex . '&configure=' . $this->name;
$helper->title = $this->displayName;
$helper->show_toolbar = false;
$helper->toolbar_scroll = false;
$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'),
)
);
$helper->fields_value = array(
'banner_text' => Configuration::get('banner_text'),
'banner_coupon_code' => Configuration::get('banner_coupon_code')
);
return $helper->generateForm(array($this->getConfigForm()));
}
public function getConfigForm()
{
$fields_form = array(
'form' => array(
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Banner text before code: '),
'name' => 'banner_text',
'lang' => false,
'required' => true,
'size' => 20
),
array(
'type' => 'select',
'label' => $this->l('Coupon code: '),
'name' => 'banner_coupon_code',
'required' => true,
'options' => array(
'query' => $this->getPromotions(),
'id' => 'code',
'name' => 'name'
)
)
),
'submit' => array(
'title' => $this->l('Save'),
'class' => 'btn btn-default pull-right'
)
)
);
return $fields_form;
}
public function getContent()
{
$output = "";
if (Tools::isSubmit('submit' . $this->name)) {
$banner_text = strval(Tools::getValue('banner_text'));
$banner_coupon_code = strval(Tools::getValue('banner_coupon_code'));
if (!isset($banner_text) || !isset($banner_coupon_code))
$output .= $this->displayError($this->l('Please insert something in this field.'));
else {
Configuration::updateValue('banner_text', $banner_text);
Configuration::updateValue('banner_coupon_code', $banner_coupon_code);
$output .= $this->displayConfirmation($this->l('Field updated successfully!'));
}
}
return $output . $this->displayForm();
}
}

Okay so I've managed to successfully register the stylesheet in the prestashop 1.7.6.1. But I think this is a good time to mention some of my mistakes and address some of the problems.
Checklist of registering a stylesheet in front office
Use correct hook for the job.
My problem has been unsolved because I've used a wrong hook.
Make sure that your __construct() registered a official hook for registering stylesheets (prestashop 1.7.x). The correct hook is: $this->registerHook('actionFrontControllerSetMedia'); you can find official docs here (If you don't have front controller in your module): https://devdocs.prestashop.com/1.7/themes/getting-started/asset-management/#without-a-front-controller-module
Make sure that you registered your hook function with $params (I don't know why but it doesn't work without a function parameter defined... This also stopped me from successfull register). The proper function should look like this:
$this->context->controller->registerStylesheet(
'stylesheet-id', //This id has to be unique
'modules/'.$this->name.'/views/css/front.css',
array('server' => 'local', 'priority' => 10)
);
}
As #bakis mentioned. After every try clear your browser cache + prestashop cache for chrome or chromium users I would suggest to disable the browser cache in inspector window completely.
I know that $this->context->controller->addCSS still exists, but this function is useful only for back office stylesheet register. Even the official docs are saying about it
Backward compatibility is kept for the addJS(), addCSS(), addJqueryUI() and addJqueryPlugin() methods.
That's pretty much everything about this question. I hope it will help someone in the future who is searching for answer.

Related

Example module how to save data in the database

I cloned a module of prestashop 1.7 and everything works perfectly without any problem. What I would like to do (please) is save the data in the prestashop database itself but I can't do it I hope I have explained myself better
code
<?php
if (!defined('_PS_VERSION_')) {
exit;
}
class Stagenti extends Module
{
protected $config_form = false;
public function __construct()
{
$this->name = 'stagenti';
$this->tab = 'administration';
$this->version = '1.0.0';
$this->author = 'Lab';
$this->need_instance = 0;
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Lab Agenti');
$this->description = $this->l('Gestionale per agenti di commercio');
$this->ps_versions_compliancy = array('min' => '1.7', 'max' => _PS_VERSION_);
}
public function install()
{
if (Shop::isFeatureActive()) Shop::setContext(Shop::CONTEXT_ALL);
$languages = Language::getLanguages(false);
foreach ($languages as $lang) {
//$values[] = Tools::getValue('SOMETEXT_TEXT_'.$lang['id_lang']);
Configuration::updateValue('STAGENTI_TEXT_' . $lang['id_lang'], '', true);
Configuration::updateValue('STAGENTI_TEXT2_' . $lang['id_lang'], '', true);
}
include(dirname(__FILE__).'/sql/install.php');
return parent::install() &&
$this->registerHook('header') &&
$this->registerHook('backOfficeHeader') &&
$this->registerHook('displayBanner');
}
public function uninstall()
{
$languages = Language::getLanguages(false);
foreach ($languages as $lang) {
//$values[] = Tools::getValue('SOMETEXT_TEXT_'.$lang['id_lang']);
Configuration::deleteByName('STAGENTI_TEXT_' . $lang['id_lang']);
Configuration::deleteByName('STAGENTI_TEXT2_' . $lang['id_lang']);
}
include(dirname(__FILE__).'/sql/uninstall.php');
return parent::uninstall();
}
public function getContent()
{
if (((bool)Tools::isSubmit('submitStagentiModule')) == true) {
$this->postProcess();
}
$this->context->smarty->assign('module_dir', $this->_path);
$output = $this->context->smarty->fetch($this->local_path . 'views/templates/admin/configure.tpl');
return $output . $this->renderForm();
}
protected function renderForm()
{
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->module = $this;
$helper->default_form_language = $this->context->language->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitStagentiModule';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
. '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFormValues(),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id,
);
return $helper->generateForm(array($this->getConfigForm()));
}
protected function getConfigForm()
{
return array(
'form' => array(
'legend' => array(
'title' => $this->l('Impostazioni'),
'icon' => 'icon-cogs',
),
'input' => array(
array(
'col' => 9,
'type' => 'text',
'desc' => $this->l('inserisci lo slogan che desideri far visualizzare'),
'name' => 'STAGENTI_TEXT2',
'label' => $this->l('Messaggio Slogan'),
'autoload_rte' => true,
'lang' => true
),
array(
'col' => 9,
'type' => 'textarea',
'desc' => $this->l('se inserisci una img le misure devono essere 1140 x 270 px'),
'name' => 'STAGENTI_TEXT',
'label' => $this->l('Messaggio riepilogo'),
'autoload_rte' => true,
'lang' => true
),
),
'submit' => array(
'title' => $this->l('Save'),
),
),
);
}
protected function getConfigFormValues()
{
$languages = Language::getLanguages(false);
$values = array();
foreach ($languages as $lang) {
$values['STAGENTI_TEXT'][$lang['id_lang']] = Configuration::get('STAGENTI_TEXT_' . $lang['id_lang']);
$values['STAGENTI_TEXT2'][$lang['id_lang']] = Configuration::get('STAGENTI_TEXT2_' . $lang['id_lang']);
}
return $values;
}
protected function postProcess()
{
$languages = Language::getLanguages(false);
foreach ($languages as $lang) {
Configuration::updateValue('STAGENTI_TEXT_' . $lang['id_lang'], Tools::getValue('STAGENTI_TEXT_' . $lang['id_lang']), true);
Configuration::updateValue('STAGENTI_TEXT2_' . $lang['id_lang'], Tools::getValue('STAGENTI_TEXT2_' . $lang['id_lang']), true);
}
}
public function hookBackOfficeHeader()
{
if (Tools::getValue('module_name') == $this->name) {
$this->context->controller->addJS($this->_path . 'views/js/back.js');
$this->context->controller->addCSS($this->_path . 'views/css/back.css');
}
}
public function hookHeader()
{
$this->context->controller->addJS($this->_path . 'views/js/front.js');
$this->context->controller->addCSS($this->_path . 'views/css/front.css');
}
public function hookDisplayBanner()
{
$some_string = Configuration::get('STAGENTI_TEXT_' . $this->context->language->id);
$this->context->smarty->assign([
'module_dir' => $this->_path,
'stagenti_message' => $some_string
]);
$some_string = Configuration::get('STAGENTI_TEXT2_' . $this->context->language->id);
$this->context->smarty->assign([
'module_dir' => $this->_path,
'stagenti_message5' => $some_string
]);
return $this->display(__FILE__, 'message.tpl');
}
}
database
<?php
$sql = array();
$sql[] = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . '` (
`id_stagenti` int(11) NOT NULL AUTO_INCREMENT,
`stagenti_text` text NOT NULL,
`stagenti_text2` text NOT NULL,
PRIMARY KEY (`id_infomess`)
) ENGINE=' . _MYSQL_ENGINE_ . ' DEFAULT CHARSET=utf8;';
foreach ($sql as $query) {
if (Db::getInstance()->execute($query) == false) {
return false;
}
}
Db::getInstance()->insert('your_table', array(
'stagenti_text' => pSQL($value1),
'stagenti_text2' => pSQL($value2),
));

Converting module Drupal7 to Drupal8

I want to convert drupal7 module to drupal8. As I know that drupal8 is object oriented but still there are some issue in my code.
I wrote the code in oop but it cannot run properly and when I run the code it shows error that function is not defined. The function of my module is to redirect folders in root directory.
A little help will be appreciated.
<?php
namespace Drupal\afridi\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Database\Database;
use Drupal\Core\Form\FormStateInterface;
use \Drupal\Core\Form\FormValidatorInterface;
use \Drupal\Core\Form\FormSubmitterInterface;
use Drupal\Core\Form\ConfigFormBase;
use Symfony\Component\HttpFoundation\Request;
/**
* Class DefaultForm.
*/
class DefaultForm extends FormBase {
// public function afridi_trigger_import_redirects($path, $path_to, $exceptions, $folder_scan = NULL);
/**
* {#inheritdoc}
*/
public function getFormId() {
return 'default_form';
}
/**
* {#inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form = array();
$form['files_autoredirect']['title'] = array(
'#markup' => t('<h2>Folder Redirect</h2><p>Before moving the media folder from old location to new location, add the folder path & destination path in order to automatically generate <b>301 redirect</b> for all the files in folder. Once the redirects are generated, move the folder from the old location to the new location & verify by visiting old url if it redirects correctly to the new file location.</p>'),
);
$form['afridi']['scan_folder'] = array(
'#type' => 'textfield',
'#title' => t('Folder to scan'),
'#default_value' => !empty(\Drupal::state()->get('afridi_scan_folder')) ? \Drupal::state()->get('afridi_scan_folder') : '',
'#size' => 60,
'#maxlength' => 128,
'#description' => t('This folder must exsist & accessible under the path so all the files inside can be scanned and a redirect rule is added for each file.<br>Example: For <b>root/content</b> folder add <b>content</b>.'),
'#required' => TRUE,
);
$form['afridi']['check'] = array(
'#title' => t("Same as folder path"),
'#type' => 'checkbox',
'#default_value' => !empty(\Drupal::state()->get('afridi_check')) ? \Drupal::state()->get('afridi_check') : '',
'#description' => t('Uncheck if the <b>redirect from</b> path is different.'),
'#ajax' => array(
'callback' => 'testprb_ajaxtest',
'wrapper' => 'testprb_replace_field_div',
),
);
$form['afridi']['path_check'] = array(
'#type' => 'container',
'#states' => array(
"visible" => array(
"input[name='check']" => array("checked" => FALSE),
),
),
);
$form['afridi']['path_check']['path_from'] = array(
'#type' => 'textfield',
'#title' => t('Redirect from path'),
'#default_value' => !empty(\Drupal::state()->get('afridi_from')) ? \Drupal::state()->get('afridi_from') : '',
'#size' => 60,
'#maxlength' => 128,
'#description' => t('Example: For <b>root/content</b> folder add <b>content</b>. If left blank scanned folder will be chosen as base path.'),
);
$form['afridi']['path_to'] = array(
'#type' => 'textfield',
'#title' => t('Redirect to path'),
'#default_value' => !empty(\Drupal::state()->get('afridi_to')) ? \Drupal::state()->get('afridi_to') : '',
'#size' => 60,
'#maxlength' => 128,
'#description' => t('Example: <b>sites/default/files/</b> for <b>root/sites/default/files</b> folder. Trailing slash must be provided.'),
'#required' => TRUE,
);
$form['afridi']['exception'] = array(
'#title' => t('Exceptions'),
'#type' => 'textarea',
'#description' => t('Exception rules, files or directories added in the list will be ignored. Add one entry per row.'),
'#default_value' => !empty(\Drupal::state()->get('afridi_exceptions')) ? implode(\Drupal::state()->get('afridi_exceptions')) : implode(PHP_EOL, array(
'. ',
'.. ',
'.DS_Store ',
)),
);
$form['submit'][] = array(
'#type' => 'submit',
'#value' => t('Generate Redirects'),
);
return $form;
}
/**
* {#inheritdoc}
*/
function submitForm(array &$form, FormStateInterface $form_state) {
if ($form_state->hasValue(array('exception'))) {
$exceptions = explode(PHP_EOL, trim($form_state->getValues('exception')));
\Drupal::state()->set('folder_redirect_exceptions', $exceptions);
}
\Drupal::state()->set('folder_redirect_check', $form_state->getValues('check'));
\Drupal::state()->set('folder_redirect_scan_folder', $form_state->getValues('scan_folder'));
\Drupal::state()->set('folder_redirect_from', $form_state->getValues('path_from'));
\Drupal::state()->set('folder_redirect_to', $form_state->getValues('path_to'));
if (!empty(\Drupal::state()->get('folder_redirect_scan_folder', '')) && !empty(\Drupal::state()->get('folder_redirect_to'))) {
if (\Drupal::state()->get('folder_redirect_check','')) {
\Drupal::state()->delete('folder_redirect_from');
if (afridi_trigger_import_redirects(\Drupal::state()->get('folder_redirect_scan_folder' , ''), \Drupal::state()->get('folder_redirect_to', ''), \Drupal::state()->get('folder_redirect_exceptions', ''))) {
drupal_set_message(t('Url redirects generated, Redirects List', array('#base-url' => url('/admin/config/search/redirect'))), 'status', TRUE);
}
else {
drupal_set_message(t('Looks like "<i> %dir </i>" doesn\'t exsist or inaccessible, please check the permission if exsists', array('%dir' => \Drupal::state()->get('folder_redirect_scan_folder') )), 'error', TRUE);
}
}
else {
if (afridi_trigger_import_redirects(\Drupal::state()->get('folder_redirect_from', ''), \Drupal::state()->get('folder_redirect_to', ''), \Drupal::state()->get('folder_redirect_exceptions', ''), \Drupal::state()->get('folder_redirect_scan_folder','')))
{
drupal_set_message(t('Url redirects generated, Redirects List', array('#base-url' => url('/admin/config/search/redirect'))), 'status', TRUE);
}
else {
drupal_set_message(t('Looks like "<i> %dir </i>" doesn\'t exsist or inaccessible, please check the permission if exsists', array('%dir' => variable_get('folder_redirect_scan_folder'))), 'error', TRUE);
}
}
}
else {
drupal_set_message(t('Invalid configurations, please try again'), 'error', TRUE);
}
}
/**
* Helper function to set important variables.
*/
function afridi_trigger_import_redirects($path, $path_to, $exceptions, $folder_scan = NULL) {
$root = DRUPAL_ROOT . "/";
$root_preg = preg_replace("/([\/]+)/", "\\/", $root);
$path_from_preg = preg_replace("/([\/]+)/", "\\/", $path);
if ($folder_scan) {
$scan_folder = $root . $folder_scan;
if (is_dir($scan_folder)) {
afridi_list_all_files($scan_folder, $path_from_preg, $path_to, $root, $root_preg, $exceptions, $path);
return TRUE;
}
else {
return FALSE;
}
}
else {
$path = $root . $path;
if (is_dir($path)) {
afridi_list_all_files($path, $path_from_preg, $path_to, $root, $root_preg, $exceptions);
return TRUE;
}
else {
return FALSE;
}
}
}
/**
* Helper function to scan the dir and its sub-dir.
*/
function afridi_list_all_files($path, $path_from_preg, $path_to, $root, $root_preg, $exceptions, $different_path_from = '') {
if (!isset($redirects)) {
$redirects = array();
}
$files = array_diff(scandir($path), array_map('trim', $exceptions));
foreach ($files as $file) {
if (is_dir($path . "/{$file}")) {
if (!empty($different_path_from)) {
afridi_list_all_files($path . "/{$file}", $path_from_preg, $path_to, $root, $root_preg, $exceptions, $different_path_from);
}
else {
afridi_list_all_files($path . "/{$file}", $path_from_preg, $path_to, $root, $root_preg, $exceptions);
}
}
else {
if (!empty($different_path_from)) {
preg_match("/" . $root_preg . "(...+)/", $path . "/{$file}", $out);
preg_match("/([a-zA-Z0-9-_]+)([\/])([.a-zA-Z0-9-_\/]+)/", $out[1], $out1);
$redirect_from = $different_path_from . '/' . $out1[3];
$redirect_to = $path_to . $out1[3];;
}
else {
preg_match("/" . $root_preg . "(...+)/", $path . "/{$file}", $out);
$redirect_from = $out[1];
preg_match("/" . $path_from_preg . "\/(...+)/", $redirect_from, $out1);
$redirect_to = $path_to . $out1[1];
}
$redirects[$redirect_from] = $redirect_to;
}
}
afridi_import_redirects($redirects);
}
/**
* Helper function to import redirects.
*/
function afridi_import_redirect($redirect_from, $redirect_to) {
$redirect = new stdClass();
module_invoke(
'redirect',
'object_prepare',
$redirect,
array(
'source' => $redirect_from,
'source_options' => array(),
'redirect' => $redirect_to,
'redirect_options' => array(),
'language' => LANGUAGE_NONE,
)
);
module_invoke('redirect', 'save', $redirect);
}
/**
* Helper function to import bulk redirects.
*/
function afridi_import_redirects($redirects) {
foreach ($redirects as $from_url => $to_url) {
if (!redirect_load_by_source($from_url)) {
$redirect = new stdClass();
redirect_object_prepare(
$redirect,
array(
'source' => $from_url,
'source_options' => array(),
'redirect' => $to_url,
'redirect_options' => array(),
'language' => LANGUAGE_NONE,
)
);
redirect_save($redirect);
}
else {
drupal_set_message(t('Redirect already exsists for path<i> "#path" </i>', array('#path' => $from_url)), 'warning', TRUE);
}
}
}
}
I want to redirect the folder path in this section but there are some issues. It show error that function is undefined.
In PHP, method calls always need to provide the object instance ($this), or the class name if it is a static method call. So for your case, you cannot directly call afridi_trigger_import_redirects, or afridi_list_all_files as they were ordinary functions.
The quick fix would be to call them with the $this instance. For example, this:
if (afridi_trigger_import_redirects(\Drupal::state()->get('folder_redirect_scan_folder' , ''), \Drupal::state()->get('folder_redirect_to', ''), \Drupal::state()->get('folder_redirect_exceptions', ''))) {
drupal_set_message(t('Url redirects generated, Redirects List', array('#base-url' => url('/admin/config/search/redirect'))), 'status', TRUE);
}
Should be rewritten into this:
if ($this->afridi_trigger_import_redirects(\Drupal::state()->get('folder_redirect_scan_folder' , ''), \Drupal::state()->get('folder_redirect_to', ''), \Drupal::state()->get('folder_redirect_exceptions', ''))) {
drupal_set_message(t('Url redirects generated, Redirects List', array('#base-url' => url('/admin/config/search/redirect'))), 'status', TRUE);
}
A more elegant way is to rewrite all methods that do not reference instance attributes as static methods. For example, this:
function ($path, $path_to, $exceptions, $folder_scan = NULL) {
should be rewritten as this:
public static function ($path, $path_to, $exceptions, $folder_scan = NULL) {
And all afridi_trigger_import_redirects calls should be rewritten in DefaultForm::afridi_trigger_import_redirects format.

How to insert an image in a template using HelperForm?

I am creating a custom module using PrestaShop 1.7 and I want to be be able to upload an image for the background. The image should be displayed if the field background_image is defined.
I am able to do it, but the image is outside of the form, as you can see in the image below.
The image should be displayed immediately above the background image field, like this (see below).
Here is my .tpl file:
{if isset($background_image)}
<div>
<div class="col-lg-3"></div>
<div>
<img src="/modules/cb_sectionaboutus/img/{$background_image}" class="img-thumbnail" width="400" />
</div>
</div>
{/if}
And here is part of the main PHP file of the module:
/**
* Load the configuration form
*/
public function getContent()
{
/**
* If values have been submitted in the form, process.
*/
if (((bool)Tools::isSubmit('submitCb_sectionaboutusModule')) == true) {
$this->postProcess();
}
$this->context->smarty->assign('module_dir', $this->_path);
/* Passes the background image to the template */
$data = $this->getDataFromDB();
$background_image = $data['background_image'];
$this->context->smarty->assign('background_image', $background_image);
// About section & Documentation
$output = $this->context->smarty->fetch($this->local_path.'views/templates/admin/configure.tpl');
return $output.$this->renderForm();
}
/**
* Create the form that will be displayed in the configuration of your module.
*/
protected function renderForm()
{
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$helper->module = $this;
$helper->default_form_language = $this->context->language->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0);
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitCb_sectionaboutusModule';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
.'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFormValues(), /* Add values for your inputs */
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id
);
return $helper->generateForm(array($this->getConfigForm()));
}
/**
* Create the structure of your form.
*/
protected function getConfigForm()
{
return array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs'
),
'input' => array(
array(
'type' => 'textarea',
'label' => $this->l('Title'),
'name' => 'title',
'desc' => $this->l('Enter the title'),
'class' => 'rte',
'autoload_rte' => true
),
array(
'type' => 'file',
'label' => $this->l('Background Image'),
'name' => 'background_image',
'desc' => $this->l('Maximum image size: ') . $this->upload_file_size_limit_in_mb . ' MB.',
'display_image' => true
)
),
'submit' => array(
'title' => $this->l('Save'),
),
),
);
}
/**
* Set values for the inputs.
*/
protected function getConfigFormValues()
{
$data = $this->getDataFromDB();
return array(
'title' => $data['title'],
'background_image' => $data['background_image']
);
}
/**
* Get the data from the database
*/
public function getDataFromDB()
{
$sql = 'SELECT * FROM ' . _DB_PREFIX_ . $this->name . ' WHERE id_' . $this->name . ' = ' . 1;
return Db::getInstance()->ExecuteS($sql)[0];
}
/**
* Save form data.
*/
protected function postProcess()
{
/* Current data */
$data_from_db = $this->getDataFromDB();
/* New data */
$form_values = $this->getConfigFormValues();
/* Sets the background image as the old value, in case there is no new upload */
$form_values['background_image'] = $data_from_db['background_image'];
/* Validates the background image file */
$file_name = $this->validateFile();
/* Checks whether the background image has been successfully uploaded */
if ($file_name) {
/* Sets the new background image */
$form_values['background_image'] = $file_name;
}
// Has rows in table --> UPDATE
if ($data_from_db) {
$sql = $sql = "UPDATE " . _DB_PREFIX_ . $this->name . " SET ";
foreach (array_keys($form_values) as $key) {
$sql .= $key . " = '" . $form_values[$key] . "', ";
}
$sql = trim($sql, " "); // first trim last space
$sql = trim($sql, ","); // then trim trailing and prefixing commas
$sql .= " WHERE id_" . $this->name . " = " . 1;
}
// No rows in table --> INSERT
else {
$columns = "id_cb_sectionaboutus, " . implode(", ", array_keys($form_values));
$values = array_map('Tools::getValue', array_keys($form_values));
$values = "1, " . "'" . implode("', '", array_values($values)) . "'";
$sql = 'INSERT INTO ' . _DB_PREFIX_ . $this->name . ' (' . $columns . ') VALUES (' . $values . ')';
}
Db::getInstance()->ExecuteS($sql);
}
How can I insert the uploaded image in the middle of the form using HelperForm?
I would prefer a solution with HelperForm, but I don't know if it works, so I will accept any answer tha gives me a good solution.
PHP file - getConfigForm function
protected function getConfigForm()
{
// ADDED THESE LINES
$image = '';
$background_image = $this->getDataFromDB()['background_image'];
if ($background_image) {
$image_url = $background_image ? '/modules/cb_sectionaboutus/img/' . $background_image : '';
$image = '<div class="col-lg-6"><img src="' . $image_url . '" class="img-thumbnail" width="400"></div>';
}
return array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs'
),
'input' => array(
array(
'type' => 'file',
'label' => $this->l('Background Image'),
'name' => 'background_image',
'desc' => $this->l('Maximum image size: ') . $this->upload_file_size_limit_in_mb . ' MB.',
'display_image' => true,
'image' => $image // ADDED THIS OPTION
),
array(
'type' => 'textarea',
'label' => $this->l('Title'),
'name' => 'title',
'desc' => $this->l('Enter the title'),
'class' => 'rte',
'autoload_rte' => true
)
),
'submit' => array(
'title' => $this->l('Save'),
),
),
);
}
and remove everything from the template.

PrestaShop, Class not found in ModuleAdminController::getController

i'm trying to develop a PrestaShop module with controllers i placed, for example in:
/modules/mymodule/controllers/admin/myControlController.php
class MyControlController extends ModuleAdminController {
public function __construct() {
$this->module = 'mymodule';
$this->bootstrap = true;
$this->context = Context::getContext();
$token = Tools::getAdminTokenLite('AdminModules');
$currentIndex='index.php?controller=AdminModules&token='.$token.'&configure=mymodule&tab_module=administration&module_name=mymodule';
Tools::redirectAdmin($currentIndex);
parent::__construct();
}
public function showForm() {
die("hello");
}}
Controller works (construct method is called) if i call it form url
http://myshop.com/adminxxx/index.php?controller=MyControl&token=9faf638aa961468c8563ffb030b3c4a8
But i can't access methods of controller from main class of module:
ModuleAdminController::getController('MyControl')->showForm();
I received "Class not found" ever
Is that the correct method to access a control from outside?
Thanks!
If you want to show anything that concern a form you should use renderForm().
Your should try parent::showForm(); or $this->showForm();.
Here is an example of controller that can work :
require_once _PS_MODULE_DIR_.'modulename/models/ModuleNameLog.php';
require_once _PS_MODULE_DIR_.'modulename/modulename.php';
class AdminModuleNameLogController extends ModuleAdminController
{
protected $_defaultOrderBy = 'id_modulenamelog';
protected $_defaultOrderWay = 'DESC';
public function __construct()
{
$this->table = 'modulenamelog';
$this->className = 'ModuleNameLog';
$this->context = Context::getContext();
$this->lang = false;
$this->bootstrap = true;
$this->actions_available = array();
$this->actions = array();
$this->show_toolbar = false;
$this->toolbar_btn['new'] = array();
$this->tabAccess['add'] = '0';
$this->allow_export = true;
$this->requiredDatabase = true;
$this->page_header_toolbar_title = $this->l('Example Module Name logs');
$this->_select = 'SUM(a.quantity) as total_quantity';
$this->_group = ' GROUP BY a.id_product, a.id_product_attribute ';
$this->fields_list = array(
'id_product' => array(
'title' => $this->l('Product'),
'align' => 'center',
'callback' => 'getProductName',
),
'id_product_attribute' => array(
'title' => $this->l('Combination'),
'align' => 'center',
'callback' => 'getAttributeName',
),
'total_quantity' => array(
'title' => $this->l('Total Quantity'),
'align' => 'center',
),
);
$this->mod = new ModuleName();
$this->mod->cleanLogs();
$this->context = Context::getContext();
parent::__construct();
}
public function getProductName($id)
{
if (!empty($id)) {
$product = new Product($id, true, $this->context->cookie->id_lang);
return $product->name;
}
}
public function getAttributeName($id)
{
if (!empty($id)) {
$combination = new Combination($id);
$names = $combination->getAttributesName($this->context->cookie->id_lang);
$str = array();
if (!empty($names)) {
foreach ($names as $value) {
$str[] = $value['name'];
}
}
return implode(' - ', $str);
} else {
return '-';
}
}
public function postProcess()
{
if (Tools::isSubmit('purge_id')) {
// Do something here
$id = (int) Tools::getValue('purge_id');
Tools::redirectAdmin(self::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModuleNameLog').'&conf=4');
}
parent::postProcess();
}
public function renderList()
{
$carts = Db::getInstance()->executeS('SELECT ct.*, cs.`firstname`, cs.`lastname` FROM '._DB_PREFIX_.'cart ct LEFT JOIN '._DB_PREFIX_.'customer cs ON ct.id_customer = cs.id_customer WHERE 1 ORDER BY id_cart DESC LIMIT 0,2000');
$tpl = $this->context->smarty->createTemplate(_PS_MODULE_DIR_.'modulename/views/templates/admin/preform.tpl');
$tpl->assign(array(
'carts' => $carts,
));
$html = $tpl->fetch();
return $html.parent::renderList();
}
public function renderForm()
{
if (!$this->loadObject(true)) {
return;
}
$obj = $this->loadObject(true);
if (isset($obj->id)) {
$this->display = 'edit';
} else {
$this->display = 'add';
}
$array_submit = array(
array(
'type' => 'select',
'label' => $this->l('Cart :'),
'name' => 'id_cart',
'options' => array(
'query' => Db::getInstance()->executeS('SELECT * FROM '._DB_PREFIX_.'cart WHERE id_cart > 0 ORDER BY id_cart DESC LIMIT 0,500'),
'id' => 'id_cart',
'name' => 'id_cart',
),
),
array(
'type' => 'text',
'label' => $this->l('Quantity translation here'),
'hint' => $this->l('Description and translation here'),
'name' => 'quantity',
),
);
$this->fields_form[0]['form'] = array(
'tinymce' => false,
'legend' => array(
'title' => $this->l('Form title'),
),
'input' => $array_submit,
'submit' => array(
'title' => $this->l('Save'),
'class' => 'btn btn-default',
),
);
$this->multiple_fieldsets = true;
return parent::renderForm();
}
}

Prestashop 1.6 - Creating video section in admin to manage and display in fornt-end

I am using prestashop version 1.6 in localhost. I need to add our own video section in admin / back office to manage and display those videos in a separate page in front end. For example, about us and term and conditions pages like that.
I have developed my own module upto configuration section of the module. Now i need to add my own form fields like title, embedcode and submit button. I dont know how to add our own form fields with "helper class" of prestashop. Also i have read the documentation but could not able to get. Can you guide me please ? Thanks in advance and sorry for my english.
Here is my code:
videomodule.php:
<?php
if (!defined('_PS_VERSION_'))
exit;
class VideoModule extends Module
{
public function __construct()
{
$this->name = 'videomodule';
$this->tab = 'video';
$this->version = 1.0;
$this->author = 'Dinesh Kumar';
$this->need_instance = 0;
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Video Module');
$this->description = $this->l('It is really an awesome experience');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall?');
Configuration::updateValue('video', serialize(array(true, true, false)));
if (!Configuration::get('videomodule'))
$this->warning = $this->l('No name provided');
// echo Configuration::get('videoid');
}
public function getContent()
{
$output = null;
if (Tools::isSubmit('submit'.$this->name))
{
$my_module_name = strval(Tools::getValue('videomodule'));
if (!$my_module_name
|| empty($my_module_name)
|| !Validate::isGenericName($my_module_name))
$output .= $this->displayError($this->l('Invalid Configuration value'));
else
{
Configuration::updateValue('videomodule', $my_module_name);
$output .= $this->displayConfirmation($this->l('Settings updated'));
}
}
return $output.$this->displayForm();
}
public function displayForm()
{
// Get default language
$default_lang = (int)Configuration::get('PS_LANG_DEFAULT');
// Init Fields form array
$fields_form[0]['form'] = array(
'legend' => array(
'title' => $this->l('Settings'),
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Configuration value'),
'name' => 'videomodule',
'size' => 20,
'required' => true
)
),
'submit' => array(
'title' => $this->l('Save'),
'class' => 'button'
)
);
$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;
// Language
$helper->default_form_language = $default_lang;
$helper->allow_employee_form_lang = $default_lang;
// 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->fields_value['videomodule'] = Configuration::get('videomodule');
return $helper->generateForm($fields_form);
}
public function install()
{
if (Shop::isFeatureActive())
Shop::setContext(Shop::CONTEXT_ALL);
if (!parent::install() ||
!$this->registerHook('leftColumn') ||
!$this->registerHook('header') ||
!Configuration::updateValue('videomodule', 'my friend')
)
return false;
return true;
}
public function uninstall()
{
if (!parent::uninstall() ||
!Configuration::deleteByName('videomodule')
)
return false;
return true;
}
public function hookLeftColumn( $params )
{
global $smarty;
return $this->display(__FILE__,'videomodule.tpl');
}
public function hookRightColumn($params)
{
return $this->hookLeftColumn($params);
}
}

Categories