how to change a bool value in prestashop 1.6 back end by icon click - prestashop

I want to change my printing status ,I am able to place the icon to change the status but the change is not occurring when I click the Print status icon shown in the image I have placed the callback as changePrintStatus
the code is reaching initProcess() when the change status icon is clicked,But after that what exactly must happen ??Or do i need to call any other function/override function ? (I want to do the same as in customers list where we change active status of customers ,similarly I want to do here for my custom module)
<?php
require_once(_PS_MODULE_DIR_.'eticketprinting/eticketprinting.php');
require_once(_PS_MODULE_DIR_.'eticketprinting/classes/Eticket.php');
class EticketController extends ModuleAdminController
{
public $module;
public $html;
public $tabName = 'renderForm';
public function __construct()
{
$this->tab = 'eticket';
$this->module = new eticketprinting();
$this->addRowAction('edit');
//$this->addRowAction('edit');
// $this->addRowAction('view'); // to display the view
//$this->addRowAction('delete');
$this->explicitSelect = false;
$this->context = Context::getContext();
$this->id_lang = $this->context->language->id;
$this->lang = false;
$this->ajax = 1;
$this->path = _MODULE_DIR_.'eticketprinting';
$this->default_form_language = $this->context->language->id;
$this->table = _DB_KITS_PREFIX_.'print_eticket';
$this->className = 'Eticket';
$this->identifier = 'id_print_eticket';
$this->allow_export = true;
$this->_select = '
id_print_eticket,
ticket_id,
ticket_no,
product_id,
print_status,
date_add,
date_upd
';
$this->name = 'EticketController';
$this->bootstrap = true;
$this->initTabModuleList();
$this->initToolbar();
$this->initPageHeaderToolbar();
// $this->initFieldList();
//$this->initContent();
parent::__construct();
$this->fields_list =
array(
'id_print_eticket' => array(
'title' => $this->l('E-Ticket Print ID'),
'width' => 25,
'type' => 'text',
),
'ticket_id' => array(
'title' => $this->l('Ticket- ID'),
'width' => 140,
'type' => 'text',
),
'ticket_no' => array(
'title' => $this->l('Ticket No'),
'width' => 140,
'type' => 'text',
),
'product_id' => array(
'title' => $this->l('Product ID'),
'width' => 100,
'type' => 'text',
),
'print_status' => array(
'title' => $this->l('Print Status'),
'align' => 'center',
'type' => 'bool',
'callback' => 'changePrintStatus',
'orderby' => false,
),
'date_add' => array(
'title' => $this->l('Date Add'),
'width' => 140,
'type' => 'text',
),
'date_upd' => array(
'title' => $this->l('Date Update'),
'width' => 140,
'type' => 'text',
),
);
}
public function changePrintStatus($value, $eticket)
{
return '<a class="list-action-enable '.($value ? 'action-enabled' : 'action-disabled').'" href="index.php?'.htmlspecialchars('tab=Eticket&id_print_eticket='
.(int)$eticket['id_print_eticket'].'&changePrintVal&token='.Tools::getAdminTokenLite('Eticket')).'">
'.($value ? '<i class="icon-check"></i>' : '<i class="icon-remove"></i>').
'</a>';
}
public function initProcess()
{
parent::initProcess();
//d($this->id_object);
if (Tools::isSubmit('changePrintVal') && $this->id_object) {
if ($this->tabAccess['edit'] === '1') {
//d("reached here");
$this->action = 'change_print_val';
} else {
$this->errors[] = Tools::displayError('You do not have permission to change this.');
}
}
}
public function postProcess()
{
//When generate pdf button is clicked
if (Tools::isSubmit('submitAddeticket')) {
if (!Validate::isDate(Tools::getValue('date_from'))) {
$this->errors[] = $this->l('Invalid "From" date');
}
if (!Validate::isDate(Tools::getValue('date_to'))) {
$this->errors[] = $this->l('Invalid "To" date');
}
if (!Validate::isInt(Tools::getValue('id_product')) || Tools::getValue('id_product')=='' ) {
$this->errors[] = $this->l('Invalid Product/select a product ');
}
if (!count($this->errors)) {
if (count(Ticket::getByProductNDateInterval(Tools::getValue('id_product'),Tools::getValue('date_from'), Tools::getValue('date_to')))) {
//d($this->context->link->getAdminLink('AdminPdf'));
Tools::redirectAdmin($this->context->link->getAdminLink('AdminPdf').'&submitAction=generateEticketPDF&id_product='.urlencode(Tools::getValue('id_product')).'&date_from='.urlencode(Tools::getValue('date_from')).'&date_to='.urlencode(Tools::getValue('date_to')));
}
$this->errors[] = $this->l('No tickets has been found or Ticket Generated Already for this period for Product ID:'.Tools::getValue('id_product').' (Change the Print Status generate the E-Ticket Again)');
}
} else {
parent::postProcess();
}
}
}

