NEW : Update variants to standard card and list

This commit is contained in:
kamel 2022-03-18 15:38:44 +01:00
parent 43e7547611
commit 1418fd7054
23 changed files with 3043 additions and 968 deletions

View File

@ -255,6 +255,12 @@ if ($action == 'update' && !empty($permissiontoadd)) {
$result = $object->update($user);
if ($result > 0) {
$action = 'view';
$urltogo = $backtopage ? str_replace('__ID__', $result, $backtopage) : $backurlforlist;
$urltogo = preg_replace('/--IDFORBACKTOPAGE--/', $object->id, $urltogo); // New method to autoselect project after a New on another form object creation
if ($urltogo) {
header("Location: " . $urltogo);
exit;
}
} else {
$error++;
// Creation KO

View File

@ -95,6 +95,8 @@ if (GETPOST('roworder', 'alpha', 3) && GETPOST('table_element_line', 'aZ09', 3)
$perm = 1;
} elseif ($table_element_line == 'facture_fourn_det_rec' && $user->rights->fournisseur->facture->creer) {
$perm = 1;
} elseif ($table_element_line == 'product_attribute_value' && $fk_element == 'fk_product_attribute' && ($user->rights->produit->lire || $user->rights->service->lire)) {
$perm = 1;
} elseif ($table_element_line == 'ecm_files') { // Used when of page "documents.php"
if (!empty($user->rights->ecm->creer)) {
$perm = 1;

View File

@ -2931,15 +2931,20 @@ abstract class CommonObject
return -1;
}
$fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
$fieldposition = 'position';
}
// Count number of lines to reorder (according to choice $renum)
$nl = 0;
$sql = "SELECT count(rowid) FROM ".$this->db->prefix().$this->table_element_line;
$sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
if (!$renum) {
$sql .= ' AND rang = 0';
$sql .= " AND " . $fieldposition . " = 0";
}
if ($renum) {
$sql .= ' AND rang <> 0';
$sql .= " AND " . $fieldposition . " <> 0";
}
dol_syslog(get_class($this)."::line_order", LOG_DEBUG);
@ -2960,7 +2965,7 @@ abstract class CommonObject
if ($fk_parent_line) {
$sql .= ' AND fk_parent_line IS NULL';
}
$sql .= " ORDER BY rang ASC, rowid ".$rowidorder;
$sql .= " ORDER BY " . $fieldposition . " ASC, rowid " . $rowidorder;
dol_syslog(get_class($this)."::line_order search all parent lines", LOG_DEBUG);
$resql = $this->db->query($sql);
@ -3001,12 +3006,17 @@ abstract class CommonObject
*/
public function getChildrenOfLine($id, $includealltree = 0)
{
$fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
$fieldposition = 'position';
}
$rows = array();
$sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
$sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
$sql .= ' AND fk_parent_line = '.((int) $id);
$sql .= ' ORDER BY rang ASC';
$sql .= " ORDER BY " . $fieldposition . " ASC";
dol_syslog(get_class($this)."::getChildrenOfLine search children lines for line ".$id, LOG_DEBUG);
$resql = $this->db->query($sql);
@ -3077,7 +3087,7 @@ abstract class CommonObject
{
global $hookmanager;
$fieldposition = 'rang'; // @todo Rename 'rang' into 'position'
if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction'))) {
if (in_array($this->table_element_line, array('bom_bomline', 'ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
$fieldposition = 'position';
}
@ -3123,13 +3133,13 @@ abstract class CommonObject
{
if ($rang > 1) {
$fieldposition = 'rang';
if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
$fieldposition = 'position';
}
$sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
$sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
$sql .= ' AND rang = '.((int) ($rang - 1));
$sql .= " AND " . $fieldposition . " = " . ((int) ($rang - 1));
if ($this->db->query($sql)) {
$sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang - 1));
$sql .= ' WHERE rowid = '.((int) $rowid);
@ -3154,13 +3164,13 @@ abstract class CommonObject
{
if ($rang < $max) {
$fieldposition = 'rang';
if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction'))) {
if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
$fieldposition = 'position';
}
$sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) $rang);
$sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
$sql .= ' AND rang = '.((int) ($rang + 1));
$sql .= " AND " . $fieldposition . " = " . ((int) ($rang + 1));
if ($this->db->query($sql)) {
$sql = "UPDATE ".$this->db->prefix().$this->table_element_line." SET ".$fieldposition." = ".((int) ($rang + 1));
$sql .= ' WHERE rowid = '.((int) $rowid);
@ -3181,7 +3191,12 @@ abstract class CommonObject
*/
public function getRangOfLine($rowid)
{
$sql = "SELECT rang FROM ".$this->db->prefix().$this->table_element_line;
$fieldposition = 'rang';
if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
$fieldposition = 'position';
}
$sql = "SELECT " . $fieldposition . " FROM ".$this->db->prefix().$this->table_element_line;
$sql .= " WHERE rowid = ".((int) $rowid);
dol_syslog(get_class($this)."::getRangOfLine", LOG_DEBUG);
@ -3200,9 +3215,14 @@ abstract class CommonObject
*/
public function getIdOfLine($rang)
{
$fieldposition = 'rang';
if (in_array($this->table_element_line, array('ecm_files', 'emailcollector_emailcollectoraction', 'product_attribute_value'))) {
$fieldposition = 'position';
}
$sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
$sql .= " WHERE ".$this->fk_element." = ".((int) $this->id);
$sql .= " AND rang = ".((int) $rang);
$sql .= " AND " . $fieldposition . " = ".((int) $rang);
$resql = $this->db->query($sql);
if ($resql) {
$row = $this->db->fetch_row($resql);
@ -3221,7 +3241,7 @@ abstract class CommonObject
{
// phpcs:enable
$positionfield = 'rang';
if ($this->table_element == 'bom_bom') {
if (in_array($this->table_element, array('bom_bom', 'product_attribute'))) {
$positionfield = 'position';
}

View File

@ -73,10 +73,10 @@ class modVariants extends DolibarrModules
$this->module_parts = array();
// Data directories to create when module is enabled.
// Example: this->dirs = array("/mymodule/temp");
// Example: this->dirs = array("/variants/temp");
$this->dirs = array();
// Config pages. Put here list of php page, stored into mymodule/admin directory, to use to setup module.
// Config pages. Put here list of php page, stored into variants/admin directory, to use to setup module.
$this->config_page_url = array('admin.php@variants');
// Dependencies
@ -97,9 +97,9 @@ class modVariants extends DolibarrModules
);
// Dictionaries
if (!isset($conf->mymodule->enabled)) {
$conf->mymodule = new stdClass();
$conf->mymodule->enabled = 0;
if (!isset($conf->variants->enabled)) {
$conf->variants = new stdClass();
$conf->variants->enabled = 0;
}
$this->dictionaries = array();

View File

@ -279,6 +279,8 @@ ErrorExecIdFailed=Can't execute command "id"
ErrorBadCharIntoLoginName=Unauthorized character in the login name
ErrorRequestTooLarge=Error, request too large
ErrorNotApproverForHoliday=You are not the approver for leave %s
ErrorAttributeIsUsedIntoProduct=This attribute is used in one or more product variants
ErrorAttributeValueIsUsedIntoProduct=This attribute value is used in one or more product variants
# Warnings
WarningParamUploadMaxFileSizeHigherThanPostMaxSize=Your PHP parameter upload_max_filesize (%s) is higher than PHP parameter post_max_size (%s). This is not a consistent setup.

View File

@ -1,6 +1,7 @@
<?php
/* Copyright (C) 2016 Marcos García <marcosgdf@gmail.com>
* Copyright (C) 2022 Open-Dsi <support@open-dsi.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -36,8 +37,6 @@ require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
$permissiontoread = $user->rights->produit->lire || $user->rights->service->lire;
// Security check
if (empty($conf->variants->enabled)) {
accessforbidden('Module not enabled');
@ -45,8 +44,7 @@ if (empty($conf->variants->enabled)) {
if ($user->socid > 0) { // Protection if external user
accessforbidden();
}
//$result = restrictedArea($user, 'variant');
if (!$permissiontoread) accessforbidden();
$result = restrictedArea($user, 'variants');
/*

View File

@ -1,5 +1,6 @@
<?php
/* Copyright (C) 2016 Marcos García <marcosgdf@gmail.com>
* Copyright (C) 2022 Open-Dsi <support@open-dsi.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -36,8 +37,6 @@ require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php';
require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttributeValue.class.php';
$permissiontoread = $user->rights->produit->lire || $user->rights->service->lire;
// Security check
if (empty($conf->variants->enabled)) {
accessforbidden('Module not enabled');
@ -45,8 +44,7 @@ if (empty($conf->variants->enabled)) {
if ($user->socid > 0) { // Protection if external user
accessforbidden();
}
//$result = restrictedArea($user, 'variant');
if (!$permissiontoread) accessforbidden();
$result = restrictedArea($user, 'variants');
/*

View File

@ -1,6 +1,7 @@
<?php
/* Copyright (C) 2016 Marcos García <marcosgdf@gmail.com>
* Copyright (C) 2022 Open-Dsi <support@open-dsi.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -36,8 +37,7 @@ if (!defined('NOREQUIRETRAN')) {
}
require '../../main.inc.php';
$permissiontoread = $user->rights->produit->lire || $user->rights->service->lire;
require DOL_DOCUMENT_ROOT . '/variants/class/ProductAttribute.class.php';
// Security check
if (empty($conf->variants->enabled)) {
@ -46,8 +46,7 @@ if (empty($conf->variants->enabled)) {
if ($user->socid > 0) { // Protection if external user
accessforbidden();
}
//$result = restrictedArea($user, 'variant');
if (!$permissiontoread) accessforbidden();
$result = restrictedArea($user, 'variants');
/*
@ -56,14 +55,15 @@ if (!$permissiontoread) accessforbidden();
top_httphead();
// Registering the location of boxes
if (GETPOSTISSET('roworder')) {
$roworder = GETPOST('roworder', 'intcomma', 2);
print '<!-- Ajax page called with url '.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.dol_escape_htmltag($_SERVER["QUERY_STRING"]).' -->'."\n";
dol_syslog("AjaxOrderAttribute roworder=".$roworder, LOG_DEBUG);
// Registering the location of boxes
if (GETPOST('roworder', 'alpha', 3)) {
$roworder = GETPOST('roworder', 'alpha', 3);
dol_syslog("AjaxOrderAttribute roworder=" . $roworder, LOG_DEBUG);
$rowordertab = explode(',', $roworder);
$newrowordertab = array();
foreach ($rowordertab as $value) {
if (!empty($value)) {
@ -71,7 +71,9 @@ if (GETPOSTISSET('roworder')) {
}
}
require DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php';
$row = new ProductAttribute($db);
ProductAttribute::bulkUpdateOrder($db, $newrowordertab);
$row->attributesAjaxOrder($newrowordertab); // This update field rank or position in table row->table_element_line
} else {
print 'Bad parameters for orderAttribute.php';
}

View File

@ -1,6 +1,7 @@
<?php
/* Copyright (C) 2016 Marcos García <marcosgdf@gmail.com>
* Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr>
* Copyright (C) 2022 Open-Dsi <support@open-dsi.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -16,27 +17,29 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/variants/card.php
* \ingroup variants
* \brief Page to show product attribute
*/
require '../main.inc.php';
require 'class/ProductAttribute.class.php';
require 'class/ProductAttributeValue.class.php';
require 'lib/variants.lib.php';
// Load translation files required by the page
$langs->loadLangs(array('products'));
$id = GETPOST('id', 'int');
$valueid = GETPOST('valueid', 'alpha');
$action = GETPOST('action', 'aZ09');
$label = GETPOST('label', 'alpha');
$ref = GETPOST('ref', 'alpha');
$action = GETPOST('action', 'aZ09');
$confirm = GETPOST('confirm', 'alpha');
$cancel = GETPOST('cancel', 'alpha');
$object = new ProductAttribute($db);
$objectval = new ProductAttributeValue($db);
if ($object->fetch($id) < 1) {
dol_print_error($db, $langs->trans('ErrorRecordNotFound'));
exit();
}
$permissiontoread = $user->rights->produit->lire || $user->rights->service->lire;
$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'productattribute'; // To manage different context of search
$backtopage = GETPOST('backtopage', 'alpha');
$backtopageforcancel = GETPOST('backtopageforcancel', 'alpha');
$lineid = GETPOST('lineid', 'alpha');
// Security check
if (empty($conf->variants->enabled)) {
@ -45,84 +48,102 @@ if (empty($conf->variants->enabled)) {
if ($user->socid > 0) { // Protection if external user
accessforbidden();
}
//$result = restrictedArea($user, 'variant');
if (!$permissiontoread) accessforbidden();
$result = restrictedArea($user, 'variants');
$object = new ProductAttribute($db);
// Load object
include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once
// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
$hookmanager->initHooks(array('productattributecard', 'globalcard'));
$permissiontoread = $user->rights->produit->lire || $user->rights->service->lire;
$permissiontoadd = $user->rights->produit->lire || $user->rights->service->lire; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
$permissiontoedit = $user->rights->produit->lire || $user->rights->service->lire; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
$permissiontodelete = $user->rights->produit->lire || $user->rights->service->lire;
$error = 0;
/*
* Actions
*/
if ($cancel) {
$action = '';
$parameters = array();
// Note that $action and $object may be modified by some hooks
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action);
if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
if ($action) {
if ($action == 'update') {
$object->ref = $ref;
$object->label = $label;
if (empty($reshook)) {
$error = 0;
if ($object->update($user) < 1) {
setEventMessages($langs->trans('CoreErrorMessage'), $object->errors, 'errors');
} else {
setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
header('Location: '.dol_buildpath('/variants/card.php?id='.$id, 2));
exit();
}
} elseif ($action == 'update_value') {
if ($objectval->fetch($valueid) > 0) {
$objectval->ref = $ref;
$objectval->value = GETPOST('value', 'alpha');
$backurlforlist = dol_buildpath('/variants/list.php', 1);
if (empty($objectval->ref)) {
$error++;
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref")), null, 'errors');
}
if (empty($objectval->value)) {
$error++;
setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label")), null, 'errors');
}
if (!$error) {
if ($objectval->update($user) > 0) {
setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
} else {
setEventMessage($langs->trans('CoreErrorMessage'), $objectval->errors, 'errors');
}
if (empty($backtopage) || ($cancel && empty($id))) {
if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) {
$backtopage = $backurlforlist;
} else {
$backtopage = dol_buildpath('/variants/card.php', 1).'?id='.((!empty($id) && $id > 0) ? $id : '__ID__');
}
}
}
header('Location: '.dol_buildpath('/variants/card.php?id='.$object->id, 2));
// Action to move up and down lines of object
include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php';
if ($cancel) {
if (!empty($backtopage)) {
header("Location: " . $backtopage);
exit;
}
$action = '';
}
// Actions cancel, add, update, update_extras, confirm_validate, confirm_delete, confirm_deleteline, confirm_clone, confirm_close, confirm_setdraft, confirm_reopen
include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php';
// Action to move up and down lines of object
if ($action == 'up' && $permissiontoedit) {
$object->line_up(GETPOST('rowid'), false);
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'#'.GETPOST('rowid'));
exit();
} elseif ($action == 'down' && $permissiontoedit) {
$object->line_down(GETPOST('rowid'), false);
header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.'#'.GETPOST('rowid'));
exit();
}
}
if ($confirm == 'yes') {
if ($action == 'confirm_delete') {
$db->begin();
if ($action == 'addline' && $permissiontoedit) {
$line_ref = GETPOST('line_ref', 'alpha');
$line_value = GETPOST('line_value', 'alpha');
$res = $objectval->deleteByFkAttribute($object->id, $user);
if ($res < 1 || ($object->delete($user) < 1)) {
$db->rollback();
setEventMessages($langs->trans('CoreErrorMessage'), $object->errors, 'errors');
header('Location: '.dol_buildpath('/variants/card.php?id='.$object->id, 2));
} else {
$db->commit();
$result = $object->addLine($line_ref, $line_value);
if ($result > 0) {
setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
header('Location: '.dol_buildpath('/variants/list.php', 2));
}
exit();
} elseif ($action == 'confirm_deletevalue') {
if ($objectval->fetch($valueid) > 0) {
if ($objectval->delete($user) < 1) {
setEventMessages($langs->trans('CoreErrorMessage'), $objectval->errors, 'errors');
} else {
setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
}
header('Location: '.dol_buildpath('/variants/card.php?id='.$object->id, 2));
header("Location: " . $_SERVER['PHP_SELF'] . '?id=' . $object->id);
exit();
} else {
setEventMessages($object->error, $object->errors, 'errors');
$action = '';
}
} elseif ($action == 'updateline' && $permissiontoedit) {
$line_ref = GETPOST('line_ref', 'alpha');
$line_value = GETPOST('line_value', 'alpha');
$result = $object->updateLine($lineid, $line_ref, $line_value);
if ($result > 0) {
setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
header("Location: " . $_SERVER['PHP_SELF'] . '?id=' . $object->id);
exit();
} else {
setEventMessages($object->error, $object->errors, 'errors');
$action = 'editline';
}
}
}
@ -132,171 +153,207 @@ if ($confirm == 'yes') {
* View
*/
$langs->load('products');
$help_url = 'EN:Module_Products#Variants';
$title = $langs->trans('ProductAttributeName', dol_htmlentities($object->label));
$help_url = 'EN:Module_Products#Variants';
llxHeader('', $title, $help_url);
//print load_fiche_titre($title);
// Part to create
if ($action == 'create') {
print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("ProductAttribute")), '', 'object_' . $object->picto);
$h = 0;
$head[$h][0] = DOL_URL_ROOT.'/variants/card.php?id='.$object->id;
$head[$h][1] = $langs->trans("ProductAttributeName");
$head[$h][2] = 'variant';
$h++;
print '<form method="POST" action="' . $_SERVER["PHP_SELF"] . '">';
print '<input type="hidden" name="token" value="' . newToken() . '">';
print '<input type="hidden" name="action" value="add">';
if ($backtopage) {
print '<input type="hidden" name="backtopage" value="' . $backtopage . '">';
}
if ($backtopageforcancel) {
print '<input type="hidden" name="backtopageforcancel" value="' . $backtopageforcancel . '">';
}
print dol_get_fiche_head($head, 'variant', $langs->trans('ProductAttributeName'), -1, 'generic');
print dol_get_fiche_head(array(), '');
if ($action == 'edit') {
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="update">';
print '<input type="hidden" name="id" value="'.$id.'">';
print '<input type="hidden" name="valueid" value="'.$valueid.'">';
print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
}
print '<table class="border centpercent tableforfieldcreate">' . "\n";
// Common attributes
include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_add.tpl.php';
if ($action != 'edit') {
print '<div class="fichecenter">';
print '<div class="underbanner clearboth"></div>';
}
print '<table class="border centpercent tableforfield">';
print '<tr>';
print '<td class="titlefield'.($action == 'edit' ? ' fieldrequired' : '').'">'.$langs->trans('Ref').'</td>';
print '<td>';
if ($action == 'edit') {
print '<input type="text" name="ref" value="'.$object->ref.'">';
} else {
print dol_htmlentities($object->ref);
}
print '</td>';
print '</tr>';
print '<tr>';
print '<td'.($action == 'edit' ? ' class="fieldrequired"' : '').'>'.$langs->trans('Label').'</td>';
print '<td>';
if ($action == 'edit') {
print '<input type="text" name="label" value="'.$object->label.'">';
} else {
print dol_htmlentities($object->label);
}
print '</td>';
print '</tr>';
print '</table>' . "\n";
print '</table>';
print dol_get_fiche_end();
if ($action != 'edit') {
print '<div class="center">';
print '<input type="submit" class="button" name="add" value="' . dol_escape_htmltag($langs->trans("Create")) . '">';
print '&nbsp; ';
print '<input type="' . ($backtopage ? "submit" : "button") . '" class="button button-cancel" name="cancel" value="' . dol_escape_htmltag($langs->trans("Cancel")) . '"' . ($backtopage ? '' : ' onclick="javascript:history.go(-1)"') . '>'; // Cancel for create does not post form if we don't know the backtopage
print '</div>';
print '</form>';
dol_set_focus('input[name="label"]');
}
print dol_get_fiche_end();
// Part to edit record
elseif (($id || $ref) && $action == 'edit') {
print load_fiche_titre($langs->trans("ProductAttribute"), '', 'object_' . $object->picto);
if ($action == 'edit') {
print '<div style="text-align: center;">';
print '<div class="inline-block divButAction">';
print '<input type="submit" class="button button-save" value="'.$langs->trans("Save").'">';
print '&nbsp; &nbsp;';
print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
print '</div>';
print '</div></form>';
} else {
if ($action == 'delete') {
$form = new Form($db);
print $form->formconfirm(
"card.php?id=".$object->id,
$langs->trans('Delete'),
$langs->trans('ProductAttributeDeleteDialog'),
"confirm_delete",
'',
0,
1
);
} elseif ($action == 'delete_value') {
if ($objectval->fetch($valueid) > 0) {
$form = new Form($db);
print $form->formconfirm(
"card.php?id=".$object->id."&valueid=".$objectval->id,
$langs->trans('Delete'),
$langs->trans('ProductAttributeValueDeleteDialog', dol_htmlentities($objectval->value), dol_htmlentities($objectval->ref)),
"confirm_deletevalue",
'',
0,
1
);
}
print '<form method="POST" action="' . $_SERVER["PHP_SELF"] . '">';
print '<input type="hidden" name="token" value="' . newToken() . '">';
print '<input type="hidden" name="action" value="update">';
print '<input type="hidden" name="id" value="' . $object->id . '">';
if ($backtopage) {
print '<input type="hidden" name="backtopage" value="' . $backtopage . '">';
}
if ($backtopageforcancel) {
print '<input type="hidden" name="backtopageforcancel" value="' . $backtopageforcancel . '">';
}
?>
print dol_get_fiche_head();
<div class="tabsAction">
<div class="inline-block divButAction">
<a href="card.php?id=<?php echo $object->id ?>&action=edit&token=<?php echo newToken(); ?>" class="butAction"><?php echo $langs->trans('Modify') ?></a>
<a href="card.php?id=<?php echo $object->id ?>&action=delete&token=<?php echo newToken(); ?>" class="butAction"><?php echo $langs->trans('Delete') ?></a>
</div>
</div>
print '<table class="border centpercent tableforfieldedit">' . "\n";
// Common attributes
include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_edit.tpl.php';
<?php
print load_fiche_titre($langs->trans("PossibleValues"));
if ($action == 'edit_value') {
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="update_value">';
print '<input type="hidden" name="id" value="'.$id.'">';
print '<input type="hidden" name="valueid" value="'.$valueid.'">';
print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
}
print '<table class="liste">';
print '<tr class="liste_titre">';
print '<th class="liste_titre titlefield">'.$langs->trans('Ref').'</th>';
print '<th class="liste_titre">'.$langs->trans('Value').'</th>';
print '<th class="liste_titre"></th>';
print '</tr>';
foreach ($objectval->fetchAllByProductAttribute($object->id) as $attrval) {
print '<tr class="oddeven">';
if ($action == 'edit_value' && ($valueid == $attrval->id)) {
?>
<td><input type="text" name="ref" value="<?php echo $attrval->ref ?>"></td>
<td><input type="text" name="value" value="<?php echo $attrval->value ?>"></td>
<td class="right">
<input type="submit" value="<?php echo $langs->trans("Save") ?>" class="button button-save">
&nbsp; &nbsp;
<input type="submit" name="cancel" value="<?php echo $langs->trans("Cancel") ?>" class="button button-cancel">
</td>
<?php
} else {
?>
<td><?php echo dol_htmlentities($attrval->ref) ?></td>
<td><?php echo dol_htmlentities($attrval->value) ?></td>
<td class="right">
<a class="editfielda marginrightonly" href="card.php?id=<?php echo $object->id ?>&action=edit_value&valueid=<?php echo $attrval->id ?>"><?php echo img_edit() ?></a>
<a href="card.php?id=<?php echo $object->id ?>&action=delete_value&token=<?php echo newToken(); ?>&valueid=<?php echo $attrval->id ?>"><?php echo img_delete() ?></a>
</td>
<?php
}
print '</tr>';
}
print '</table>';
if ($action == 'edit_value') {
print '</form>';
print dol_get_fiche_end();
print '<div class="center"><input type="submit" class="button button-save" name="save" value="' . $langs->trans("Save") . '">';
print ' &nbsp; <input type="submit" class="button button-cancel" name="cancel" value="' . $langs->trans("Cancel") . '">';
print '</div>';
print '</form>';
}
// Part to show record
elseif ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) {
$res = $object->fetch_optionals();
$head = productAttributePrepareHead($object);
print dol_get_fiche_head($head, 'card', $langs->trans("ProductAttribute"), -1, $object->picto);
$formconfirm = '';
// Confirmation to delete
if ($action == 'delete') {
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id, $langs->trans('DeleteMyObject'), $langs->trans('ProductAttributeDeleteDialog'), 'confirm_delete', '', 0, 1);
} elseif ($action == 'ask_deleteline') {
// Confirmation to delete line
$object_value = new ProductAttributeValue($db);
if ($object_value->fetch($lineid) > 0) {
$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"] . '?id=' . $object->id . '&lineid=' . $lineid, $langs->trans('DeleteLine'), $langs->trans('ProductAttributeValueDeleteDialog', dol_htmlentities($object_value->value), dol_htmlentities($object_value->ref)), 'confirm_deleteline', '', 0, 1);
}
}
print '<div class="tabsAction">';
print '<div class="inline-block divButAction">';
print '<a href="create_val.php?id='.$object->id.'" class="butAction">'.$langs->trans('Create').'</a>';
// Call Hook formConfirm
$parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid);
$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if (empty($reshook)) {
$formconfirm .= $hookmanager->resPrint;
} elseif ($reshook > 0) {
$formconfirm = $hookmanager->resPrint;
}
// Print form confirm
print $formconfirm;
// Object card
// ------------------------------------------------------------
$backtolist = (GETPOST('backtolist') ? GETPOST('backtolist') : DOL_URL_ROOT . '/variants/list.php?leftmenu=?restore_lastsearch_values=1');
$linkback = '<a href="' . dol_sanitizeUrl($backtolist) . '">' . $langs->trans("BackToList") . '</a>';
dol_banner_tab($object, 'id', $linkback);
print '<div class="fichecenter">';
print '<div class="fichehalfleft">';
print '<div class="underbanner clearboth"></div>';
print '<table class="border centpercent tableforfield">' . "\n";
// Common attributes
include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php';
print '</table>';
print '</div>';
print '</div>';
print '<div class="clearboth"></div>';
print dol_get_fiche_end();
// Buttons for actions
if ($action != 'editline') {
print '<div class="tabsAction">' . "\n";
$parameters = array();
$reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
if (empty($reshook)) {
// Modify
print dolGetButtonAction($langs->trans('Modify'), '', 'default', $_SERVER["PHP_SELF"] . '?id=' . $object->id . '&action=edit', '', $permissiontoedit);
// Delete (need delete permission, or if draft, just need create/modify permission)
print dolGetButtonAction($langs->trans('Delete'), '', 'delete', $_SERVER['PHP_SELF'] . '?id=' . $object->id . '&action=delete', '', $permissiontodelete);
}
print '</div>' . "\n";
}
/*
* Lines
*/
if (!empty($object->table_element_line)) {
// Show object lines
$result = $object->getLinesArray();
print load_fiche_titre($langs->trans("PossibleValues") . (!empty($object->lines) ? ' (' . count($object->lines) . ')' : ''));
print ' <form name="addproduct" id="addproduct" action="' . $_SERVER["PHP_SELF"] . '?id=' . $object->id . (($action != 'editline') ? '' : '#line_' . GETPOST('lineid', 'int')) . '" method="POST">
<input type="hidden" name="token" value="' . newToken() . '">
<input type="hidden" name="action" value="' . (($action != 'editline') ? 'addline' : 'updateline') . '">
<input type="hidden" name="mode" value="">
<input type="hidden" name="page_y" value="">
<input type="hidden" name="id" value="' . $object->id . '">
';
if ($backtopage) {
print '<input type="hidden" name="backtopage" value="' . $backtopage . '">';
}
if ($backtopageforcancel) {
print '<input type="hidden" name="backtopageforcancel" value="' . $backtopageforcancel . '">';
}
if (!empty($conf->use_javascript_ajax)) {
include DOL_DOCUMENT_ROOT . '/core/tpl/ajaxrow.tpl.php';
}
print '<div class="div-table-responsive-no-min">';
if (!empty($object->lines) || ($permissiontoedit && $action != 'selectlines' && $action != 'editline')) {
print '<table id="tablelines" class="noborder noshadow" width="100%">';
}
// Form to add new line
if ($permissiontoedit && $action != 'selectlines') {
if ($action != 'editline') {
// Add products/services form
$parameters = array();
$reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
if (empty($reshook))
$object->formAddObjectLine(1, $mysoc, $soc);
}
}
if (!empty($object->lines)) {
$object->printObjectLines($action, $mysoc, null, GETPOST('lineid', 'int'), 1);
}
if (!empty($object->lines) || ($permissiontoedit && $action != 'selectlines' && $action != 'editline')) {
print '</table>';
}
print '</div>';
print "</form>\n";
}
}
// End of page

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,7 @@
<?php
/* Copyright (C) 2016 Marcos García <marcosgdf@gmail.com>
* Copyright (C) 2022 Open-Dsi <support@open-dsi.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -16,42 +17,79 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
/**
* Class ProductAttributeValue
* Used to represent a product attribute value
*/
class ProductAttributeValue extends CommonObject
class ProductAttributeValue extends CommonObjectLine
{
/**
* Database handler
* @var DoliDB
* @var string ID of module.
*/
public $db;
public $module = 'variants';
/**
* Attribute value id
* @var int
* @var string ID to identify managed object.
*/
public $element = 'productattributevalue';
/**
* @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
*/
public $table_element = 'product_attribute_value';
/**
* @var int Does this object support multicompany module ?
* 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
*/
public $ismultientitymanaged = 1;
/**
* @var int Does object support extrafields ? 0=No, 1=Yes
*/
public $isextrafieldmanaged = 0;
/**
* 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
* Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
* 'label' the translation key.
* 'picto' is code of a picto to show before value in forms
* 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
* 'position' is the sort order of field.
* 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
* 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
* 'noteditable' says if field is not editable (1 or 0)
* 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
* 'index' if we want an index in database.
* 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
* 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
* 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
* 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'maxwidth200', 'wordbreak', 'tdoverflowmax200'
* 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
* 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
* 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
* 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
* 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
* 'comment' is not used. You can store here any text of your choice. It is not used by application.
*
* Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
*/
/**
* @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
*/
public $fields=array(
'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
'fk_product_attribute' => array('type'=>'integer:ProductAttribute:variants/class/ProductAttribute.class.php', 'label'=>'ProductAttribute', 'enabled'=>1, 'visible'=>0, 'position'=>10, 'notnull'=>1, 'index'=>1,),
'ref' => array('type'=>'varchar(255)', 'label'=>'Ref', 'visible'=>1, 'enabled'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object", 'css'=>''),
'value' => array('type'=>'varchar(255)', 'label'=>'Value', 'enabled'=>'1', 'position'=>30, 'notnull'=>1, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'help'=>"", 'showoncombobox'=>'1',),
'position' => array('type'=>'integer', 'label'=>'Rank', 'enabled'=>1, 'visible'=>0, 'default'=>0, 'position'=>200, 'notnull'=>1,),
);
public $id;
/**
* Product attribute id
* @var int
*/
public $fk_product_attribute;
/**
* Attribute value ref
* @var string
*/
public $ref;
/**
* Attribute value value
* @var string
*/
public $value;
public $position;
/**
* Constructor
@ -60,40 +98,163 @@ class ProductAttributeValue extends CommonObject
*/
public function __construct(DoliDB $db)
{
global $conf;
global $conf, $langs;
$this->db = $db;
$this->entity = $conf->entity;
if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
$this->fields['rowid']['visible'] = 0;
}
if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
$this->fields['entity']['enabled'] = 0;
}
// Unset fields that are disabled
foreach ($this->fields as $key => $val) {
if (isset($val['enabled']) && empty($val['enabled'])) {
unset($this->fields[$key]);
}
}
// Translate some data of arrayofkeyval
if (is_object($langs)) {
foreach ($this->fields as $key => $val) {
if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
foreach ($val['arrayofkeyval'] as $key2 => $val2) {
$this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
}
}
}
}
}
/**
* Creates a value for a product attribute
*
* @param User $user Object user
* @param int $notrigger Do not execute trigger
* @return int <0 KO >0 OK
*/
public function create(User $user, $notrigger = 0)
{
global $langs;
$error = 0;
// Clean parameters
$this->fk_product_attribute = $this->fk_product_attribute > 0 ? $this->fk_product_attribute : 0;
$this->ref = strtoupper(dol_sanitizeFileName(dol_string_nospecial(trim($this->ref)))); // Ref must be uppercase
$this->value = trim($this->value);
// Check parameters
if (empty($this->fk_product_attribute)) {
$this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductAttribute"));
$error++;
}
if (empty($this->ref)) {
$this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref"));
$error++;
}
if (empty($this->value)) {
$this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Value"));
$error++;
}
if ($error) {
dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
return -1;
}
$this->db->begin();
$sql = "INSERT INTO " . MAIN_DB_PREFIX . $this->table_element . " (";
$sql .= " fk_product_attribute, ref, value, entity, position";
$sql .= ")";
$sql .= " VALUES (";
$sql .= " " . ((int) $this->fk_product_attribute);
$sql .= ", '" . $this->db->escape($this->ref) . "'";
$sql .= ", '" . $this->db->escape($this->value) . "'";
$sql .= ", " . ((int) $this->entity);
$sql .= ", " . ((int) $this->position);
$sql .= ")";
dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql);
if (!$resql) {
$this->errors[] = "Error " . $this->db->lasterror();
$error++;
}
if (!$error) {
$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
}
if (!$error && !$notrigger) {
// Call trigger
$result = $this->call_trigger('PRODUCT_ATTRIBUTE_VALUE_CREATE', $user);
if ($result < 0) {
$error++;
}
// End call triggers
}
if ($error) {
$this->db->rollback();
return -1 * $error;
} else {
$this->db->commit();
return $this->id;
}
}
/**
* Gets a product attribute value
*
* @param int $valueid Product attribute value id
* @param int $id Product attribute value id
* @return int <0 KO, >0 OK
*/
public function fetch($valueid)
public function fetch($id)
{
$sql = "SELECT rowid, fk_product_attribute, ref, value FROM ".MAIN_DB_PREFIX."product_attribute_value WHERE rowid = ".(int) $valueid." AND entity IN (".getEntity('product').")";
global $langs;
$error = 0;
$query = $this->db->query($sql);
// Clean parameters
$id = $id > 0 ? $id : 0;
if (!$query) {
// Check parameters
if (empty($id)) {
$this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID"));
$error++;
}
if ($error) {
dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
return -1;
}
if (!$this->db->num_rows($query)) {
$sql = "SELECT rowid, fk_product_attribute, ref, value";
$sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element;
$sql .= " WHERE rowid = " . ((int) $id);
$sql .= " AND entity IN (" . getEntity('product') . ")";
dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql);
if (!$resql) {
$this->errors[] = "Error " . $this->db->lasterror();
dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
return -1;
}
$obj = $this->db->fetch_object($query);
$numrows = $this->db->num_rows($resql);
if ($numrows) {
$obj = $this->db->fetch_object($resql);
$this->id = $obj->rowid;
$this->fk_product_attribute = $obj->fk_product_attribute;
$this->ref = $obj->ref;
$this->value = $obj->value;
$this->id = $obj->rowid;
$this->fk_product_attribute = $obj->fk_product_attribute;
$this->ref = $obj->ref;
$this->value = $obj->value;
}
$this->db->free($resql);
return 1;
return $numrows;
}
/**
@ -107,24 +268,24 @@ class ProductAttributeValue extends CommonObject
{
$return = array();
$sql = 'SELECT ';
$sql = "SELECT ";
if ($only_used) {
$sql .= 'DISTINCT ';
$sql .= "DISTINCT ";
}
$sql .= 'v.fk_product_attribute, v.rowid, v.ref, v.value FROM '.MAIN_DB_PREFIX.'product_attribute_value v ';
$sql .= "v.fk_product_attribute, v.rowid, v.ref, v.value FROM " . MAIN_DB_PREFIX . "product_attribute_value v ";
if ($only_used) {
$sql .= 'LEFT JOIN '.MAIN_DB_PREFIX.'product_attribute_combination2val c2v ON c2v.fk_prod_attr_val = v.rowid ';
$sql .= 'LEFT JOIN '.MAIN_DB_PREFIX.'product_attribute_combination c ON c.rowid = c2v.fk_prod_combination ';
$sql .= 'LEFT JOIN '.MAIN_DB_PREFIX.'product p ON p.rowid = c.fk_product_child ';
$sql .= "LEFT JOIN " . MAIN_DB_PREFIX . "product_attribute_combination2val c2v ON c2v.fk_prod_attr_val = v.rowid ";
$sql .= "LEFT JOIN " . MAIN_DB_PREFIX . "product_attribute_combination c ON c.rowid = c2v.fk_prod_combination ";
$sql .= "LEFT JOIN " . MAIN_DB_PREFIX . "product p ON p.rowid = c.fk_product_child ";
}
$sql .= 'WHERE v.fk_product_attribute = '.(int) $prodattr_id;
$sql .= "WHERE v.fk_product_attribute = " . ((int) $prodattr_id);
if ($only_used) {
$sql .= ' AND c2v.rowid IS NOT NULL AND p.tosell = 1';
$sql .= " AND c2v.rowid IS NOT NULL AND p.tosell = 1";
}
$query = $this->db->query($sql);
@ -142,45 +303,6 @@ class ProductAttributeValue extends CommonObject
return $return;
}
/**
* Creates a value for a product attribute
*
* @param User $user Object user
* @param int $notrigger Do not execute trigger
* @return int <0 KO >0 OK
*/
public function create(User $user, $notrigger = 0)
{
if (!$this->fk_product_attribute) {
return -1;
}
// Ref must be uppercase
$this->ref = strtoupper($this->ref);
$this->value = $this->db->escape($this->value);
$sql = "INSERT INTO ".MAIN_DB_PREFIX."product_attribute_value (fk_product_attribute, ref, value, entity)
VALUES (".(int) $this->fk_product_attribute.", '".$this->db->escape($this->ref)."', '".$this->db->escape($this->value)."', ".(int) $this->entity.")";
$query = $this->db->query($sql);
if ($query) {
$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'product_attribute_value');
if (empty($notrigger)) {
// Call trigger
$result = $this->call_trigger('PRODUCT_ATTRIBUTE_VALUE_CREATE', $user);
if ($result < 0) {
return -1;
}
// End call triggers
}
return 1;
}
return -1;
}
/**
* Updates a product attribute value
*
@ -190,28 +312,66 @@ class ProductAttributeValue extends CommonObject
*/
public function update(User $user, $notrigger = 0)
{
if (empty($notrigger)) {
global $langs;
$error = 0;
// Clean parameters
$this->fk_product_attribute = $this->fk_product_attribute > 0 ? $this->fk_product_attribute : 0;
$this->ref = strtoupper(dol_sanitizeFileName(dol_string_nospecial(trim($this->ref)))); // Ref must be uppercase
$this->value = trim($this->value);
// Check parameters
if (empty($this->fk_product_attribute)) {
$this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductAttribute"));
$error++;
}
if (empty($this->ref)) {
$this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref"));
$error++;
}
if (empty($this->value)) {
$this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Value"));
$error++;
}
if ($error) {
dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
return -1;
}
$this->db->begin();
$sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET";
$sql .= " fk_product_attribute = " . ((int) $this->fk_product_attribute);
$sql .= ", ref = '" . $this->db->escape($this->ref) . "'";
$sql .= ", value = '" . $this->db->escape($this->value) . "'";
$sql .= ", position = " . ((int) $this->position);
$sql .= " WHERE rowid = " . ((int) $this->id);
dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql);
if (!$resql) {
$this->errors[] = "Error " . $this->db->lasterror();
$error++;
}
if (!$error && !$notrigger) {
// Call trigger
$result = $this->call_trigger('PRODUCT_ATTRIBUTE_VALUE_MODIFY', $user);
if ($result < 0) {
return -1;
$error++;
}
// End call triggers
}
//Ref must be uppercase
$this->ref = trim(strtoupper($this->ref));
$this->value = trim($this->value);
$sql = "UPDATE ".MAIN_DB_PREFIX."product_attribute_value
SET fk_product_attribute = '".(int) $this->fk_product_attribute."', ref = '".$this->db->escape($this->ref)."',
value = '".$this->db->escape($this->value)."' WHERE rowid = ".(int) $this->id;
if ($this->db->query($sql)) {
if (!$error) {
$this->db->commit();
return 1;
} else {
$this->db->rollback();
return -1 * $error;
}
return -1;
}
/**
@ -223,56 +383,98 @@ class ProductAttributeValue extends CommonObject
*/
public function delete(User $user, $notrigger = 0)
{
global $langs;
$error = 0;
if (empty($notrigger)) {
// Call trigger
$result = $this->call_trigger('PRODUCT_ATTRIBUTE_VALUE_DELETE', $user);
if ($result < 0) {
return -1;
}
// End call triggers
// Clean parameters
$this->id = $this->id > 0 ? $this->id : 0;
// Check parameters
if (empty($this->id)) {
$this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID"));
$error++;
}
$sql = "DELETE FROM ".MAIN_DB_PREFIX."product_attribute_value WHERE rowid = ".(int) $this->id;
if ($this->db->query($sql)) {
return 1;
}
return -1;
}
/**
* Deletes all product attribute values by a product attribute id
*
* @param int $fk_attribute Product attribute id
* @param User $user Object user
* @return int <0 KO, >0 OK
*/
public function deleteByFkAttribute($fk_attribute, User $user)
{
$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product_attribute_value WHERE fk_product_attribute = ".(int) $fk_attribute;
$query = $this->db->query($sql);
if (!$query) {
if ($error) {
dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
return -1;
}
if (!$this->db->num_rows($query)) {
return 1;
$result = $this->isUsed();
if ($result < 0) {
return -1;
} elseif ($result > 0) {
$this->errors[] = $langs->trans('ErrorAttributeValueIsUsedIntoProduct');
return -1;
}
while ($obj = $this->db->fetch_object($query)) {
$tmp = new ProductAttributeValue($this->db);
if ($tmp->fetch($obj->rowid) > 0) {
$result = $tmp->delete($user);
if ($result < 0) {
return -1;
}
} else {
return -1;
$this->db->begin();
if (!$error && !$notrigger) {
// Call trigger
$result = $this->call_trigger('PRODUCT_ATTRIBUTE_VALUE_DELETE', $user);
if ($result < 0) {
$error++;
}
// End call triggers
}
if (!$error) {
$sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element . " WHERE rowid = " . ((int) $this->id);
dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql);
if (!$resql) {
$this->errors[] = "Error " . $this->db->lasterror();
$error++;
}
}
return 1;
if (!$error) {
$this->db->commit();
return 1;
} else {
$this->db->rollback();
return -1 * $error;
}
}
/**
* Test if used by a product
*
* @return int <0 KO, =0 if No, =1 if Yes
*/
public function isUsed()
{
global $langs;
$error = 0;
// Clean parameters
$this->id = $this->id > 0 ? $this->id : 0;
// Check parameters
if (empty($this->id)) {
$this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID"));
$error++;
}
if ($error) {
dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
return -1;
}
$sql = "SELECT COUNT(*) AS nb FROM " . MAIN_DB_PREFIX . "product_attribute_combination2val WHERE fk_prod_attr_val = " . ((int) $this->id);
dol_syslog(__METHOD__, LOG_DEBUG);
$resql = $this->db->query($sql);
if (!$resql) {
$this->errors[] = "Error " . $this->db->lasterror();
return -1;
}
$used = 0;
if ($obj = $this->db->fetch_object($resql)) {
$used = $obj->nb;
}
return $used ? 1 : 0;
}
}

View File

@ -2,6 +2,7 @@
/* Copyright (C) 2016 Marcos García <marcosgdf@gmail.com>
* Copyright (C) 2018 Juanjo Menent <jmenent@2byte.es>
* Copyright (C) 2022 Open-Dsi <support@open-dsi.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -628,12 +629,12 @@ class ProductCombination
$variants = array();
//Attributes
$sql = "SELECT DISTINCT fk_prod_attr, a.rang";
$sql = "SELECT DISTINCT fk_prod_attr, a.position";
$sql .= " FROM ".MAIN_DB_PREFIX."product_attribute_combination2val c2v LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination c ON c2v.fk_prod_combination = c.rowid";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product p ON p.rowid = c.fk_product_child";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute a ON a.rowid = fk_prod_attr";
$sql .= " WHERE c.fk_product_parent = ".((int) $productid)." AND p.tosell = 1";
$sql .= $this->db->order('a.rang', 'asc');
$sql .= $this->db->order('a.position', 'asc');
$query = $this->db->query($sql);

View File

@ -1,6 +1,7 @@
<?php
/* Copyright (C) 2016 Marcos García <marcosgdf@gmail.com>
* Copyright (C) 2022 Open-Dsi <support@open-dsi.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -69,8 +70,8 @@ class ProductCombination2ValuePair
*/
public function __toString()
{
require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttributeValue.class.php';
require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php';
require_once DOL_DOCUMENT_ROOT . '/variants/class/ProductAttributeValue.class.php';
require_once DOL_DOCUMENT_ROOT . '/variants/class/ProductAttribute.class.php';
$prodattr = new ProductAttribute($this->db);
$prodattrval = new ProductAttributeValue($this->db);
@ -78,7 +79,7 @@ class ProductCombination2ValuePair
$prodattr->fetch($this->fk_prod_attr);
$prodattrval->fetch($this->fk_prod_attr_val);
return $prodattr->label.': '.$prodattrval->value;
return $prodattr->label . ': ' . $prodattrval->value;
}
/**
@ -87,14 +88,14 @@ class ProductCombination2ValuePair
*/
public function create()
{
$sql = "INSERT INTO ".MAIN_DB_PREFIX."product_attribute_combination2val
$sql = "INSERT INTO " . MAIN_DB_PREFIX . "product_attribute_combination2val
(fk_prod_combination, fk_prod_attr, fk_prod_attr_val)
VALUES(".(int) $this->fk_prod_combination.", ".(int) $this->fk_prod_attr.", ".(int) $this->fk_prod_attr_val.")";
VALUES(" . (int) $this->fk_prod_combination . ", " . (int) $this->fk_prod_attr . ", " . (int) $this->fk_prod_attr_val . ")";
$query = $this->db->query($sql);
if ($query) {
$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'product_attribute_combination2val');
$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . 'product_attribute_combination2val');
return 1;
}
@ -115,10 +116,10 @@ class ProductCombination2ValuePair
c2v.fk_prod_attr_val,
c2v.fk_prod_attr,
c2v.fk_prod_combination
FROM ".MAIN_DB_PREFIX."product_attribute c LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination2val c2v ON c.rowid = c2v.fk_prod_attr
WHERE c2v.fk_prod_combination = ".(int) $fk_combination;
FROM " . MAIN_DB_PREFIX . "product_attribute c LEFT JOIN " . MAIN_DB_PREFIX . "product_attribute_combination2val c2v ON c.rowid = c2v.fk_prod_attr
WHERE c2v.fk_prod_combination = " . (int) $fk_combination;
$sql .= $this->db->order('c.rang', 'asc');
$sql .= $this->db->order('c.position', 'asc');
$query = $this->db->query($sql);
@ -149,7 +150,7 @@ class ProductCombination2ValuePair
*/
public function deleteByFkCombination($fk_combination)
{
$sql = "DELETE FROM ".MAIN_DB_PREFIX."product_attribute_combination2val WHERE fk_prod_combination = ".(int) $fk_combination;
$sql = "DELETE FROM " . MAIN_DB_PREFIX . "product_attribute_combination2val WHERE fk_prod_combination = " . (int) $fk_combination;
if ($this->db->query($sql)) {
return 1;

View File

@ -2,6 +2,7 @@
/* Copyright (C) 2016 Marcos García <marcosgdf@gmail.com>
* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
* Copyright (C) 2018-2019 Frédéric France <frederic.france@netlogic.fr>
* Copyright (C) 2022 Open-Dsi <support@open-dsi.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -50,6 +51,7 @@ $confirm = GETPOST('confirm', 'alpha');
$toselect = GETPOST('toselect', 'array');
$cancel = GETPOST('cancel', 'alpha');
$delete_product = GETPOST('delete_product', 'alpha');
$subaction = GETPOST('subaction', 'aZ09');
// Security check
$fieldvalue = (!empty($id) ? $id : $ref);
@ -106,8 +108,19 @@ if ($action == 'add') {
}
if ($action == 'create' && GETPOST('selectvariant', 'alpha')) { // We click on select combination
$action = 'add';
if (GETPOST('attribute') != '-1' && GETPOST('value') != '-1') {
$selectedvariant[GETPOST('attribute').':'.GETPOST('value')] = GETPOST('attribute').':'.GETPOST('value');
$attribute_id = GETPOST('attribute', 'int');
$attribute_value_id = GETPOST('value', 'int');
if ($attribute_id> 0 && $attribute_value_id > 0) {
$feature = $attribute_id . '-' . $attribute_value_id;
$selectedvariant[$feature] = $feature;
$_SESSION['addvariant_'.$object->id] = $selectedvariant;
}
}
if ($action == 'create' && $subaction == 'delete') { // We click on select combination
$action = 'add';
$feature = GETPOST('feature', 'intcomma');
if (isset($selectedvariant[$feature])) {
unset($selectedvariant[$feature]);
$_SESSION['addvariant_'.$object->id] = $selectedvariant;
}
}
@ -118,7 +131,7 @@ $prodcomb2val = new ProductCombination2ValuePair($db);
$productCombination2ValuePairs1 = array();
if (($action == 'add' || $action == 'create') && empty($massaction) && !GETPOST('selectvariant', 'alpha')) { // We click on Create all defined combinations
if (($action == 'add' || $action == 'create') && empty($massaction) && !GETPOST('selectvariant', 'alpha') && empty($subaction)) { // We click on Create all defined combinations
//$features = GETPOST('features', 'array');
$features = $_SESSION['addvariant_'.$object->id];
@ -146,13 +159,8 @@ if (($action == 'add' || $action == 'create') && empty($massaction) && !GETPOST(
//First, sanitize
foreach ($features as $feature) {
$explode = explode(':', $feature);
if ($prodattr->fetch($explode[0]) < 0) {
continue;
}
if ($prodattr_val->fetch($explode[1]) < 0) {
$explode = explode('-', $feature);
if ($prodattr->fetch($explode[0]) <= 0 || $prodattr_val->fetch($explode[1]) <= 0) {
continue;
}
@ -460,19 +468,16 @@ if (!empty($id) || !empty($ref)) {
//First, sanitize
$listofvariantselected = '<div id="parttoaddvariant">';
if (!empty($features)) {
$toprint = array();
foreach ($features as $feature) {
$explode = explode(':', $feature);
if ($prodattr->fetch($explode[0]) < 0) {
$explode = explode('-', $feature);
if ($prodattr->fetch($explode[0]) <= 0 || $prodattr_val->fetch($explode[1]) <= 0) {
continue;
}
if ($prodattr_val->fetch($explode[1]) < 0) {
continue;
}
$listofvariantselected .= '<i>'.$prodattr->label.'</i>:'.$prodattr_val->value.' ';
$toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #ddd;">' . $prodattr->label.' : '.$prodattr_val->value .
' <a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=create&subaction=delete&feature='.urlencode($feature).'">' . img_delete() . '</a></li>';
}
$listofvariantselected .= '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
}
$listofvariantselected .= '</div>';
//print dol_get_fiche_end();
@ -572,9 +577,8 @@ if (!empty($id) || !empty($ref)) {
print load_fiche_titre($title);
print '<form method="post" id="combinationform" action="'.$_SERVER["PHP_SELF"].'">'."\n";
print '<form method="post" id="combinationform" action="'.$_SERVER["PHP_SELF"] .'?id='.$object->id.'">'."\n";
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="id" value="'.dol_escape_htmltag($id).'">'."\n";
print '<input type="hidden" name="action" value="'.(($valueid > 0) ? "update" : "create").'">'."\n";
if ($valueid > 0) {
print '<input type="hidden" name="valueid" value="'.$valueid.'">'."\n";
@ -820,10 +824,9 @@ if (!empty($id) || !empty($ref)) {
// List of variants
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<form method="POST" action="'.$_SERVER["PHP_SELF"] .'?id='.$object->id.'">';
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="massaction">';
print '<input type="hidden" name="id" value="'.$id.'">';
print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
// List of mass actions available

View File

@ -1,115 +0,0 @@
<?php
/* Copyright (C) 2016 Marcos García <marcosgdf@gmail.com>
* Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
require '../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php';
$ref = GETPOST('ref', 'alpha');
$label = GETPOST('label', 'alpha');
$backtopage = GETPOST('backtopage', 'alpha');
$action = GETPOST('action', 'alpha');
$permissiontoread = $user->rights->produit->lire || $user->rights->service->lire;
// Security check
if (empty($conf->variants->enabled)) {
accessforbidden('Module not enabled');
}
if ($user->socid > 0) { // Protection if external user
accessforbidden();
}
//$result = restrictedArea($user, 'variant');
if (!$permissiontoread) accessforbidden();
/*
* Actions
*/
if ($action == 'add') {
if (empty($ref) || empty($label)) {
setEventMessages($langs->trans('ErrorFieldsRequired'), null, 'errors');
} else {
$prodattr = new ProductAttribute($db);
$prodattr->label = $label;
$prodattr->ref = $ref;
$resid = $prodattr->create($user);
if ($resid > 0) {
setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
if ($backtopage) {
header('Location: '.$backtopage);
} else {
header('Location: '.DOL_URL_ROOT.'/variants/card.php?id='.$resid.'&backtopage='.urlencode($backtopage));
}
exit;
} else {
setEventMessages($langs->trans('ErrorRecordAlreadyExists'), $prodattr->errors, 'errors');
}
}
}
$langs->load('products');
/*
* View
*/
$help_url = 'EN:Module_Products#Variants';
$title = $langs->trans('NewProductAttribute');
llxHeader('', $title, $help_url);
print load_fiche_titre($title);
print dol_get_fiche_head();
print '<form method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="add">';
print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
?>
<table class="border centpercent">
<tr>
<td class="titlefield fieldrequired"><label for="ref"><?php echo $langs->trans('Ref') ?></label></td>
<td><input type="text" id="ref" name="ref" value="<?php echo $ref ?>"></td>
<td><?php echo $langs->trans("VariantRefExample"); ?>
</tr>
<tr>
<td class="fieldrequired"><label for="label"><?php echo $langs->trans('Label') ?></label></td>
<td><input type="text" id="label" name="label" value="<?php echo $label ?>"></td>
<td><?php echo $langs->trans("VariantLabelExample"); ?>
</tr>
</table>
<?php
print dol_get_fiche_end();
print '<div class="center"><input type="submit" class="button" value="'.$langs->trans("Create").'"></div>';
print '</form>';
// End of page
llxFooter();
$db->close();

View File

@ -1,161 +0,0 @@
<?php
/* Copyright (C) 2016 Marcos García <marcosgdf@gmail.com>
* Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
require '../main.inc.php';
require 'class/ProductAttribute.class.php';
require 'class/ProductAttributeValue.class.php';
$id = GETPOST('id', 'int');
$ref = GETPOST('ref', 'alpha');
$value = GETPOST('value', 'alpha');
$action = GETPOST('action', 'aZ09');
$cancel = GETPOST('cancel', 'alpha');
$backtopage = GETPOST('backtopage', 'alpha');
$object = new ProductAttribute($db);
$objectval = new ProductAttributeValue($db);
if ($object->fetch($id) < 1) {
dol_print_error($db, $langs->trans('ErrorRecordNotFound'));
exit();
}
$permissiontoread = $user->rights->produit->lire || $user->rights->service->lire;
// Security check
if (empty($conf->variants->enabled)) {
accessforbidden('Module not enabled');
}
if ($user->socid > 0) { // Protection if external user
accessforbidden();
}
//$result = restrictedArea($user, 'variant');
if (!$permissiontoread) accessforbidden();
/*
* Actions
*/
if ($cancel) {
$action = '';
header('Location: '.DOL_URL_ROOT.'/variants/card.php?id='.$object->id);
exit();
}
// None
/*
* View
*/
if ($action == 'add') {
if (empty($ref) || empty($value)) {
setEventMessages($langs->trans('ErrorFieldsRequired'), null, 'errors');
} else {
$objectval->fk_product_attribute = $object->id;
$objectval->ref = $ref;
$objectval->value = $value;
if ($objectval->create($user) > 0) {
setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
header('Location: '.DOL_URL_ROOT.'/variants/card.php?id='.$object->id);
exit();
} else {
setEventMessages($langs->trans('ErrorCreatingProductAttributeValue'), $objectval->errors, 'errors');
}
}
}
$langs->load('products');
$help_url = 'EN:Module_Products#Variants';
$title = $langs->trans('ProductAttributeName', dol_htmlentities($object->label));
llxHeader('', $title, $help_url);
$h = 0;
$head[$h][0] = DOL_URL_ROOT.'/variants/card.php?id='.$object->id;
$head[$h][1] = $langs->trans("ProductAttributeName");
$head[$h][2] = 'variant';
$h++;
print dol_get_fiche_head($head, 'variant', $langs->trans('ProductAttributeName'), -1, 'generic');
print '<div class="fichecenter">';
print '<div class="underbanner clearboth"></div>';
?>
<table class="border" style="width: 100%">
<tr>
<td class="titlefield fieldrequired"><?php echo $langs->trans('Ref') ?></td>
<td><?php echo dol_htmlentities($object->ref) ?>
</tr>
<tr>
<td class="fieldrequired"><?php echo $langs->trans('Label') ?></td>
<td><?php echo dol_htmlentities($object->label) ?></td>
</tr>
</table>
<?php
print '</div>';
print dol_get_fiche_end();
print '<br>';
print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="action" value="add">';
print '<input type="hidden" name="id" value="'.$object->id.'">';
print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
print load_fiche_titre($langs->trans('NewProductAttributeValue'));
print dol_get_fiche_head();
?>
<table class="border" style="width: 100%">
<tr>
<td class="titlefield fieldrequired"><label for="ref"><?php echo $langs->trans('Ref') ?></label></td>
<td><input id="ref" type="text" name="ref" value="<?php echo $ref ?>"></td>
</tr>
<tr>
<td class="fieldrequired"><label for="value"><?php echo $langs->trans('Label') ?></label></td>
<td><input id="value" type="text" name="value" value="<?php echo $value ?>"></td>
</tr>
</table>
<?php
print dol_get_fiche_end();
print '<div class="center">';
print '<input type="submit" class="button" name="create" value="'.$langs->trans("Create").'">';
print ' &nbsp; ';
print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
print '</div>';
print '</form>';
// End of page
llxFooter();
$db->close();

View File

@ -0,0 +1,53 @@
<?php
/* Copyright (C) 2022 Open-Dsi <support@open-dsi.fr>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* \file /variants/lib/variants.lib.php
* \ingroup variants
* \brief Library files with common functions for Variants
*/
/**
* Prepare array with list of tabs
*
* @param Product $object Object related to tabs
* @return array Array of tabs to show
*/
function productAttributePrepareHead($object)
{
global $langs, $conf;
$langs->load("products");
$h = 0;
$head = array();
$head[$h][0] = DOL_URL_ROOT.'/variants/card.php?id='.$object->id;
$head[$h][1] = $langs->trans("ProductAttribute");
$head[$h][2] = 'card';
$h++;
// Show more tabs from modules
// Entries must be declared in modules descriptor with line
// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__'); to add new tab
// $this->tabs = array('entity:-tabname); to remove a tab
complete_head_from_modules($conf, $langs, $object, $head, $h, 'product_attribute');
complete_head_from_modules($conf, $langs, $object, $head, $h, 'product_attribute', 'remove');
return $head;
}

View File

@ -1,5 +1,6 @@
<?php
/* Copyright (C) 2016 Marcos García <marcosgdf@gmail.com>
* Copyright (C) 2022 Open-Dsi <support@open-dsi.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -15,47 +16,195 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* \file htdocs/variants/list.php
* \ingroup variants
* \brief List page for product attribute
*/
require '../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php';
$action = GETPOST('action', 'aZ09');
// Load translation files required by the page
$langs->loadLangs(array("products", "other"));
$action = GETPOST('action', 'aZ09') ?GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ...
$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
$show_files = GETPOST('show_files', 'int'); // Show files area generated by bulk actions ?
$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation
$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button
$toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list
$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'productattributelist'; // To manage different context of search
$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
$id = GETPOST('id', 'int');
// Load variable for pagination
$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit;
$sortfield = GETPOST('sortfield', 'aZ09comma');
$sortorder = GETPOST('sortorder', 'aZ09comma');
$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
// If $page is not defined, or '' or -1 or if we click on clear filters
$page = 0;
}
$offset = $limit * $page;
$pageprev = $page - 1;
$pagenext = $page + 1;
// Initialize technical objects
$object = new ProductAttribute($db);
$rowid = GETPOST('rowid', 'int'); // Id of line for up / down when no javascript available
//$extrafields = new ExtraFields($db);
$diroutputmassaction = $conf->variants->dir_output.'/temp/massgeneration/'.$user->id;
$hookmanager->initHooks(array('productattributelist')); // Note that conf->hooks_modules contains array
// Fetch optionals attributes and labels
//$extrafields->fetch_name_optionals_label($object->table_element);
//$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
// Default sort order (if not yet defined by previous GETPOST)
if (!$sortfield) {
$sortfield = "t.position"; // Set here default search field. By default 1st field in definition.
}
if (!$sortorder) {
$sortorder = "ASC";
}
// Initialize array of search criterias
$search_all = GETPOST('search_all', 'alphanohtml') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml');
$search = array();
foreach ($object->fields as $key => $val) {
if (GETPOST('search_'.$key, 'alpha') !== '') {
$search[$key] = GETPOST('search_'.$key, 'alpha');
}
if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
$search[$key.'_dtstart'] = dol_mktime(0, 0, 0, GETPOST('search_'.$key.'_dtstartmonth', 'int'), GETPOST('search_'.$key.'_dtstartday', 'int'), GETPOST('search_'.$key.'_dtstartyear', 'int'));
$search[$key.'_dtend'] = dol_mktime(23, 59, 59, GETPOST('search_'.$key.'_dtendmonth', 'int'), GETPOST('search_'.$key.'_dtendday', 'int'), GETPOST('search_'.$key.'_dtendyear', 'int'));
}
}
$search['nb_of_values'] = GETPOST('search_nb_of_values', 'alpha');
$search['nb_products'] = GETPOST('search_nb_products', 'alpha');
// List of fields to search into when doing a "search in all"
$fieldstosearchall = array();
foreach ($object->fields as $key => $val) {
if (!empty($val['searchall'])) {
$fieldstosearchall['t.'.$key] = $val['label'];
}
}
// Definition of array of fields for columns
$arrayfields = array();
foreach ($object->fields as $key => $val) {
// If $val['visible']==0, then we never show the field
if (!empty($val['visible'])) {
$visible = (int) dol_eval($val['visible'], 1);
$arrayfields['t.'.$key] = array(
'label'=>$val['label'],
'checked'=>(($visible < 0) ? 0 : 1),
'enabled'=>($visible != 3 && dol_eval($val['enabled'], 1)),
'position'=>$val['position'],
'help'=> isset($val['help']) ? $val['help'] : ''
);
}
}
$arrayfields['nb_of_values'] = array(
'label' => $langs->trans('NbOfDifferentValues'),
'checked' => 1,
'enabled' => 1,
'position' => 40,
'help' => ''
);
$arrayfields['nb_products'] = array(
'label' => $langs->trans('NbProducts'),
'checked' => 1,
'enabled' => 1,
'position' => 50,
'help' => ''
);
// Extra fields
//include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php';
$object->fields = dol_sort_array($object->fields, 'position');
$arrayfields = dol_sort_array($arrayfields, 'position');
$permissiontoread = $user->rights->produit->lire || $user->rights->service->lire;
$permissiontoadd = $user->rights->produit->creer || $user->rights->service->creer;
$permissiontoadd = $user->rights->produit->lire || $user->rights->service->lire;
$permissiontodelete = $user->rights->produit->lire || $user->rights->service->lire;
// Security check
if (empty($conf->variants->enabled)) {
accessforbidden('Module not enabled');
}
$socid = 0;
if ($user->socid > 0) { // Protection if external user
//$socid = $user->socid;
accessforbidden();
}
//$result = restrictedArea($user, 'variant');
if (!$permissiontoread) accessforbidden();
/*
* Actions
*/
if ($action == 'up' && $permissiontoadd) {
$object->fetch($rowid);
$object->moveUp();
if (GETPOST('cancel', 'alpha')) {
$action = 'list';
$massaction = '';
}
if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
$massaction = '';
}
header('Location: '.$_SERVER['PHP_SELF']);
exit();
} elseif ($action == 'down' && $permissiontoadd) {
$object->fetch($rowid);
$object->moveDown();
$parameters = array();
$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
if ($reshook < 0) {
setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
}
header('Location: '.$_SERVER['PHP_SELF']);
exit();
if (empty($reshook)) {
// Selection of new fields
include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
// Purge search criteria
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
foreach ($object->fields as $key => $val) {
$search[$key] = '';
if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
$search[$key.'_dtstart'] = '';
$search[$key.'_dtend'] = '';
}
}
$search['nb_of_values'] = '';
$search['nb_products'] = '';
$toselect = array();
$search_array_options = array();
}
if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
|| GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) {
$massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
}
if ($action == 'up' && $permissiontoadd) {
$object->attributeMoveUp($rowid);
header('Location: '.$_SERVER['PHP_SELF']);
exit();
} elseif ($action == 'down' && $permissiontoadd) {
$object->attributeMoveDown($rowid);
header('Location: '.$_SERVER['PHP_SELF']);
exit();
}
// Mass actions
$objectclass = 'ProductAttribute';
$objectlabel = 'ProductAttribute';
$uploaddir = $conf->variants->dir_output;
include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php';
}
@ -64,22 +213,540 @@ if ($action == 'up' && $permissiontoadd) {
* View
*/
$langs->load('products');
$form = new Form($db);
$title = $langs->trans($langs->trans('ProductAttributes'));
$now = dol_now();
$variants = $object->fetchAll();
$help_url = '';
$title = $langs->trans('ListOf', $langs->transnoentitiesnoconv("ProductAttributes"));
$morejs = array();
$morecss = array();
llxHeader('', $title);
$newcardbutton = '';
if ($user->rights->produit->creer) {
$newcardbutton .= dolGetButtonTitle($langs->trans('Create'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/variants/create.php');
// Build and execute select
// --------------------------------------------------------------------
$sql = "SELECT ";
$sql .= " COUNT(DISTINCT pav.rowid) AS nb_of_values, COUNT(DISTINCT pac2v.fk_prod_combination) AS nb_products,";
$sql .= $object->getFieldList("t");
// Add fields from extrafields
//if (!empty($extrafields->attributes[$object->table_element]['label'])) {
// foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
// $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key." as options_".$key.", " : "");
// }
//}
// Add fields from hooks
$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object); // Note that $action and $object may have been modified by hook
$sql .= preg_replace('/^,/', '', $hookmanager->resPrint);
$sql = preg_replace('/,\s*$/', '', $sql);
$sql .= " FROM ".MAIN_DB_PREFIX.$object->table_element." as t";
//if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) {
// $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)";
//}
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination2val AS pac2v ON pac2v.fk_prod_attr = t.rowid";
$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_value AS pav ON pav.fk_product_attribute = t.rowid";
// Add table from hooks
$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object); // Note that $action and $object may have been modified by hook
$sql .= $hookmanager->resPrint;
if ($object->ismultientitymanaged == 1) {
$sql .= " WHERE t.entity IN (".getEntity($object->element).")";
} else {
$sql .= " WHERE 1 = 1";
}
foreach ($search as $key => $val) {
if (preg_match('/(_dtstart|_dtend)$/', $key) && $search[$key] != '') {
$columnName = preg_replace('/(_dtstart|_dtend)$/', '', $key);
if (preg_match('/^(date|timestamp|datetime)/', $object->fields[$columnName]['type'])) {
if (preg_match('/_dtstart$/', $key)) {
$sql .= " AND t.".$columnName." >= '".$db->idate($search[$key])."'";
}
if (preg_match('/_dtend$/', $key)) {
$sql .= " AND t." . $columnName . " <= '" . $db->idate($search[$key]) . "'";
}
}
} elseif (array_key_exists($key, $object->fields)) {
if ($key == 'status' && $search[$key] == -1) {
continue;
}
$mode_search = (($object->isInt($object->fields[$key]) || $object->isFloat($object->fields[$key])) ? 1 : 0);
if ((strpos($object->fields[$key]['type'], 'integer:') === 0) || (strpos($object->fields[$key]['type'], 'sellist:') === 0) || !empty($object->fields[$key]['arrayofkeyval'])) {
if ($search[$key] == '-1' || ($search[$key] === '0' && (empty($object->fields[$key]['arrayofkeyval']) || !array_key_exists('0', $object->fields[$key]['arrayofkeyval'])))) {
$search[$key] = '';
}
$mode_search = 2;
}
if ($search[$key] != '') {
$sql .= natural_search("t.".$key, $search[$key], (($key == 'status') ? 2 : $mode_search));
}
}
}
if ($search_all) {
$sql .= natural_search(array_keys($fieldstosearchall), $search_all);
}
//$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear);
// Add where from extra fields
//include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php';
// Add where from hooks
$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object); // Note that $action and $object may have been modified by hook
$sql .= $hookmanager->resPrint;
$hasgroupby = true;
$sql .= " GROUP BY ";
foreach ($object->fields as $key => $val) {
$sql .= "t." . $key . ", ";
}
// Add fields from extrafields
//if (!empty($extrafields->attributes[$object->table_element]['label'])) {
// foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) {
// $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.', ' : '');
// }
//}
// Add where from hooks
$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListGroupBy', $parameters, $object); // Note that $action and $object may have been modified by hook
$sql .= $hookmanager->resPrint;
$sql = preg_replace("/,\s*$/", "", $sql);
$sql .= " HAVING 1=1";
if ($search['nb_of_values'] != '') {
$sql .= natural_search("nb_of_values", $search['nb_of_values'], 1);
}
if ($search['nb_products'] != '') {
$sql .= natural_search("nb_products", $search['nb_products'], 1);
}
// Add HAVING from hooks
$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListHaving', $parameters, $object); // Note that $action and $object may have been modified by hook
$sql .= empty($hookmanager->resPrint) ? "" : " ".$hookmanager->resPrint;
// Count total nb of records
$nbtotalofrecords = '';
if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
/* This old and fast method to get and count full list returns all record so use a high amount of memory.
$resql = $db->query($sql);
$nbtotalofrecords = $db->num_rows($resql);
*/
/* The slow method does not consume memory on mysql (not tested on pgsql) */
/*$resql = $db->query($sql, 0, 'auto', 1);
while ($db->fetch_object($resql)) {
$nbtotalofrecords++;
}*/
/* The fast and low memory method to get and count full list converts the sql into a sql count */
$sqlforcount = preg_replace("/^SELECT[a-z0-9\._\s\(\),]+FROM/i", "SELECT COUNT(*) as nbtotalofrecords FROM", $sql);
$resql = $db->query($sqlforcount);
if ($resql) {
if ($hasgroupby) {
$nbtotalofrecords = $db->num_rows($resql);
} else {
$objforcount = $db->fetch_object($resql);
$nbtotalofrecords = $objforcount->nbtotalofrecords;
}
if (($page * $limit) > $nbtotalofrecords) { // if total of record found is smaller than page * limit, goto and load page 0
$page = 0;
$offset = 0;
}
$db->free($resql);
}
}
print load_fiche_titre($title, $newcardbutton, 'product');
// Complete request and execute it with limit
$sql .= $db->order($sortfield, $sortorder);
if ($limit) {
$sql .= $db->plimit($limit + 1, $offset);
}
$resql = $db->query($sql);
if (!$resql) {
dol_print_error($db);
exit;
}
$num = $db->num_rows($resql);
// Direct jump if only one record found
if ($num == 1 && !empty($conf->global->MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE) && $search_all && !$page) {
$obj = $db->fetch_object($resql);
$id = $obj->rowid;
header("Location: " . dol_buildpath('/variants/card.php', 2) . '?id=' . $id);
exit;
}
// Output page
// --------------------------------------------------------------------
llxHeader('', $title, $help_url, '', 0, 0, $morejs, $morecss, '', '');
$arrayofselected = is_array($toselect) ? $toselect : array();
$param = '';
if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
$param .= '&contextpage='.urlencode($contextpage);
}
if ($limit > 0 && $limit != $conf->liste_limit) {
$param .= '&limit='.urlencode($limit);
}
foreach ($search as $key => $val) {
if (is_array($search[$key]) && count($search[$key])) {
foreach ($search[$key] as $skey) {
if ($skey != '') {
$param .= '&search_'.$key.'[]='.urlencode($skey);
}
}
} elseif ($search[$key] != '') {
$param .= '&search_'.$key.'='.urlencode($search[$key]);
}
}
if ($optioncss != '') {
$param .= '&optioncss='.urlencode($optioncss);
}
// Add $param from extra fields
//include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php';
// Add $param from hooks
$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldListSearchParam', $parameters, $object); // Note that $action and $object may have been modified by hook
$param .= $hookmanager->resPrint;
// List of mass actions available
$arrayofmassactions = array(
//'validate'=>img_picto('', 'check', 'class="pictofixedwidth"').$langs->trans("Validate"),
//'generate_doc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("ReGeneratePDF"),
//'builddoc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("PDFMerge"),
//'presend'=>img_picto('', 'email', 'class="pictofixedwidth"').$langs->trans("SendByMail"),
);
if ($permissiontodelete) {
$arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete");
}
if (GETPOST('nomassaction', 'int') || in_array($massaction, array('presend', 'predelete'))) {
$arrayofmassactions = array();
}
$massactionbutton = $form->selectMassAction('', $arrayofmassactions);
print '<form method="POST" id="searchFormList" action="'.$_SERVER["PHP_SELF"].'">'."\n";
if ($optioncss != '') {
print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
}
print '<input type="hidden" name="token" value="'.newToken().'">';
print '<input type="hidden" name="formfilteraction" id="formfilteraction" value="list">';
print '<input type="hidden" name="action" value="list">';
print '<input type="hidden" name="sortfield" value="'.$sortfield.'">';
print '<input type="hidden" name="sortorder" value="'.$sortorder.'">';
print '<input type="hidden" name="page" value="'.$page.'">';
print '<input type="hidden" name="contextpage" value="'.$contextpage.'">';
$newcardbutton = dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', DOL_URL_ROOT.'/variants/card.php?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']), '', $permissiontoadd);
print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'object_'.$object->picto, 0, $newcardbutton, '', $limit, 0, 0, 1);
// Add code for pre mass action (confirmation or email presend form)
$topicmail = "SendProductAttributeRef";
$modelmail = "productattribute";
$objecttmp = new ProductAttribute($db);
$trackid = 'pa'.$object->id;
include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php';
if ($search_all) {
foreach ($fieldstosearchall as $key => $val) {
$fieldstosearchall[$key] = $langs->trans($val);
}
print '<div class="divsearchfieldfilter">'.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'</div>';
}
$moreforfilter = '';
/*$moreforfilter.='<div class="divsearchfield">';
$moreforfilter.= $langs->trans('MyFilter') . ': <input type="text" name="search_myfield" value="'.dol_escape_htmltag($search_myfield).'">';
$moreforfilter.= '</div>';*/
$parameters = array();
$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
if (empty($reshook)) {
$moreforfilter .= $hookmanager->resPrint;
} else {
$moreforfilter = $hookmanager->resPrint;
}
if (!empty($moreforfilter)) {
print '<div class="liste_titre liste_titre_bydiv centpercent">';
print $moreforfilter;
print '</div>';
}
$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage;
$selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields
$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : '');
print '<div class="div-table-responsive">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
print '<table id="tableattributes" class="tagtable nobottomiftotal liste'.($moreforfilter ? " listwithfilterbefore" : "").'">'."\n";
// Fields title search
// --------------------------------------------------------------------
print '<tr class="liste_titre">';
foreach ($object->fields as $key => $val) {
$cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']);
if ($key == 'status') {
$cssforfield .= ($cssforfield ? ' ' : '').'center';
} elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
$cssforfield .= ($cssforfield ? ' ' : '').'center';
} elseif (in_array($val['type'], array('timestamp'))) {
$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) {
$cssforfield .= ($cssforfield ? ' ' : '').'right';
}
if (!empty($arrayfields['t.'.$key]['checked'])) {
print '<td class="liste_titre'.($cssforfield ? ' '.$cssforfield : '').'">';
if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
print $form->selectarray('search_'.$key, $val['arrayofkeyval'], (isset($search[$key]) ? $search[$key] : ''), $val['notnull'], 0, 0, '', 1, 0, 0, '', 'maxwidth100', 1);
} elseif ((strpos($val['type'], 'integer:') === 0) || (strpos($val['type'], 'sellist:') === 0)) {
print $object->showInputField($val, $key, (isset($search[$key]) ? $search[$key] : ''), '', '', 'search_', 'maxwidth125', 1);
} elseif (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
print '<div class="nowrap">';
print $form->selectDate($search[$key.'_dtstart'] ? $search[$key.'_dtstart'] : '', "search_".$key."_dtstart", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From'));
print '</div>';
print '<div class="nowrap">';
print $form->selectDate($search[$key.'_dtend'] ? $search[$key.'_dtend'] : '', "search_".$key."_dtend", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to'));
print '</div>';
} elseif ($key == 'lang') {
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
$formadmin = new FormAdmin($db);
print $formadmin->select_language($search[$key], 'search_lang', 0, null, 1, 0, 0, 'minwidth150 maxwidth200', 2);
} else {
print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag(isset($search[$key]) ? $search[$key] : '').'">';
}
print '</td>';
}
}
// Extra fields
//include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php';
$key = 'nb_of_values';
if (!empty($arrayfields[$key]['checked'])) {
print '<td class="liste_titre center">';
print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag(isset($search[$key]) ? $search[$key] : '').'">';
print '</td>';
}
$key = 'nb_products';
if (!empty($arrayfields[$key]['checked'])) {
print '<td class="liste_titre center">';
print '<input type="text" class="flat maxwidth75" name="search_'.$key.'" value="'.dol_escape_htmltag(isset($search[$key]) ? $search[$key] : '').'">';
print '</td>';
}
// Fields from hook
$parameters = array('arrayfields'=>$arrayfields);
$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
// Action column
print '<td class="liste_titre linecoledit width25"></td>';
print '<td class="liste_titre maxwidthsearch">';
$searchpicto = $form->showFilterButtons();
print $searchpicto;
print '</td>';
print '<td class="liste_titre linecolmove width25"></td>';
print '</tr>'."\n";
// Fields title label
// --------------------------------------------------------------------
print '<tr class="liste_titre">';
foreach ($object->fields as $key => $val) {
$cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']);
if ($key == 'status') {
$cssforfield .= ($cssforfield ? ' ' : '').'center';
} elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
$cssforfield .= ($cssforfield ? ' ' : '').'center';
} elseif (in_array($val['type'], array('timestamp'))) {
$cssforfield .= ($cssforfield ? ' ' : '').'nowrap';
} elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) {
$cssforfield .= ($cssforfield ? ' ' : '').'right';
}
if (!empty($arrayfields['t.'.$key]['checked'])) {
print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''))."\n";
}
}
// Extra fields
//include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php';
$key = 'nb_of_values';
if (!empty($arrayfields[$key]['checked'])) {
print getTitleFieldOfList($arrayfields[$key]['label'], 0, $_SERVER['PHP_SELF'], $key, '', $param, 'class="center"', $sortfield, $sortorder, 'center ')."\n";
}
$key = 'nb_products';
if (!empty($arrayfields[$key]['checked'])) {
print getTitleFieldOfList($arrayfields[$key]['label'], 0, $_SERVER['PHP_SELF'], $key, '', $param, 'class="center"', $sortfield, $sortorder, 'center ')."\n";
}
// Hook fields
$parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder);
$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
// Action column
print getTitleFieldOfList('', 0, '', '', '', '', '', '', '', 'linecoledit ')."\n";
print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n";
print getTitleFieldOfList('', 0, '', '', '', '', '', '', '', 'linecolmove ')."\n";
print '</tr>'."\n";
// Detect if we need a fetch on each output line
$needToFetchEachLine = 0;
//if (isset($extrafields->attributes[$object->table_element]['computed']) && is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) {
// foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) {
// if (preg_match('/\$object/', $val)) {
// $needToFetchEachLine++; // There is at least one compute field that use $object
// }
// }
//}
// Loop on record
// --------------------------------------------------------------------
$i = 0;
$totalarray = array();
$totalarray['nbfield'] = 0;
while ($i < ($limit ? min($num, $limit) : $num)) {
$obj = $db->fetch_object($resql);
if (empty($obj)) {
break; // Should not happen
}
$object->setVarsFromFetchObj($obj);
// Show here line of result
print '<tr id="row-' . $obj->rowid . '" class="oddeven drag drop">';
foreach ($object->fields as $key => $val) {
$cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']);
if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) {
$cssforfield .= ($cssforfield ? ' ' : '') . 'center';
} elseif ($key == 'status') {
$cssforfield .= ($cssforfield ? ' ' : '') . 'center';
}
if (in_array($val['type'], array('timestamp'))) {
$cssforfield .= ($cssforfield ? ' ' : '') . 'nowrap';
} elseif ($key == 'ref') {
$cssforfield .= ($cssforfield ? ' ' : '') . 'nowrap';
}
if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('rowid', 'status')) && empty($val['arrayofkeyval'])) {
$cssforfield .= ($cssforfield ? ' ' : '') . 'right';
}
//if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100';
if (!empty($arrayfields['t.' . $key]['checked'])) {
print '<td' . ($cssforfield ? ' class="' . $cssforfield . '"' : '') . '>';
if ($key == 'status') {
print $object->getLibStatut(5);
} elseif ($key == 'rowid') {
print $object->showOutputField($val, $key, $object->id, '');
} else {
print $object->showOutputField($val, $key, $object->$key, '');
}
print '</td>';
if (!$i) {
$totalarray['nbfield']++;
}
if (!empty($val['isameasure']) && $val['isameasure'] == 1) {
if (!$i) {
$totalarray['pos'][$totalarray['nbfield']] = 't.' . $key;
}
if (!isset($totalarray['val'])) {
$totalarray['val'] = array();
}
if (!isset($totalarray['val']['t.' . $key])) {
$totalarray['val']['t.' . $key] = 0;
}
$totalarray['val']['t.' . $key] += $object->$key;
}
}
}
// Extra fields
//include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php';
$key = 'nb_of_values';
if (!empty($arrayfields[$key]['checked'])) {
print '<td class="center">';
print $obj->$key;
print '</td>';
if (!$i) {
$totalarray['nbfield']++;
}
}
$key = 'nb_products';
if (!empty($arrayfields[$key]['checked'])) {
print '<td class="center">';
print $obj->$key;
print '</td>';
if (!$i) {
$totalarray['nbfield']++;
}
}
// Fields from hook
$parameters = array('arrayfields' => $arrayfields, 'object' => $object, 'obj' => $obj, 'i' => $i, 'totalarray' => &$totalarray);
$reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
// Action column
print '<td class="linecoledit center width25">';
if ($permissiontoadd) {
print '<a class="editfielda reposition" href="' . DOL_URL_ROOT . '/variants/card.php?id=' . $obj->rowid . '&action=edit&save_lastsearch_values=1&backtopage=' . urlencode($_SERVER['PHP_SELF']) . '">' . img_edit() . '</a>';
}
print '</td>';
if (!$i) {
$totalarray['nbfield']++;
}
print '<td class="nowrap center">';
if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
$selected = 0;
if (in_array($object->id, $arrayofselected)) {
$selected = 1;
}
print '<input id="cb' . $object->id . '" class="flat checkforselect" type="checkbox" name="toselect[]" value="' . $object->id . '"' . ($selected ? ' checked="checked"' : '') . '>';
}
print '</td>';
if (!$i) {
$totalarray['nbfield']++;
}
print '<td class="center linecolmove tdlineupdown">';
if ($i > 0) {
print '<a class="lineupdown" href="' . $_SERVER['PHP_SELF'] . '?action=up&amp;rowid=' . $obj->rowid . '">' . img_up('default', 0, 'imgupforline') . '</a>';
}
if ($i < $num - 1) {
print '<a class="lineupdown" href="' . $_SERVER['PHP_SELF'] . '?action=down&amp;rowid=' . $obj->rowid . '">' . img_down('default', 0, 'imgdownforline') . '</a>';
}
print '</td>';
if (!$i) {
$totalarray['nbfield']++;
}
print '</tr>' . "\n";
$i++;
}
// Show total line
include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php';
// If no record found
if ($num == 0) {
$colspan = 3;
foreach ($arrayfields as $key => $val) {
if (!empty($val['checked'])) {
$colspan++;
}
}
print '<tr><td colspan="'.$colspan.'"><span class="opacitymedium">'.$langs->trans("NoRecordFound").'</span></td></tr>';
}
$db->free($resql);
$parameters = array('arrayfields'=>$arrayfields, 'sql'=>$sql);
$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object); // Note that $action and $object may have been modified by hook
print $hookmanager->resPrint;
print '</table>'."\n";
print '</div>'."\n";
print '</form>'."\n";
$forcereloadpage = empty($conf->global->MAIN_FORCE_RELOAD_PAGE) ? 0 : 1;
$tagidfortablednd = (empty($tagidfortablednd) ? 'tableattributes' : $tagidfortablednd);
?>
<script>
$(document).ready(function(){
@ -97,11 +764,13 @@ $forcereloadpage = empty($conf->global->MAIN_FORCE_RELOAD_PAGE) ? 0 : 1;
}
);
$("#tablelines").tableDnD({
$("#<?php echo $tagidfortablednd; ?>").tableDnD({
onDrop: function(table, row) {
console.log('drop');
$('#<?php echo $tagidfortablednd; ?> tr[data-element=extrafield]').attr('id', ''); // Set extrafields id to empty value in order to ignore them in tableDnDSerialize function
$('#<?php echo $tagidfortablednd; ?> tr[data-ignoreidfordnd=1]').attr('id', ''); // Set id to empty value in order to ignore them in tableDnDSerialize function
var reloadpage = "<?php echo $forcereloadpage; ?>";
var roworder = cleanSerialize(decodeURI($("#tablelines").tableDnDSerialize()));
var roworder = cleanSerialize(decodeURI($("#<?php echo $tagidfortablednd; ?>").tableDnDSerialize()));
$.post("<?php echo DOL_URL_ROOT; ?>/variants/ajax/orderAttribute.php",
{
roworder: roworder,
@ -110,13 +779,6 @@ $forcereloadpage = empty($conf->global->MAIN_FORCE_RELOAD_PAGE) ? 0 : 1;
function() {
if (reloadpage == 1) {
location.href = '<?php echo dol_escape_htmltag($_SERVER['PHP_SELF']).'?'.dol_escape_htmltag($_SERVER['QUERY_STRING']); ?>';
} else {
$("#tablelines .drag").each(
function( intIndex ) {
$(this).removeClass("pair impair");
if (intIndex % 2 == 0) $(this).addClass('impair');
if (intIndex % 2 == 1) $(this).addClass('pair');
});
}
});
},
@ -125,38 +787,27 @@ $forcereloadpage = empty($conf->global->MAIN_FORCE_RELOAD_PAGE) ? 0 : 1;
});
});
</script>
<table class="liste nobottom" id="tablelines">
<tr class="liste_titre nodrag nodrop">
<th class="liste_titre"><?php print $langs->trans('Ref') ?></th>
<th class="liste_titre"><?php print $langs->trans('Label') ?></th>
<th class="liste_titre right"><?php print $langs->trans('NbOfDifferentValues') ?></th>
<th class="liste_titre right"><?php print $langs->trans('NbProducts') ?></th>
<th class="liste_titre" colspan="2"></th>
</tr>
<?php
foreach ($variants as $key => $attribute) {
print '<tr id="row-'.$attribute->id.'" class="drag drop oddeven">';
print '<td><a href="card.php?id='.$attribute->id.'">'.dol_htmlentities($attribute->ref).'</a></td>';
print '<td><a href="card.php?id='.$attribute->id.'">'.dol_htmlentities($attribute->label).'</a></td>';
print '<td class="right">'.$attribute->countChildValues().'</td>';
print '<td class="right">'.$attribute->countChildProducts().'</td>';
print '<td class="right">';
print '<a class="editfielda marginrightonly paddingleftonly" href="card.php?id='.$attribute->id.'&action=edit&token='.newToken().'">'.img_edit().'</a>';
print '<a class="marginrightonly paddingleftonlyhref="card.php?id='.$attribute->id.'&action=delete&token='.newToken().'">'.img_delete().'</a>';
print '</td>';
print '<td class="center linecolmove tdlineupdown">';
if ($key > 0) {
print '<a class="lineupdown" href="'.$_SERVER['PHP_SELF'].'?action=up&amp;rowid='.$attribute->id.'">'.img_up('default', 0, 'imgupforline').'</a>';
}
if ($key < count($variants) - 1) {
print '<a class="lineupdown" href="'.$_SERVER['PHP_SELF'].'?action=down&amp;rowid='.$attribute->id.'">'.img_down('default', 0, 'imgdownforline').'</a>';
}
print '</td>';
print "</tr>\n";
}
print '</table>';
if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
$hidegeneratedfilelistifempty = 1;
if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
$hidegeneratedfilelistifempty = 0;
}
require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
$formfile = new FormFile($db);
// Show list of available documents
$urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder;
$urlsource .= str_replace('&amp;', '&', $param);
$filedir = $diroutputmassaction;
$genallowed = $permissiontoread;
$delallowed = $permissiontoadd;
print $formfile->showdocuments('massfilesarea_productattribute', '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty);
}
// End of page
llxFooter();

