// Add HelperOptions to generate preferences forms

git-svn-id: http://dev.prestashop.com/svn/v1/branches/1.5.x@9369 b9a71923-0436-4b27-9f14-aed3839534dd
This commit is contained in:
tDidierjean
2011-10-14 14:30:07 +00:00
parent 5bd7821915
commit 92565efe43
11 changed files with 1120 additions and 70 deletions
+141 -2
View File
@@ -76,6 +76,8 @@ class AdminControllerCore extends Controller
protected $list_display;
protected $form_list;
protected $_listSkipDelete = array();
protected $shopLink;
@@ -160,6 +162,7 @@ class AdminControllerCore extends Controller
protected $edit;
protected $delete;
protected $duplicate;
protected $deleted;
/**
* @var bool is a list filter set
*/
@@ -943,7 +946,7 @@ class AdminControllerCore extends Controller
// Check if form template has been overriden
if (file_exists($this->context->smarty->template_dir.'/'.$this->tpl_folder.'form.tpl'))
$helper->tpl = $this->tpl_folder.'form.tpl';
HelperForm::$currentIndex = self::$currentIndex;
$helper->currentIndex = self::$currentIndex;
$helper->token = $this->token;
$helper->table = $this->table;
$helper->id = $obj->id;
@@ -993,7 +996,7 @@ class AdminControllerCore extends Controller
$helper->duplicate = $this->duplicate;*/
$helper->bulk_actions = $this->bulk_actions;
HelperList::$currentIndex = self::$currentIndex;
$helper->currentIndex = self::$currentIndex;
$helper->className = $this->className;
$helper->table = $this->table;
$helper->shopLink = $this->shopLink;
@@ -1006,6 +1009,11 @@ class AdminControllerCore extends Controller
$this->content .= $helper->generateList($this->_list, $this->fieldsDisplay);
}
else if ($this->display == 'options')
{
$helper = new HelperOptions();
$this->content .= $helper->generateOptions();
}
}
/**
@@ -1124,6 +1132,8 @@ class AdminControllerCore extends Controller
//define('_PS_BASE_URL_', Tools::getShopDomain(true));
//define('_PS_BASE_URL_SSL_', Tools::getShopDomainSsl(true));
$this->context->currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
// Change shop context ?
if (Shop::isMultiShopActivated() && Tools::getValue('setShopContext') !== false)
{
@@ -1613,6 +1623,135 @@ class AdminControllerCore extends Controller
VALUES('.(int)$asso['id_object'].', '.(int)$asso['id_'.$type].')');
}
protected function validateField($value, $field)
{
if (isset($field['validation']))
{
if ((!isset($field['empty']) || !$field['empty'] || (isset($field['empty']) && $field['empty'] && $value)) && method_exists('Validate', $field['validation']))
{
if (!Validate::$field['validation']($value))
{
$this->_errors[] = Tools::displayError($field['title'].' : Incorrect value');
return false;
}
}
}
return true;
}
/**
* Can be overriden
*/
public function beforeUpdateOptions()
{
}
/**
* Update options and preferences
*
* @param string $token
*/
protected function updateOptions($token)
{
if ($this->tabAccess['edit'] === '1')
{
$this->beforeUpdateOptions();
$languages = Language::getLanguages(false);
foreach ($this->form_list as $option_list)
{
foreach ($option_list as $category => $categoryData)
{
$fields = $categoryData['fields'];
/* Check required fields */
foreach ($fields as $field => $values)
if (isset($values['required']) && $values['required'] && !isset($_POST['configUseDefault'][$field]))
if (isset($values['type']) && $values['type'] == 'textLang')
{
foreach ($languages as $language)
if (($value = Tools::getValue($field.'_'.$language['id_lang'])) == false && (string)$value != '0')
$this->_errors[] = Tools::displayError('field').' <b>'.$values['title'].'</b> '.Tools::displayError('is required.');
}
elseif (($value = Tools::getValue($field)) == false && (string)$value != '0')
$this->_errors[] = Tools::displayError('field').' <b>'.$values['title'].'</b> '.Tools::displayError('is required.');
/* Check fields validity */
foreach ($fields as $field => $values)
if (isset($values['type']) && $values['type'] == 'textLang')
{
foreach ($languages as $language)
if (Tools::getValue($field.'_'.$language['id_lang']) && isset($values['validation']))
if (!Validate::$values['validation'](Tools::getValue($field.'_'.$language['id_lang'])))
$this->_errors[] = Tools::displayError('field').' <b>'.$values['title'].'</b> '.Tools::displayError('is invalid.');
}
elseif (Tools::getValue($field) && isset($values['validation']))
if (!Validate::$values['validation'](Tools::getValue($field)))
$this->_errors[] = Tools::displayError('field').' <b>'.$values['title'].'</b> '.Tools::displayError('is invalid.');
/* Default value if null */
foreach ($fields as $field => $values)
if (!Tools::getValue($field) && isset($values['default']))
$_POST[$field] = $values['default'];
if (1||!count($this->_errors))
{
foreach ($fields as $key => $options)
{
if (isset($options['visibility']) && $options['visibility'] > Context::getContext()->shop->getContextType())
continue;
if (Shop::isMultiShopActivated() && isset($_POST['configUseDefault'][$key]))
{
Configuration::deleteFromContext($key);
continue;
}
// check if a method updateOptionFieldName is available
$method_name = 'updateOption'.Tools::toCamelCase($key, true);
if (method_exists($this, $method_name))
$this->$method_name(Tools::getValue($key));
else if (isset($options['type']) && in_array($options['type'], array('textLang', 'textareaLang')))
{
$list = array();
foreach ($languages as $language)
{
$val = (isset($options['cast']) ? $options['cast'](Tools::getValue($key.'_'.$language['id_lang'])) : Tools::getValue($key.'_'.$language['id_lang']));
if ($this->validateField($val, $options))
{
if (Validate::isCleanHtml($val))
$list[$language['id_lang']] = $val;
else
$this->_errors[] = Tools::displayError('Can not add configuration '.$key.' for lang '.Language::getIsoById((int)$language['id_lang']));
}
}
Configuration::updateValue($key, $list);
}
else
{
$val = (isset($options['cast']) ? $options['cast'](Tools::getValue($key)) : Tools::getValue($key));
if ($this->validateField($val, $options))
{
if (Validate::isCleanHtml($val))
Configuration::updateValue($key, $val);
else
$this->_errors[] = Tools::displayError('Can not add configuration '.$key);
}
}
}
}
}
}
if (count($this->_errors) <= 0)
Tools::redirectAdmin(self::$currentIndex.'&conf=6&token='.$token);
}
else
$this->_errors[] = Tools::displayError('You do not have permission to edit here.');
}
/**
* Overload this method for custom checking
*
+33
View File
@@ -32,6 +32,10 @@
class HelperCore
{
public $currentIndex;
public $table;
public $token;
public $context;
public function __construct()
{
@@ -202,5 +206,34 @@ class HelperCore
return rtrim($html, ' ');
}
/**
* use translations files to replace english expression.
*
* @param mixed $string term or expression in english
* @param string $class
* @param boolan $addslashes if set to true, the return value will pass through addslashes(). Otherwise, stripslashes().
* @param boolean $htmlentities if set to true(default), the return value will pass through htmlentities($string, ENT_QUOTES, 'utf-8')
* @return string the translation if available, or the english default text.
*/
protected function l($string, $class = 'AdminTab', $addslashes = FALSE, $htmlentities = TRUE)
{
// if the class is extended by a module, use modules/[module_name]/xx.php lang file
$currentClass = get_class($this);
if(Module::getModuleNameFromClass($currentClass))
{
$string = str_replace('\'', '\\\'', $string);
return Module::findTranslation(Module::$classInModule[$currentClass], $string, $currentClass);
}
global $_LANGADM;
if ($class == __CLASS__)
$class = 'AdminTab';
$key = md5(str_replace('\'', '\\\'', $string));
$str = (key_exists(get_class($this).$key, $_LANGADM)) ? $_LANGADM[get_class($this).$key] : ((key_exists($class.$key, $_LANGADM)) ? $_LANGADM[$class.$key] : $string);
$str = $htmlentities ? htmlentities($str, ENT_QUOTES, 'utf-8') : $str;
return str_replace('"', '&quot;', ($addslashes ? addslashes($str) : stripslashes($str)));
}
}
+4 -7
View File
@@ -49,8 +49,6 @@ class HelperFormCore extends Helper
public $default_form_language = null;
public $allow_employee_form_lang = null;
public static $currentIndex;
public $tpl = 'form.tpl';
public function generateForm($fields_form)
@@ -64,7 +62,7 @@ class HelperFormCore extends Helper
{
$this->context->smarty->assign(array(
'firstCall' => $this->first_call,
'current' => self::$currentIndex,
'current' => $this->currentIndex,
'token' => $this->token,
'table' => $this->table,
'languages' => $this->languages,
@@ -85,10 +83,9 @@ class HelperFormCore extends Helper
public function getFieldsRequired()
{
if (isset($this->fields_form['input']))
foreach ($this->fields_form['input'] as $input)
if (array_key_exists('required', $input) && $input['required'])
return true;
foreach ($this->fields_form['input'] as $input)
if (array_key_exists('required', $input) && $input['required'])
return true;
return false;
}
+12 -49
View File
@@ -51,16 +51,10 @@ class HelperListCore extends Helper
/** @var string Order way (ASC, DESC) determined by arrows in list header */
protected $_orderWay;
protected $context;
public $identifier;
protected $deleted = 0;
public static $currentIndex;
public $token;
public static $cache_lang = array();
protected $is_cms = false;
@@ -145,7 +139,7 @@ class HelperListCore extends Helper
*/
protected function _displayEnableLink($token, $id, $value, $active, $id_category = null, $id_product = null)
{
return '<a href="'.self::$currentIndex.'&'.$this->identifier.'='.$id.'&'.$active.$this->table.
return '<a href="'.$this->currentIndex.'&'.$this->identifier.'='.$id.'&'.$active.$this->table.
((int)$id_category && (int)$id_product ? '&id_category='.$id_category : '').'&token='.($token != null ? $token : $this->token).'">
<img src="../img/admin/'.($value ? 'enabled.gif' : 'disabled.gif').'"
alt="'.($value ? $this->l('Enabled') : $this->l('Disabled')).'" title="'.($value ? $this->l('Enabled') : $this->l('Disabled')).'" /></a>';
@@ -216,10 +210,10 @@ class HelperListCore extends Helper
{
$this->_list[$index][$key] = array(
'position' => $tr[$key],
'position_url_down' => self::$currentIndex.
'position_url_down' => $this->currentIndex.
'&'.$key_to_get.'='.(int)$id_category.'&'.$this->identifiersDnd[$this->identifier].'='.$id.
'&way=1&position='.(int)($tr['position'] + 1).'&token='.$this->token,
'position_url_up' => self::$currentIndex.
'position_url_up' => $this->currentIndex.
'&'.$key_to_get.'='.(int)$id_category.'&'.$this->identifiersDnd[$this->identifier].'='.$id.
'&way=0&position='.(int)($tr['position'] - 1).'&token='.$this->token
);
@@ -289,7 +283,7 @@ class HelperListCore extends Helper
'list' => $this->_list,
'actions' => $this->actions,
'no_link' => $this->noLink,
'current_index' => self::$currentIndex,
'current_index' => $this->currentIndex,
'view' => in_array('view', $this->actions),
'edit' => in_array('edit', $this->actions),
'has_actions' => (bool)count($this->actions),
@@ -305,10 +299,10 @@ class HelperListCore extends Helper
if (!array_key_exists('Copy images too?', self::$cache_lang))
self::$cache_lang['Copy images too?'] = $this->l('Copy images too?', __CLASS__, true, false);
$duplicate = self::$currentIndex.'&'.$this->identifier.'='.$id.'&duplicate'.$this->table;
$duplicate = $this->currentIndex.'&'.$this->identifier.'='.$id.'&duplicate'.$this->table;
$this->context->smarty->assign(array(
'href' => self::$currentIndex.'&'.$this->identifier.'='.$id.'&view'.$this->table.'&token='.($token != null ? $token : $this->token),
'href' => $this->currentIndex.'&'.$this->identifier.'='.$id.'&view'.$this->table.'&token='.($token != null ? $token : $this->token),
'action' => self::$cache_lang['Duplicate'],
'confirm' => self::$cache_lang['Copy images too?'],
'location_ok' => $duplicate.'&token='.($token != null ? $token : $this->token),
@@ -325,7 +319,7 @@ class HelperListCore extends Helper
self::$cache_lang['View'] = $this->l('View');
$this->context->smarty->assign(array(
'href' => self::$currentIndex.'&'.$this->identifier.'='.$id.'&view'.$this->table.'&token='.($token != null ? $token : $this->token),
'href' => $this->currentIndex.'&'.$this->identifier.'='.$id.'&view'.$this->table.'&token='.($token != null ? $token : $this->token),
'action' => self::$cache_lang['View'],
));
@@ -339,7 +333,7 @@ class HelperListCore extends Helper
self::$cache_lang['Edit'] = $this->l('Edit');
$this->context->smarty->assign(array(
'href' => self::$currentIndex.'&'.$this->identifier.'='.$id.'&update'.$this->table.'&token='.($token != null ? $token : $this->token),
'href' => $this->currentIndex.'&'.$this->identifier.'='.$id.'&update'.$this->table.'&token='.($token != null ? $token : $this->token),
'action' => self::$cache_lang['Edit'],
));
@@ -356,7 +350,7 @@ class HelperListCore extends Helper
self::$cache_lang['DeleteItem'] = $this->l('Delete item #', __CLASS__, true, false);
$this->context->smarty->assign(array(
'href' => self::$currentIndex.'&'.$this->identifier.'='.$id.'&delete'.$this->table.'&token='.($token != null ? $token : $this->token),
'href' => $this->currentIndex.'&'.$this->identifier.'='.$id.'&delete'.$this->table.'&token='.($token != null ? $token : $this->token),
'confirm' => self::$cache_lang['DeleteItem'].$id.' ?'.(!is_null($this->specificConfirmDelete) ? '\r'.$this->specificConfirmDelete : ''),
'action' => self::$cache_lang['Delete'],
));
@@ -384,7 +378,7 @@ class HelperListCore extends Helper
if (!$total_pages) $total_pages = 1;
$action = self::$currentIndex
$action = $this->currentIndex
.(Tools::getIsset($this->identifier)
? '&'.$this->identifier.'='.(int)Tools::getValue($this->identifier)
: '')
@@ -419,7 +413,7 @@ class HelperListCore extends Helper
// Cleaning links
if (Tools::getValue($this->table.'Orderby') && Tools::getValue($this->table.'Orderway'))
self::$currentIndex = preg_replace('/&'.$this->table.'Orderby=([a-z _]*)&'.$this->table.'Orderway=([a-z]*)/i', '', self::$currentIndex);
$this->currentIndex = preg_replace('/&'.$this->table.'Orderby=([a-z _]*)&'.$this->table.'Orderway=([a-z]*)/i', '', $this->currentIndex);
if (array_key_exists($this->identifier, $this->identifiersDnd) && (int)Tools::getValue($this->identifiersDnd[$this->identifier], 1))
$table_id = substr($this->identifier, 3, strlen($this->identifier));
@@ -468,7 +462,7 @@ class HelperListCore extends Helper
$this->context->smarty->assign(array(
'table' => $this->table,
'currentIndex' => self::$currentIndex,
'currentIndex' => $this->currentIndex,
'action' => $action,
'page' => $page,
'total_pages' => $total_pages,
@@ -505,35 +499,4 @@ class HelperListCore extends Helper
));
return $this->context->smarty->fetch(_PS_ADMIN_DIR_.'/themes/template/list_footer.tpl');
}
/**
* use translations files to replace english expression.
*
* @param mixed $string term or expression in english
* @param string $class
* @param boolan $addslashes if set to true, the return value will pass through addslashes(). Otherwise, stripslashes().
* @param boolean $htmlentities if set to true(default), the return value will pass through htmlentities($string, ENT_QUOTES, 'utf-8')
* @return string the translation if available, or the english default text.
*/
protected function l($string, $class = 'AdminTab', $addslashes = false, $htmlentities = true)
{
// if the class is extended by a module, use modules/[module_name]/xx.php lang file
$current_class = get_class($this);
if (Module::getModuleNameFromClass($current_class))
{
$string = str_replace('\'', '\\\'', $string);
return Module::findTranslation(Module::$classInModule[$current_class], $string, $current_class);
}
global $_LANGADM;
if ($class == __CLASS__)
$class = 'AdminTab';
$key = md5(str_replace('\'', '\\\'', $string));
$str = key_exists(get_class($this).$key, $_LANGADM)
? $_LANGADM[get_class($this).$key]
: ((key_exists($class.$key, $_LANGADM)) ? $_LANGADM[$class.$key] : $string);
$str = $htmlentities ? htmlentities($str, ENT_QUOTES, 'utf-8') : $str;
return str_replace('"', '&quot;', ($addslashes ? addslashes($str) : stripslashes($str)));
}
}
+193
View File
@@ -0,0 +1,193 @@
<?php
/*
* 2007-2011 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-2011 PrestaShop SA
* @version Release: $Revision$
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* Use this helper to generate preferences forms, with values stored in the configuration table
*/
class HelperOptionsCore extends Helper
{
public $first_call = true;
/**
* @var array of forms fields
* Usage :
*
*/
protected $fields_form = array();
public $fields_value = array();
public $tpl = 'options.tpl';
/**
* Generate a form for options
* @param array options
* @return string html
*/
public function generateOptions($option_list)
{
$tab = Tab::getTab($this->context->language->id, $this->id);
foreach ($option_list as $category => $category_data)
{
$required = false;
foreach ($category_data['fields'] as $key => $field)
{
// Field value
$option_list[$category]['fields'][$key]['value'] = $this->getOptionValue($key, $field);
// Check if var is invisible (can't edit it in current shop context), or disable (use default value for multishop)
$isDisabled = $isInvisible = false;
if (Shop::isMultiShopActivated())
{
if (isset($field['visibility']) && $field['visibility'] > $this->context->shop->getContextType())
{
$isDisabled = true;
$isInvisible = true;
}
else if (Context::shop() != Shop::CONTEXT_ALL && !Configuration::isOverridenByCurrentContext($key))
$isDisabled = true;
}
$option_list[$category]['fields'][$key]['is_disabled'] = $isDisabled;
$option_list[$category]['fields'][$key]['is_invisible'] = $isInvisible;
// Cast options values if specified
if ($field['type'] == 'select' && isset($field['cast']))
foreach ($field['list'] as $option_key => $option)
$option_list[$category]['fields'][$key]['list'][$option_key][$field['identifier']] = $field['cast']($option[$field['identifier']]);
// Fill values for all languages for all lang fields
if (substr($field['type'], -4) == 'Lang')
{
if (!isset($languages))
$languages = Language::getLanguages(false);
foreach ($languages as $language)
{
if ($field['type'] == 'textLang')
$value = Tools::safeOutput(Tools::getValue($key.'_'.$language['id_lang'], Configuration::get($key, $language['id_lang'])));
elseif ($field['type'] == 'textareaLang')
$value = Configuration::get($key, $language['id_lang']);
$option_list[$category]['fields'][$key]['languages'][$language['id_lang']] = $value;
}
$option_list[$category]['fields'][$key]['flags'] = $this->displayFlags($languages, $this->context->language->id, $key, $key, true);
}
// Multishop default value
$option_list[$category]['fields'][$key]['multishop_default'] = (Shop::isMultiShopActivated() && Context::shop() != Shop::CONTEXT_ALL && !$isInvisible);
}
}
$this->context->smarty->assign(array(
'img_legend' => (!empty($tab['module']) && file_exists($_SERVER['DOCUMENT_ROOT']._MODULE_DIR_.$tab['module'].'/'.$tab['class_name'].'.gif') ? _MODULE_DIR_.$tab['module'].'/' : '../img/t/').$tab['class_name'].'.gif',
'current' => $this->currentIndex,
'optionsList' => $option_list,
'current_id_lang' => $this->context->language->id,
));
return $this->context->smarty->fetch(_PS_ADMIN_DIR_.'/themes/template/'.$this->tpl);
}
/**
* Type = image
* @ TODO
*/
public function displayOptionTypeImage($key, $field, $value)
{
echo '<table cellspacing="0" cellpadding="0">';
echo '<tr>';
$i = 0;
foreach ($field['list'] as $theme)
{
echo '<td class="center" style="width: 180px; padding:0px 20px 20px 0px;">';
echo '<input type="radio" name="'.$key.'" id="'.$key.'_'.$theme['name'].'_on" style="vertical-align: text-bottom;" value="'.$theme['name'].'"'.(_THEME_NAME_ == $theme['name'] ? 'checked="checked"' : '').' />';
echo '<label class="t" for="'.$key.'_'.$theme['name'].'_on"> '.Tools::strtolower($theme['name']).'</label>';
echo '<br />';
echo '<label class="t" for="'.$key.'_'.$theme['name'].'_on">';
echo '<img src="../themes/'.$theme['name'].'/preview.jpg" alt="'.Tools::strtolower($theme['name']).'">';
echo '</label>';
echo '</td>';
if (isset($field['max']) && ($i +1 ) % $field['max'] == 0)
echo '</tr><tr>';
$i++;
}
echo '</tr>';
echo '</table>';
}
/**
* Type = selectLang
* @ TODO
*/
public function displayOptionTypeSelectLang($key, $field, $value)
{
$languages = Language::getLanguages(false);
foreach ($languages as $language)
{
echo '<div id="'.$key.'_'.$language['id_lang'].'" style="margin-bottom:8px; display: '.($language['id_lang'] == $this->context->language->id ? 'block' : 'none').'; float: left; vertical-align: top;">';
echo '<select name="'.$key.'_'.strtoupper($language['iso_code']).'">';
foreach ($field['list'] as $k => $v)
echo '<option value="'.(isset($v['cast']) ? $v['cast']($v[$field['identifier']]) : $v[$field['identifier']]).'"'.((htmlentities(Tools::getValue($key.'_'.strtoupper($language['iso_code']), (Configuration::get($key.'_'.strtoupper($language['iso_code'])) ? Configuration::get($key.'_'.strtoupper($language['iso_code'])) : '')), ENT_COMPAT, 'UTF-8') == $v[$field['identifier']]) ? ' selected="selected"' : '').'>'.$v['name'].'</option>';
echo '</select>';
echo '</div>';
}
$this->displayFlags($languages, $this->context->language->id, $key, $key);
}
/**
* Type = price
* @ TODO
*/
public function displayOptionTypePrice($key, $field, $value)
{
echo $this->context->currency->getSign('left');
$this->displayOptionTypeText($key, $field, $value);
echo $this->context->currency->getSign('right').' '.$this->l('(tax excl.)');
}
/**
* Type = disabled
*
* @ TODO
*/
public function displayOptionTypeDisabled($key, $field, $value)
{
echo $field['disabled'];
}
public function getOptionValue($key, $field)
{
$value = Tools::getValue($key, Configuration::get($key));
if (!Validate::isCleanHtml($value))
$value = Configuration::get($key);
if (isset($field['defaultValue']) && !$value)
$value = $field['defaultValue'];
return $value;
}
}