I was missing the process function :
**But note that $this->action = 'change_print_val';
and name f the process must be similar in my case processChangePrintVal
So if action is $this->action = 'change_printStatus_val'; then process name must be processChangePrintStatusVal**
I added Below function
/**
* Toggle the Eticket Print Status flag- Here the update action occurs
*/
public function processChangePrintVal()
{
$eticket = new Eticket($this->id_object);
if (!Validate::isLoadedObject($eticket)) {
$this->errors[] = Tools::displayError('An error occurred while updating Eticket Print Status information.');
}
$eticket->print_status = $eticket->print_status ? 0 : 1;
if (!$eticket->update()) {
$this->errors[] = Tools::displayError('An error occurred while Eticket Print Status customer information.');
}
Tools::redirectAdmin(self::$currentIndex.'&token='.$this->token);
}

Related

how to add an admin tab without extending a controller in prestashop?

i would like to add admin tab, i defined a controller and install the tab with this function:
public function installTab($class_name, $tabname) {
$tab = new Tab();
// Define the title of your tab that will be displayed in BO
$tab->name[$this->context->language->id] = $tabname;
// Name of your admin controller
$tab->class_name = $class_name;
// Id of the controller where the tab will be attached
// If you want to attach it to the root, it will be id 0 (I'll explain it below)
$tab->id_parent = 0;
$tab->active = 1;
// Name of your module, if you're not working in a module, just ignore it, it will be set to null in DB
$tab->module = $this->name;
// Other field like the position will be set to the last, if you want to put it to the top you'll have to modify the position fields directly in your DB
$tab->add();
return true;
}
and my controller is defined like this:
class AdminBarCodeGeneratorAdminController extends AdminController
{
/** #var Smarty */
public $smarty;
public function __construct(){
parent::__construct();
}
public function initContent()
{
parent::initContent();
$scan_form=$this->renderForm();
$this->smarty->assign('scan_form',$scan_form);
$this->setTemplate(_PS_MODULE_DIR_.'BarCodeGenerator/views/templates/admin/tabs/scan.tpl');
}
// public function display(){
// $smarty = $this->context->smarty;
// $scan_form=$this->renderForm();
// $smarty->assign('scan_form',$scan_form);
// return $this->display(__FILE__, 'views/templates/admin/tabs/scan.tpl');
// }
protected function renderForm()
{
$this->loadAsset();
$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 = $action;
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false)
.'&configure='.$this->name.'&module_name='.$this->name;
$helper->currentIndex .= '&id_BarCodeGenerator='.(int)Tools::getValue('id_BarCodeGenerator');
$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()));
}
public function getConfigFormValues(){
return array(
'prefixe2'=>Tools::getValue('prefixe2'),
'reference'=>Tools::getValue('reference'),
'key'=>Tools::getValue('key')
);
}
protected function getConfigForm(){
return array(
'form' => array(
'legend' => array(
'title' => $this->l('Scan des codes barres'),
'icon' => 'icon-qrcode',
),
'input' => array(
array(
'col' => 3,
'type' => 'text',
//'prefix' => '<i class="icon icon-envelope"></i>',
'desc' => $this->l('Entrez le prefix du code barre'),
'name' => 'prefixe2',
'label' => $this->l('Prefixe'),
'required'=>true
),
array(
'col' => 3,
'type' => 'text',
//'prefix' => '<i class="icon icon-envelope"></i>',
'desc' => $this->l('Entrez la reférence de la commande'),
'name' => 'reference',
'label' => $this->l('Reférence commande'),
'required'=>true
),
array(
'col' => 3,
'type' => 'text',
//'prefix' => '<i class="icon icon-envelope"></i>',
'desc' => $this->l('Entrez la clé du code barre'),
'name' => 'key',
'label' => $this->l('key'),
'required'=>true
),
),
'submit' => array(
'title' => $this->l('Mettre à jour le statut'),
),
),
);
}
}
but the shop i want to deploy it has the particularity the overrides are disabled, so i tried to insert the controller with two methods:
by trying to install modulesRoutes hook
public function hookModuleRoutes($params){
return [
'module-BarCodeGenerator-AdminBarCodeGeneratorAdmin'=>[
'controller'=>'AdminBarCodeGeneratorAdmin'
]
];
}
in this case, the hook did not even install successfully
-by adding manually the controller in the config/routes.yml
scanTab:
path: BarCodeGenerator/demo
methods: [GET]
defaults:
_controller: 'BarCodeGenerator/controllers/admin/AdminBarCodeGeneratorAdminController::initContent'
_legacy_controller: 'AdminBarCodeGeneratorAdminController'
_legacy_link: 'AdminBarCodeGeneratorAdminController'
but none of these methods worked