View File

@ -0,0 +1,3 @@
README (english)
This directory is used for storing the common default templates of the system core. (outside any modules)

View File

@ -0,0 +1,91 @@
<?php
/* Copyright (C) 2022 Open-Dsi <support@open-dsi.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* Need to have following variables defined:
* $object (invoice, order, ...)
* $conf
* $langs
* $dateSelector
* $forceall (0 by default, 1 for supplier invoices/orders)
* $senderissupplier (0 by default, 1 or 2 for supplier invoices/orders)
* $inputalsopricewithtax (0 by default, 1 to also show column with unit price including tax)
*/
// Protection to avoid direct call of template
if (empty($object) || !is_object($object)) {
print "Error: this template page cannot be called directly as an URL";
exit;
}
global $forcetoshowtitlelines;
// Define colspan for the button 'Add'
$colspan = 3; // Columns: col edit + col delete + move button
// Lines for extrafield
$objectline = null;
print "<!-- BEGIN PHP TEMPLATE productattributevalueline_create.tpl.php -->\n";
$nolinesbefore = (count($this->lines) == 0 || $forcetoshowtitlelines);
if ($nolinesbefore) {
?>
<tr class="liste_titre<?php echo ($nolinesbefore ? '' : ' liste_titre_add_') ?> nodrag nodrop">
<?php if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { ?>
<td class="linecolnum center"></td>
<?php } ?>
<td class="linecolref">
<div id="add"></div><span class="hideonsmartphone"><?php echo $langs->trans('AddNewLine'); ?></span>
</td>
<td class="linecolvalue"><span id="title_vat"><?php echo $langs->trans('Value'); ?></span></td>
<td class="linecoledit" colspan="<?php echo $colspan; ?>">&nbsp;</td>
</tr>
<?php
}
?>
<tr class="pair nodrag nodrop nohoverpair<?php echo $nolinesbefore ? '' : ' liste_titre_create'; ?>">
<?php
$coldisplay = 0;
// Adds a line numbering column
if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) {
$coldisplay++;
echo '<td class="nobottom linecolnum center"></td>';
}
$coldisplay++;
?>
<td class="nobottom linecolref">
<?php $coldisplay++; if ($nolinesbefore) { echo $langs->trans('Ref') . ': '; } ?>
<input type="text" name="line_ref" id="line_ref" class="flat" value="<?php echo (GETPOSTISSET("line_ref") ? GETPOST("line_ref", 'alpha', 2) : ''); ?>" autofocus>
<?php
if (is_object($hookmanager)) {
$parameters = array();
$reshook = $hookmanager->executeHooks('formCreateValueOptions', $parameters, $object, $action);
if (!empty($hookmanager->resPrint)) {
print $hookmanager->resPrint;
}
}
?>
</td>
<td class="nobottom linecolvalue"><?php $coldisplay++; ?>
<input type="text" name="line_value" id="line_value" class="flat" value="<?php echo (GETPOSTISSET("line_value") ? GETPOST("line_value", 'alpha', 2) : ''); ?>">
</td>
<td class="nobottom linecoledit center valignmiddle" colspan="<?php echo $colspan; ?>"><?php $coldisplay += $colspan; ?>
<input type="submit" class="button reposition" value="<?php echo $langs->trans('Add'); ?>" name="addline" id="addline">
</td>
</tr>
<!-- END PHP TEMPLATE productattributevalueline_create.tpl.php -->

View File

@ -0,0 +1,77 @@
<?php
/* Copyright (C) 2022 Open-Dsi <support@open-dsi.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* Need to have following variables defined:
* $object (invoice, order, ...)
* $conf
* $langs
* $seller, $buyer
* $dateSelector
* $forceall (0 by default, 1 for supplier invoices/orders)
* $senderissupplier (0 by default, 1 for supplier invoices/orders)
* $inputalsopricewithtax (0 by default, 1 to also show column with unit price including tax)
* $canchangeproduct (0 by default, 1 to allow to change the product if it is a predefined product)
*/
// Protection to avoid direct call of template
if (empty($object) || !is_object($object)) {
print "Error, template page can't be called as URL";
exit;
}
// Define colspan for the button 'Add'
$colspan = 3; // Column: col edit + col delete + move button
print "<!-- BEGIN PHP TEMPLATE productattributevalueline_edit.tpl.php -->\n";
$coldisplay = 0;
?>
<tr class="oddeven tredited">
<?php if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { ?>
<td class="linecolnum center"><?php $coldisplay++; ?><?php echo ($i + 1); ?></td>
<?php }
$coldisplay++;
?>
<td class="nobottom linecolref">
<div id="line_<?php echo $line->id; ?>"></div>
<input type="hidden" name="lineid" value="<?php echo $line->id; ?>">
<?php $coldisplay++; ?>
<input type="text" name="line_ref" id="line_ref" class="flat" value="<?php echo (GETPOSTISSET("line_ref") ? GETPOST("line_ref", 'alpha', 2) : $line->ref); ?>">
<?php
if (is_object($hookmanager)) {
$parameters = array('line'=>$line);
$reshook = $hookmanager->executeHooks('formEditProductOptions', $parameters, $object, $action);
if (!empty($hookmanager->resPrint)) {
print $hookmanager->resPrint;
}
}
?>
</td>
<td class="nobottom linecolvalue"><?php $coldisplay++; ?>
<input type="text" name="line_value" id="line_value" class="flat" value="<?php echo (GETPOSTISSET("line_value") ? GETPOST("line_value", 'alpha', 2) : $line->value); ?>">
</td>
<!-- colspan for this td because it replace td for buttons+... -->
<td class="center valignmiddle" colspan="<?php echo $colspan; ?>"><?php $coldisplay += $colspan; ?>
<input type="submit" class="button buttongen marginbottomonly button-save" id="savelinebutton marginbottomonly" name="save" value="<?php echo $langs->trans("Save"); ?>"><br>
<input type="submit" class="button buttongen marginbottomonly button-cancel" id="cancellinebutton" name="cancel" value="<?php echo $langs->trans("Cancel"); ?>">
</td>
</tr>
<!-- END PHP TEMPLATE productattributevalueline_edit.tpl.php -->