Prestashop 1.7 Module Admin action view don't work

I created an admin module to manage the data of a new table. The list is displayed in the back office. I want to create a detail view for each line, but the "view" action does not work! I have this error that appears:
ClassNotFoundException in AdminController.php line 1632: Attempted to
load class "Guides" from the global namespace. Did you forget a "use"
statement?
require_once _PS_MODULE_DIR_.'mymodguides/classes/Guides.php';
class AdminMyModGuidesController extends ModuleAdminController
{
protected $_pagination = array(20, 50, 100, 300, 1000);
protected $_default_pagination = 20;
public function __construct(){
$this->table = 'guides';
$this->identifier = 'id_guide';
$this->className = 'Guides';
$this->module = 'mymodguides';
$this->fields_list = array(
'id_guide' => array('title' => $this->l('ID'), 'align' => 'center','width' => 30),
'name' => array('title' => $this->l('Name'), 'align' => 'center','width' => 150),
'professional' => array('title' => $this->l('Prof'), 'align' => 'center','width' => 30),
'ranking' => array('title' => $this->l('Ranking'), 'align' => 'center','width' => 30),
'active' => array('title' => $this->l('Active'), 'align' => 'center','width' => 30),
'date_add' => array('title' => $this->l('Date'), 'align' => 'center','width' => 30)
);
$this->bootstrap = true;
parent::__construct();
$this->_select = "CONCAT(c.`firstname` ,' ', c.`lastname` ) as name";
$this->_join = 'LEFT JOIN `'._DB_PREFIX_.'customer` c ON (c.`id_customer` = a.`fk_id_customer`)';
// Add actions
$this->addRowAction('view');
}
public function renderView(){
$tpl = $this->context->smarty->createTemplate(_PS_MODULE_DIR_.'mymodguides/views/templates/admin/view.tpl');
return $tpl->fetch();
}
protected function l($string, $class = null, $addslashes = false, $htmlentities = true)
{
if ( _PS_VERSION_ >= '1.7') {
return Context::getContext()->getTranslator()->trans($string);
} else {
return parent::l($string, $class, $addslashes, $htmlentities);
}
}
}
Has anyone ever encountered this problem?
Thank you

Additional fields in Prestashop module - changes not displaing, parse error & class missing