View File

@ -0,0 +1,70 @@
<?php
/* Copyright (C) 2022 Open-Dsi <support@open-dsi.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* Need to have following variables defined:
* $object (invoice, order, ...)
* $conf
* $langs
* $element (used to test $user->rights->$element->creer)
* $permtoedit (used to replace test $user->rights->$element->creer)
* $inputalsopricewithtax (0 by default, 1 to also show column with unit price including tax)
* $outputalsopricetotalwithtax
* $usemargins (0 to disable all margins columns, 1 to show according to margin setup)
*
* $type, $text, $description, $line
*/
// Protection to avoid direct call of template
if (empty($object) || !is_object($object)) {
print "Error, template page can't be called as URL";
exit;
}
print "<!-- BEGIN PHP TEMPLATE productattributevalueline_title.tpl.php -->\n";
// Title line
print "<thead>\n";
print '<tr class="liste_titre nodrag nodrop">';
// Adds a line numbering column
if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) {
print '<td class="linecolnum center">&nbsp;</td>';
}
// Ref
print '<td class="linecolref">'.$langs->trans('Ref').'</td>';
// Value
print '<td class="linecolvalue">'.$langs->trans('Value').'</td>';
print '<td class="linecoledit"></td>'; // No width to allow autodim
print '<td class="linecoldelete" style="width: 10px"></td>';
print '<td class="linecolmove" style="width: 10px"></td>';
if ($action == 'selectlines') {
print '<td class="linecolcheckall center">';
print '<input type="checkbox" class="linecheckboxtoggle" />';
print '<script>$(document).ready(function() {$(".linecheckboxtoggle").click(function() {var checkBoxes = $(".linecheckbox");checkBoxes.prop("checked", this.checked);})});</script>';
print '</td>';
}
print "</tr>\n";
print "</thead>\n";
print "<!-- END PHP TEMPLATE productattributevalueline_title.tpl.php -->\n";