I'm usually working with WP, but I need to manipulate a module blockcontactinfos on Prestashop - just simply add two more fields which will be shown on the front end, but somehow it's not working.
I have carrefully copied one of the fields, changed it everywhere but I when trying to clear the cache (in the Performance menu):
2 errors
blockcontactinfos (parse error in /modules/blockcontactinfos/blockcontactinfos.php)
blockcontactinfos (class missing in /modules/blockcontactinfos/blockcontactinfos.php)
Could anybody help me out of this? Thanks a lot in advance. Prestashop is 1.6. Fields are displayed correctly in settings, values saved, but there is the error above and I just can't force the web page to load changed template file.
blockcontactinfos.php (added the ones with _url), lines 31-141, changes marked with // KV:
<?php
if (!defined('_CAN_LOAD_FILES_'))
exit;
class Blockcontactinfos extends Module
{
protected static $contact_fields = array(
'BLOCKCONTACTINFOS_COMPANY',
'BLOCKCONTACTINFOS_ADDRESS',
'BLOCKCONTACTINFOS_ADDRESS_URL',
'BLOCKCONTACTINFOS_PHONE',
'BLOCKCONTACTINFOS_PHONE_URL',
'BLOCKCONTACTINFOS_EMAIL',
);
public function __construct()
{
$this->name = 'blockcontactinfos';
$this->author = 'PrestaShop';
$this->tab = 'front_office_features';
$this->version = '1.2.0';
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Contact information block');
$this->description = $this->l('This module will allow you to display your e-store\'s contact information in a customizable block.');
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
}
public function install()
{
Configuration::updateValue('BLOCKCONTACTINFOS_COMPANY', Configuration::get('PS_SHOP_NAME'));
Configuration::updateValue('BLOCKCONTACTINFOS_ADDRESS', trim(preg_replace('/ +/', ' ', Configuration::get('PS_SHOP_ADDR1').' '.Configuration::get('PS_SHOP_ADDR2')."\n".Configuration::get('PS_SHOP_CODE').' '.Configuration::get('PS_SHOP_CITY')."\n".Country::getNameById(Configuration::get('PS_LANG_DEFAULT'), Configuration::get('PS_SHOP_COUNTRY_ID')))));
Configuration::updateValue('BLOCKCONTACTINFOS_ADDRESS_URL', Configuration::get('PS_SHOP_ADDRESS_URL'));
Configuration::updateValue('BLOCKCONTACTINFOS_PHONE', Configuration::get('PS_SHOP_PHONE'));
Configuration::updateValue('BLOCKCONTACTINFOS_PHONE_URL', Configuration::get('PS_SHOP_PHONE_URL'));
Configuration::updateValue('BLOCKCONTACTINFOS_EMAIL', Configuration::get('PS_SHOP_EMAIL'));
$this->_clearCache('blockcontactinfos.tpl');
return (parent::install() && $this->registerHook('header') && $this->registerHook('footer'));
}
public function uninstall()
{
foreach (Blockcontactinfos::$contact_fields as $field)
Configuration::deleteByName($field);
return (parent::uninstall());
}
public function getContent()
{
$html = '';
if (Tools::isSubmit('submitModule'))
{
foreach (Blockcontactinfos::$contact_fields as $field)
Configuration::updateValue($field, Tools::getValue($field));
$this->_clearCache('blockcontactinfos.tpl');
$html = $this->displayConfirmation($this->l('Configuration updated'));
}
return $html.$this->renderForm();
}
public function hookHeader()
{
$this->context->controller->addCSS(($this->_path).'blockcontactinfos.css', 'all');
}
public function hookFooter($params)
{
if (!$this->isCached('blockcontactinfos.tpl', $this->getCacheId()))
foreach (Blockcontactinfos::$contact_fields as $field)
$this->smarty->assign(strtolower($field), Configuration::get($field));
return $this->display(__FILE__, 'blockcontactinfos.tpl', $this->getCacheId());
}
public function renderForm()
{
$fields_form = array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs'
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Company name'),
'name' => 'BLOCKCONTACTINFOS_COMPANY',
),
array(
'type' => 'textarea',
'label' => $this->l('Address'),
'name' => 'BLOCKCONTACTINFOS_ADDRESS',
),
array(
'type' => 'text',
'label' => $this->l('URL na Google mapy'),
'name' => 'BLOCKCONTACTINFOS_ADDRESS_URL',
),
array(
'type' => 'text',
'label' => $this->l('Phone number'),
'name' => 'BLOCKCONTACTINFOS_PHONE',
),
array(
'type' => 'text',
'label' => $this->l('Telefonní číslo bez mezer'),
'name' => 'BLOCKCONTACTINFOS_PHONE_URL',
),
array(
'type' => 'text',
'label' => $this->l('Email'),
'name' => 'BLOCKCONTACTINFOS_EMAIL',
),
),
'submit' => array(
'title' => $this->l('Save')
)
),
);
$helper = new HelperForm();
$helper->show_toolbar = false;
$helper->table = $this->table;
$lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
$helper->default_form_language = $lang->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$this->fields_form = array();
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitModule';
$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' => array(),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id
);
foreach (Blockcontactinfos::$contact_fields as $field)
$helper->tpl_vars['fields_value'][$field] = Tools::getValue($field, Configuration::get($field));
return $helper->generateForm(array($fields_form));
}
}
blockcontactinfos.tpl (added the ones with _url), lines 32-33:
{if $blockcontactinfos_address != ''}<li><pre> {$blockcontactinfos_address|escape:'html':'UTF-8'|nl2br}</pre></li>{/if}
{if $blockcontactinfos_phone != ''}<li>{l s='Tel' mod='blockcontactinfos'} {$blockcontactinfos_phone|escape:'html':'UTF-8'}</li>{/if}

Prestashop add another field to the the address form

I have been trying to add another two non-mandatory fields to the address pages, (user page, admin page, etc)
I created two columns in the ps_address and named address3 and address4 and changed available files in version 1.6.0.11 according to this article
I was able to add the new adreess3 and address4 fields in the country address settings. But there is no text field to add address3 and address4 in the AddressesController and the customer add addresses list.
Following is my modified AddressesController file.
<?php
/*
* 2007-2015 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license#prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* #author PrestaShop SA <contact#prestashop.com>
* #copyright 2007-2015 PrestaShop SA
* #license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class AdminAddressesControllerCore extends AdminController
{
/** #var array countries list */
protected $countries_array = array();
public function __construct()
{
$this->bootstrap = true;
$this->required_database = true;
$this->required_fields = array('company', 'address2', 'address3', 'address4', 'postcode', 'other', 'phone', 'phone_mobile', 'vat_number', 'dni');
$this->table = 'address';
$this->className = 'Address';
$this->lang = false;
$this->addressType = 'customer';
$this->explicitSelect = true;
$this->context = Context::getContext();
$this->addRowAction('edit');
$this->addRowAction('delete');
$this->bulk_actions = array(
'delete' => array(
'text' => $this->l('Delete selected'),
'confirm' => $this->l('Delete selected items?'),
'icon' => 'icon-trash'
)
);
$this->allow_export = true;
if (!Tools::getValue('realedit'))
$this->deleted = true;
$countries = Country::getCountries($this->context->language->id);
foreach ($countries as $country)
$this->countries_array[$country['id_country']] = $country['name'];
$this->fields_list = array(
'id_address' => array('title' => $this->l('ID'), 'align' => 'center', 'class' => 'fixed-width-xs'),
'firstname' => array('title' => $this->l('First Name'), 'filter_key' => 'a!firstname'),
'lastname' => array('title' => $this->l('Last Name'), 'filter_key' => 'a!lastname'),
'address1' => array('title' => $this->l('Address')),
'postcode' => array('title' => $this->l('Zip/Postal Code'), 'align' => 'right'),
'city' => array('title' => $this->l('City')),
'country' => array('title' => $this->l('Country'), 'type' => 'select', 'list' => $this->countries_array, 'filter_key' => 'cl!id_country'));
parent::__construct();
$this->_select = 'cl.`name` as country';
$this->_join = '
LEFT JOIN `'._DB_PREFIX_.'country_lang` cl ON (cl.`id_country` = a.`id_country` AND cl.`id_lang` = '.(int)$this->context->language->id.')
LEFT JOIN `'._DB_PREFIX_.'customer` c ON a.id_customer = c.id_customer
';
$this->_where = 'AND a.id_customer != 0 '.Shop::addSqlRestriction(Shop::SHARE_CUSTOMER, 'c');
}
public function initToolbar()
{
parent::initToolbar();
if (!$this->display)
$this->toolbar_btn['import'] = array(
'href' => $this->context->link->getAdminLink('AdminImport', true).'&import_type=addresses',
'desc' => $this->l('Import')
);
}
public function initPageHeaderToolbar()
{
if (empty($this->display))
$this->page_header_toolbar_btn['new_address'] = array(
'href' => self::$currentIndex.'&addaddress&token='.$this->token,
'desc' => $this->l('Add new address', null, null, false),
'icon' => 'process-icon-new'
);
parent::initPageHeaderToolbar();
}
public function renderForm()
{
$this->fields_form = array(
'legend' => array(
'title' => $this->l('Addresses'),
'icon' => 'icon-envelope-alt'
),
'input' => array(
array(
'type' => 'text_customer',
'label' => $this->l('Customer'),
'name' => 'id_customer',
'required' => false,
),
array(
'type' => 'text',
'label' => $this->l('Identification Number'),
'name' => 'dni',
'required' => false,
'col' => '4',
'hint' => $this->l('DNI / NIF / NIE')
),
array(
'type' => 'text',
'label' => $this->l('Address alias'),
'name' => 'alias',
'required' => true,
'col' => '4',
'hint' => $this->l('Invalid characters:').' <>;=#{}'
),
array(
'type' => 'textarea',
'label' => $this->l('Other'),
'name' => 'other',
'required' => false,
'cols' => 15,
'rows' => 3,
'hint' => $this->l('Forbidden characters:').' <>;=#{}'
),
),
'submit' => array(
'title' => $this->l('Save'),
)
);
$id_customer = (int)Tools::getValue('id_customer');
if (!$id_customer && Validate::isLoadedObject($this->object))
$id_customer = $this->object->id_customer;
if ($id_customer)
{
$customer = new Customer((int)$id_customer);
$token_customer = Tools::getAdminToken('AdminCustomers'.(int)(Tab::getIdFromClassName('AdminCustomers')).(int)$this->context->employee->id);
}
$this->tpl_form_vars = array(
'customer' => isset($customer) ? $customer : null,
'tokenCustomer' => isset ($token_customer) ? $token_customer : null
);
// Order address fields depending on country format
$addresses_fields = $this->processAddressFormat();
// we use delivery address
$addresses_fields = $addresses_fields['dlv_all_fields'];
// get required field
$required_fields = AddressFormat::getFieldsRequired();
// Merge with field required
$addresses_fields = array_unique(array_merge($addresses_fields, $required_fields));
$temp_fields = array();
foreach ($addresses_fields as $addr_field_item)
{
if ($addr_field_item == 'company')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Company'),
'name' => 'company',
'required' => in_array('company', $required_fields),
'col' => '4',
'hint' => $this->l('Invalid characters:').' <>;=#{}'
);
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('VAT number'),
'col' => '2',
'name' => 'vat_number',
'required' => in_array('vat_number', $required_fields)
);
}
elseif ($addr_field_item == 'lastname')
{
if (isset($customer) &&
!Tools::isSubmit('submit'.strtoupper($this->table)) &&
Validate::isLoadedObject($customer) &&
!Validate::isLoadedObject($this->object))
$default_value = $customer->lastname;
else
$default_value = '';
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Last Name'),
'name' => 'lastname',
'required' => true,
'col' => '4',
'hint' => $this->l('Invalid characters:').' 0-9!&lt;&gt;,;?=+()##"�{}_$%:',
'default_value' => $default_value,
);
}
elseif ($addr_field_item == 'firstname')
{
if (isset($customer) &&
!Tools::isSubmit('submit'.strtoupper($this->table)) &&
Validate::isLoadedObject($customer) &&
!Validate::isLoadedObject($this->object))
$default_value = $customer->firstname;
else
$default_value = '';
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('First Name'),
'name' => 'firstname',
'required' => true,
'col' => '4',
'hint' => $this->l('Invalid characters:').' 0-9!&lt;&gt;,;?=+()##"�{}_$%:',
'default_value' => $default_value,
);
}
elseif ($addr_field_item == 'address1')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Address'),
'name' => 'address1',
'col' => '6',
'required' => true,
);
}
elseif ($addr_field_item == 'address2')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Address').' (2)',
'name' => 'address2',
'col' => '6',
'required' => in_array('address2', $required_fields),
);
}
elseif ($addr_field_item == 'address3')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Address').' (3)',
'name' => 'address3',
'col' => '6',
'required' => in_array('address3', $required_fields),
);
}
elseif ($addr_field_item == 'address4')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Address').' (4)',
'name' => 'address4',
'col' => '6',
'required' => in_array('address4', $required_fields),
);
}
elseif ($addr_field_item == 'postcode')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Zip/Postal Code'),
'name' => 'postcode',
'col' => '2',
'required' => true,
);
}
elseif ($addr_field_item == 'city')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('City'),
'name' => 'city',
'col' => '4',
'required' => true,
);
}
elseif ($addr_field_item == 'country' || $addr_field_item == 'Country:name')
{
$temp_fields[] = array(
'type' => 'select',
'label' => $this->l('Country'),
'name' => 'id_country',
'required' => in_array('Country:name', $required_fields) || in_array('country', $required_fields),
'col' => '4',
'default_value' => (int)$this->context->country->id,
'options' => array(
'query' => Country::getCountries($this->context->language->id),
'id' => 'id_country',
'name' => 'name'
)
);
$temp_fields[] = array(
'type' => 'select',
'label' => $this->l('State'),
'name' => 'id_state',
'required' => false,
'col' => '4',
'options' => array(
'query' => array(),
'id' => 'id_state',
'name' => 'name'
)
);
}
elseif ($addr_field_item == 'phone')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Home phone'),
'name' => 'phone',
'required' => in_array('phone', $required_fields) || Configuration::get('PS_ONE_PHONE_AT_LEAST'),
'col' => '4',
'hint' => Configuration::get('PS_ONE_PHONE_AT_LEAST') ? sprintf($this->l('You must register at least one phone number.')) : ''
);
}
elseif ($addr_field_item == 'phone_mobile')
{
$temp_fields[] = array(
'type' => 'text',
'label' => $this->l('Mobile phone'),
'name' => 'phone_mobile',
'required' => in_array('phone_mobile', $required_fields) || Configuration::get('PS_ONE_PHONE_AT_LEAST'),
'col' => '4',
'hint' => Configuration::get('PS_ONE_PHONE_AT_LEAST') ? sprintf($this->l('You must register at least one phone number.')) : ''
);
}
}
// merge address format with the rest of the form
array_splice($this->fields_form['input'], 3, 0, $temp_fields);
return parent::renderForm();
}
public function processSave()
{
if (Tools::getValue('submitFormAjax'))
$this->redirect_after = false;
// Transform e-mail in id_customer for parent processing
if (Validate::isEmail(Tools::getValue('email')))
{
$customer = new Customer();
$customer->getByEmail(Tools::getValue('email'), null, false);
if (Validate::isLoadedObject($customer))
$_POST['id_customer'] = $customer->id;
else
$this->errors[] = Tools::displayError('This email address is not registered.');
}
elseif ($id_customer = Tools::getValue('id_customer'))
{
$customer = new Customer((int)$id_customer);
if (Validate::isLoadedObject($customer))
$_POST['id_customer'] = $customer->id;
else
$this->errors[] = Tools::displayError('This customer ID is not recognized.');
}
else
$this->errors[] = Tools::displayError('This email address is not valid. Please use an address like bob#example.com.');
if (Country::isNeedDniByCountryId(Tools::getValue('id_country')) && !Tools::getValue('dni'))
$this->errors[] = Tools::displayError('The identification number is incorrect or has already been used.');
/* If the selected country does not contain states */
$id_state = (int)Tools::getValue('id_state');
$id_country = (int)Tools::getValue('id_country');
$country = new Country((int)$id_country);
if ($country && !(int)$country->contains_states && $id_state)
$this->errors[] = Tools::displayError('You have selected a state for a country that does not contain states.');
/* If the selected country contains states, then a state have to be selected */
if ((int)$country->contains_states && !$id_state)
$this->errors[] = Tools::displayError('An address located in a country containing states must have a state selected.');
$postcode = Tools::getValue('postcode');
/* Check zip code format */
if ($country->zip_code_format && !$country->checkZipCode($postcode))
$this->errors[] = Tools::displayError('Your Zip/postal code is incorrect.').'<br />'.Tools::displayError('It must be entered as follows:').' '.str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $country->zip_code_format)));
elseif(empty($postcode) && $country->need_zip_code)
$this->errors[] = Tools::displayError('A Zip/postal code is required.');
elseif ($postcode && !Validate::isPostCode($postcode))
$this->errors[] = Tools::displayError('The Zip/postal code is invalid.');
if (Configuration::get('PS_ONE_PHONE_AT_LEAST') && !Tools::getValue('phone') && !Tools::getValue('phone_mobile'))
$this->errors[] = Tools::displayError('You must register at least one phone number.');
/* If this address come from order's edition and is the same as the other one (invoice or delivery one)
** we delete its id_address to force the creation of a new one */
if ((int)Tools::getValue('id_order'))
{
$this->_redirect = false;
if (isset($_POST['address_type']))
$_POST['id_address'] = '';
}
// Check the requires fields which are settings in the BO
$address = new Address();
$this->errors = array_merge($this->errors, $address->validateFieldsRequiredDatabase());
if (empty($this->errors))
return parent::processSave();
else
// if we have errors, we stay on the form instead of going back to the list
$this->display = 'edit';
/* Reassignation of the order's new (invoice or delivery) address */
$address_type = ((int)Tools::getValue('address_type') == 2 ? 'invoice' : ((int)Tools::getValue('address_type') == 1 ? 'delivery' : ''));
if ($this->action == 'save' && ($id_order = (int)Tools::getValue('id_order')) && !count($this->errors) && !empty($address_type))
{
if (!Db::getInstance()->execute('UPDATE '._DB_PREFIX_.'orders SET `id_address_'.$address_type.'` = '.Db::getInstance()->Insert_ID().' WHERE `id_order` = '.$id_order))
$this->errors[] = Tools::displayError('An error occurred while linking this address to its order.');
else
Tools::redirectAdmin(Tools::getValue('back').'&conf=4');
}
}
public function processAdd()
{
if (Tools::getValue('submitFormAjax'))
$this->redirect_after = false;
return parent::processAdd();
}
/**
* Get Address formats used by the country where the address id retrieved from POST/GET is.
*
* #return array address formats
*/
protected function processAddressFormat()
{
$tmp_addr = new Address((int)Tools::getValue('id_address'));
$selected_country = ($tmp_addr && $tmp_addr->id_country) ? $tmp_addr->id_country : (int)Configuration::get('PS_COUNTRY_DEFAULT');
$inv_adr_fields = AddressFormat::getOrderedAddressFields($selected_country, false, true);
$dlv_adr_fields = AddressFormat::getOrderedAddressFields($selected_country, false, true);
$inv_all_fields = array();
$dlv_all_fields = array();
$out = array();
foreach (array('inv','dlv') as $adr_type)
{
foreach (${$adr_type.'_adr_fields'} as $fields_line)
foreach (explode(' ', $fields_line) as $field_item)
${$adr_type.'_all_fields'}[] = trim($field_item);
$out[$adr_type.'_adr_fields'] = ${$adr_type.'_adr_fields'};
$out[$adr_type.'_all_fields'] = ${$adr_type.'_all_fields'};
}
return $out;
}
/**
* Method called when an ajax request is made
* #see AdminController::postProcess()
*/
public function ajaxProcess()
{
if (Tools::isSubmit('email'))
{
$email = pSQL(Tools::getValue('email'));
$customer = Customer::searchByName($email);
if (!empty($customer))
{
$customer = $customer['0'];
echo Tools::jsonEncode(array('infos' => pSQL($customer['firstname']).'_'.pSQL($customer['lastname']).'_'.pSQL($customer['company'])));
}
}
die;
}
/**
* Object Delete
*/
public function processDelete()
{
if (Validate::isLoadedObject($object = $this->loadObject()))
if (!$object->isUsed())
$this->deleted = false;
return parent::processDelete();
}
/**
* Delete multiple items
*
* #return boolean true if succcess
*/
protected function processBulkDelete()
{
if (is_array($this->boxes) && !empty($this->boxes))
{
$deleted = false;
foreach ($this->boxes as $id)
{
$to_delete = new Address((int)$id);
if ($to_delete->isUsed())
{
$deleted = true;
break;
}
}
$this->deleted = $deleted;
}
return parent::processBulkDelete();
}
}
I also tried clearing cache using the Advanced Parameters > Performance and also did a manual cache clearance as well.
What might the problem be as to not showing the new address fields in backend or the frontend?
Try also delete (no worries it will be rebuid) class_index.php file at cache folder of Your store