View File

@ -0,0 +1,105 @@
<?php
/* Copyright (C) 2022 Open-Dsi <support@open-dsi.fr>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* Need to have following variables defined:
* $object (invoice, order, ...)
* $conf
* $langs
* $dateSelector
* $forceall (0 by default, 1 for supplier invoices/orders)
* $element (used to test $user->rights->$element->creer)
* $permtoedit (used to replace test $user->rights->$element->creer)
* $senderissupplier (0 by default, 1 for supplier invoices/orders)
* $inputalsopricewithtax (0 by default, 1 to also show column with unit price including tax)
* $outputalsopricetotalwithtax
* $usemargins (0 to disable all margins columns, 1 to show according to margin setup)
* $object_rights->creer initialized from = $object->getRights()
* $disableedit, $disablemove, $disableremove
*
* $text, $description, $line
*/
// Protection to avoid direct call of template
if (empty($object) || !is_object($object)) {
print "Error, template page can't be called as URL";
exit;
}
// add html5 elements
$domData = ' data-element="'.$line->element.'"';
$domData .= ' data-id="'.$line->id.'"';
$coldisplay = 0;
?>
<!-- BEGIN PHP TEMPLATE productattributevalueline_view.tpl.php -->
<tr id="row-<?php print $line->id?>" class="drag drop oddeven" <?php print $domData; ?> >
<?php if (!empty($conf->global->MAIN_VIEW_LINE_NUMBER)) { ?>
<td class="linecolnum center"><span class="opacitymedium"><?php $coldisplay++; ?><?php print ($i + 1); ?></span></td>
<?php } ?>
<td class="linecolref nowrap"><?php $coldisplay++; ?><div id="line_<?php print $line->id; ?>"></div>
<?php print $line->ref ?>
</td>
<td class="linecolvalue nowrap"><?php $coldisplay++; print $line->value ?></td>
<?php
if (!empty($object_rights->write) && $action != 'selectlines') {
print '<td class="linecoledit center width25">';
$coldisplay++;
if (empty($disableedit)) { ?>
<a class="editfielda reposition" href="<?php print $_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=editline&amp;lineid='.$line->id.'#line_'.$line->id; ?>">
<?php print img_edit().'</a>';
}
print '</td>';
print '<td class="linecoldelete center width25">';
$coldisplay++;
if (empty($disableremove)) { // For situation invoice, deletion is not possible if there is a parent company.
print '<a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=ask_deleteline&amp;lineid='.$line->id.'">';
print img_delete();
print '</a>';
}
print '</td>';
if ($num > 1 && $conf->browser->layout != 'phone' && empty($disablemove)) {
print '<td class="linecolmove tdlineupdown center width25">';
$coldisplay++;
if ($i > 0) { ?>
<a class="lineupdown" href="<?php print $_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=up&amp;rowid='.$line->id; ?>">
<?php print img_up('default', 0, 'imgupforline'); ?>
</a>
<?php }
if ($i < $num - 1) { ?>
<a class="lineupdown" href="<?php print $_SERVER["PHP_SELF"].'?id='.$this->id.'&amp;action=down&amp;rowid='.$line->id; ?>">
<?php print img_down('default', 0, 'imgdownforline'); ?>
</a>
<?php }
print '</td>';
} else {
print '<td '.(($conf->browser->layout != 'phone' && empty($disablemove)) ? ' class="linecolmove tdlineupdown center"' : ' class="linecolmove center"').'></td>';
$coldisplay++;
}
} else {
print '<td colspan="3"></td>';
$coldisplay = $coldisplay + 3;
}
if ($action == 'selectlines') { ?>
<td class="linecolcheck center"><input type="checkbox" class="linecheckbox" name="line_checkbox[<?php print $i + 1; ?>]" value="<?php print $line->id; ?>" ></td>
<?php }
print "</tr>\n";
print "<!-- END PHP TEMPLATE productattributevalueline_view.tpl.php -->\n";