Prestashop - Translatable form field fails with HelperForm

I'm trying to do a Prestashop module, but when trying to set a translatable form field at the configuration form, it fails.
This is the error I get, through the JS console:
[14:33:39.915] ReferenceError: defaultLanguage is not defined # http://localhost:8888/js/admin.js:173
I think that I have well configurated the languajes in the backoffice, so I'm not sure why is this happening.
This is how I try to create the form:
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('Título de la noticia'),
'name' => 'NOTICIA_TIT',
'size' => 30,
'required' => true,
'lang' => true
),
array(
'type' => 'text',
'label' => $this->l('Imagen de la noticia'),
'name' => 'NOTICIA_IMG',
'size' => 30,
'required' => true,
'enabled' => false
),
array(
'type' => 'file',
'label' => $this->l('Subir nueva imagen'),
'name' => 'NOTICIA_IMG_FILE',
'size' => 30
),
array(
'type' => 'textarea',
'label' => $this->l('Texto de la noticia'),
'name' => 'NOTICIA_TXT',
'required' => true,
'cols' => 30,
'rows' => 4,
'lang' => 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['NOTICIA_TXT'] = Configuration::get('NOTICIA_TXT');
$helper->fields_value['NOTICIA_TIT'] = Configuration::get('NOTICIA_TIT');
$helper->fields_value['NOTICIA_IMG'] = Configuration::get('NOTICIA_IMG');
return $helper->generateForm($fields_form);
}
EDIT: I've seen this in the code.
<script type="text/javascript">
var module_dir = '/modules/';
var id_language = 1;
var languages = new Array();
var vat_number = 1;
// Multilang field setup must happen before document is ready so that calls to displayFlags() to avoid
// precedence conflicts with other document.ready() blocks
// we need allowEmployeeFormLang var in ajax request
allowEmployeeFormLang = 1;
displayFlags(languages, id_language, allowEmployeeFormLang);
$(document).ready(function() {
if ($(".datepicker").length > 0)
$(".datepicker").datepicker({
prevText: '',
nextText: '',
dateFormat: 'yy-mm-dd'
});
});
</script>
languajes variable is created as an empty array. However, this is function displayFlags:
function displayFlags(languages, defaultLanguageID, employee_cookie)
{
if ($('.translatable'))
{
$('.translatable').each(function() {
if (!$(this).find('.displayed_flag').length > 0) {
$.each(languages, function(key, language) {
if (language['id_lang'] == defaultLanguageID)
{
defaultLanguage = language;
return false;
}
});
var displayFlags = $('<div></div>')
.addClass('displayed_flag')
.append($('<img>')
.addClass('language_current')
.addClass('pointer')
.attr('src', '../img/l/' + defaultLanguage['id_lang'] + '.jpg')
.attr('alt', defaultLanguage['name'])
.click(function() {
toggleLanguageFlags(this);
})
);
var languagesFlags = $('<div></div>')
.addClass('language_flags')
.html('Choose language:<br /><br />');
$.each(languages, function(key, language) {
var img = $('<img>')
.addClass('pointer')
.css('margin', '0 2px')
.attr('src', '../img/l/' + language['id_lang'] + '.jpg')
.attr('alt', language['name'])
.click(function() {
changeFormLanguage(language['id_lang'], language['iso_code'], employee_cookie);
});
languagesFlags.append(img);
});
if ($(this).find('p:last-child').hasClass('clear'))
$(this).find('p:last-child').before(displayFlags).before(languagesFlags);
else
$(this).append(displayFlags).append(languagesFlags);
}
});
}
}
I fix the same error that you got but I get another one.
In order to define defaultLanguage, you should fill languages attribute of the helperform. You can do it this way:
$languages = Language::getLanguages(true);
$helper->languages = $languages;
I'm not sure whether you should put true or false for getLanguages... I tired both and I still get this error :
Uncaught SyntaxError: Unexpected token ILLEGAL
It happens here:
languages[0] = {
id_lang: 1,
iso_code: 'en',
name: 'English',
is_default: '<br />
So now, there probably more to do in order to have the property is_default defined... Have you find a way fix your problem?
EDIT :
By setting is_default on your own, it works. But it's ugly...
// Languages
$languages = Language::getLanguages(true);
for($i=0; $i<count($languages); $i++){
if($languages[$i]['id_lang'] == $default_lang){
$languages[$i]['is_default'] = 1;
}else{
$languages[$i]['is_default'] = 0;
}
}
$helper->languages = $languages;
Get the languages from the module controller:
$languages = $this->context->controller->getLanguages();