瀏覽代碼

NEW : Update variants to standard card and list

kamel 3 年之前
父節點
當前提交
1418fd7054

+ 6 - 0
htdocs/core/actions_addupdatedelete.inc.php

@@ -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

+ 2 - 0
htdocs/core/ajax/row.php

@@ -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;

+ 32 - 12
htdocs/core/class/commonobject.class.php

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

+ 5 - 5
htdocs/core/modules/modVariants.class.php

@@ -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();
 

+ 2 - 0
htdocs/langs/en_US/errors.lang

@@ -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.

+ 2 - 4
htdocs/variants/ajax/getCombinations.php

@@ -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');
 
 
 /*

+ 2 - 4
htdocs/variants/ajax/get_attribute_values.php

@@ -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');
 
 
 /*

+ 12 - 10
htdocs/variants/ajax/orderAttribute.php

@@ -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();
 
+print '<!-- Ajax page called with url '.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.dol_escape_htmltag($_SERVER["QUERY_STRING"]).' -->'."\n";
+
 // Registering the location of boxes
-if (GETPOSTISSET('roworder')) {
-	$roworder = GETPOST('roworder', 'intcomma', 2);
+if (GETPOST('roworder', 'alpha', 3)) {
+	$roworder = GETPOST('roworder', 'alpha', 3);
 
-	dol_syslog("AjaxOrderAttribute roworder=".$roworder, LOG_DEBUG);
+	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';
 }

+ 261 - 204
htdocs/variants/card.php

@@ -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');
-
-			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');
-			}
+	$backurlforlist = dol_buildpath('/variants/list.php', 1);
 
-			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));
-		exit();
+	// 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 = '';
 	}
-}
 
-if ($confirm == 'yes') {
-	if ($action == 'confirm_delete') {
-		$db->begin();
+	// 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';
 
-		$res = $objectval->deleteByFkAttribute($object->id, $user);
+	// Action to move up and down lines of object
+	if ($action == 'up' && $permissiontoedit) {
+		$object->line_up(GETPOST('rowid'), false);
 
-		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();
+		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 ($action == 'addline' && $permissiontoedit) {
+		$line_ref = GETPOST('line_ref', 'alpha');
+		$line_value = GETPOST('line_value', 'alpha');
+
+		$result = $object->addLine($line_ref, $line_value);
+		if ($result > 0) {
 			setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
-			header('Location: '.dol_buildpath('/variants/list.php', 2));
+			header("Location: " . $_SERVER['PHP_SELF'] . '?id=' . $object->id);
+			exit();
+		} else {
+			setEventMessages($object->error, $object->errors, 'errors');
+			$action = '';
 		}
-		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');
-			}
+	} elseif ($action == 'updateline' && $permissiontoedit) {
+		$line_ref = GETPOST('line_ref', 'alpha');
+		$line_value = GETPOST('line_value', 'alpha');
 
-			header('Location: '.dol_buildpath('/variants/card.php?id='.$object->id, 2));
+		$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');
-
+$title = $langs->trans('ProductAttributeName', dol_htmlentities($object->label));
 $help_url = 'EN:Module_Products#Variants';
+llxHeader('', $title, $help_url);
 
-$title = $langs->trans('ProductAttributeName', dol_htmlentities($object->label));
+// Part to create
+if ($action == 'create') {
+	print load_fiche_titre($langs->trans("NewObject", $langs->transnoentitiesnoconv("ProductAttribute")), '', 'object_' . $object->picto);
 
-llxHeader('', $title, $help_url);
+	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 load_fiche_titre($title);
+	print dol_get_fiche_head(array(), '');
 
-$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 '<table class="border centpercent tableforfieldcreate">' . "\n";
 
-print dol_get_fiche_head($head, 'variant', $langs->trans('ProductAttributeName'), -1, 'generic');
+	// Common attributes
+	include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_add.tpl.php';
 
-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>' . "\n";
 
+	print dol_get_fiche_end();
 
-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 '<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 '</td>';
-print '</tr>';
 
-print '</table>';
+// Part to edit record
+elseif (($id || $ref) && $action == 'edit') {
+	print load_fiche_titre($langs->trans("ProductAttribute"), '', 'object_' . $object->picto);
+
+	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();
+
+	print '<table class="border centpercent tableforfieldedit">' . "\n";
+
+	// Common attributes
+	include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_edit.tpl.php';
 
+	print '</table>';
+
+	print dol_get_fiche_end();
 
-if ($action != 'edit') {
+	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>';
 }
 
-print dol_get_fiche_end();
+// Part to show record
+elseif ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) {
+	$res = $object->fetch_optionals();
 
-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 {
+	$head = productAttributePrepareHead($object);
+	print dol_get_fiche_head($head, 'card', $langs->trans("ProductAttribute"), -1, $object->picto);
+
+	$formconfirm = '';
+
+	// Confirmation to delete
 	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
-			);
+		$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);
 		}
 	}
 
-	?>
+	// 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;
+	}
 
-	<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 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>';
 
-	<?php
+	dol_banner_tab($object, 'id', $linkback);
 
-	print load_fiche_titre($langs->trans("PossibleValues"));
+	print '<div class="fichecenter">';
+	print '<div class="fichehalfleft">';
+	print '<div class="underbanner clearboth"></div>';
+	print '<table class="border centpercent tableforfield">' . "\n";
 
-	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.'">';
-	}
+	// Common attributes
+	include DOL_DOCUMENT_ROOT . '/core/tpl/commonfields_view.tpl.php';
 
-	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>';
+	print '</div>';
+	print '</div>';
+
+	print '<div class="clearboth"></div>';
+
+	print dol_get_fiche_end();
 
-	if ($action == 'edit_value') {
-		print '</form>';
+	// 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";
 	}
 
-	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>';
-	print '</div>';
-	print '</div>';
+	/*
+	 * 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

+ 1173 - 164
htdocs/variants/class/ProductAttribute.class.php

@@ -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
@@ -28,52 +29,213 @@ class ProductAttribute extends CommonObject
 	 * @var DoliDB
 	 */
 	public $db;
+	/**
+	 * @var string ID of module.
+	 */
+	public $module = 'variants';
 
 	/**
-	 * Id of the product attribute
-	 * @var int
+	 * @var string ID to identify managed object.
 	 */
-	public $id;
+	public $element = 'productattribute';
 
 	/**
-	 * Ref of the product attribute
-	 * @var string
+	 * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
 	 */
-	public $ref;
+	public $table_element = 'product_attribute';
 
 	/**
-	 * External ref of the product attribute
-	 * @var string
+	 * @var string    Name of sub table line
 	 */
-	public $ref_ext;
+	public $table_element_line = 'product_attribute_value';
 
 	/**
-	 * Label of the product attribute
-	 * @var string
+	 * @var string Field with ID of parent key if this field has a parent or for child tables
 	 */
-	public $label;
+	public $fk_element = 'fk_product_attribute';
 
 	/**
-	 * Order of attribute.
-	 * Lower ones will be shown first and higher ones last
-	 * @var int
+	 * @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 $rang;
+	public $ismultientitymanaged = 1;
 
+	/**
+	 * @var int  Does object support extrafields ? 0=No, 1=Yes
+	 */
+	public $isextrafieldmanaged = 0;
+
+	/**
+	 * @var string String with name of icon for conferenceorbooth. Must be the part after the 'object_' into object_conferenceorbooth.png
+	 */
+	public $picto = 'product';
+
+	/**
+	 *  '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"),
+		'ref' => array('type'=>'varchar(255)', 'label'=>'Ref', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object", 'css'=>''),
+		'ref_ext' => array('type' => 'varchar(255)', 'label' => 'ExternalRef', 'enabled' => 1, 'visible' => 0, 'position' => 20, 'searchall'=>1),
+		'label' => array('type'=>'varchar(255)', 'label'=>'Label', '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'=>40, 'notnull'=>1,),
+	);
+	public $id;
+	public $ref;
+	public $ref_ext;
+	public $label;
 	public $position;
 
+	/**
+	 * @var ProductAttributeValue[]
+	 */
+	public $lines = array();
+	/**
+	 * @var ProductAttributeValue
+	 */
+	public $line;
+
 
 	/**
 	 * Constructor
 	 *
-	 * @param   DoliDB $db     Database handler
+	 * @param DoliDb $db Database handler
 	 */
 	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 product attribute
+	 *
+	 * @param   User    $user      Object user
+	 * @param   int     $notrigger Do not execute trigger
+	 * @return 					int <0 KO, Id of new variant if OK
+	 */
+	public function create(User $user, $notrigger = 0)
+	{
+		global $langs;
+		$error = 0;
+
+		// Clean parameters
+		$this->ref = strtoupper(dol_sanitizeFileName(dol_string_nospecial(trim($this->ref)))); // Ref must be uppercase
+		$this->label = trim($this->label);
+		$this->position = $this->position > 0 ? $this->position : 0;
+
+		// Position to use
+		if (empty($this->position)) {
+			$positionmax = $this->getMaxAttributesPosition();
+			$this->position = $positionmax + 1;
+		}
+
+		// Check parameters
+		if (empty($this->ref)) {
+			$this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref"));
+			$error++;
+		}
+		if (empty($this->label)) {
+			$this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label"));
+			$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 .= " ref, ref_ext, label, entity, position";
+		$sql .= ")";
+		$sql .= " VALUES (";
+		$sql .= "  '" . $this->db->escape($this->ref) . "'";
+		$sql .= ", '" . $this->db->escape($this->ref_ext) . "'";
+		$sql .= ", '" . $this->db->escape($this->label) . "'";
+		$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_CREATE', $user);
+			if ($result < 0) {
+				$error++;
+			}
+			// End call triggers
+		}
+
+		if (!$error) {
+			$this->db->commit();
+			return $this->id;
+		} else {
+			$this->db->rollback();
+			return -1 * $error;
+		}
 	}
 
 	/**
@@ -84,28 +246,49 @@ class ProductAttribute extends CommonObject
 	 */
 	public function fetch($id)
 	{
-		if (!$id) {
+		global $langs;
+		$error = 0;
+
+		// Clean parameters
+		$id = $id > 0 ? $id : 0;
+
+		// 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;
 		}
 
-		$sql = "SELECT rowid, ref, ref_ext, label, position FROM ".MAIN_DB_PREFIX."product_attribute WHERE rowid = ".((int) $id)." AND entity IN (".getEntity('product').")";
-
-		$query = $this->db->query($sql);
+		$sql = "SELECT rowid, ref, ref_ext, label, position";
+		$sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element;
+		$sql .= " WHERE rowid = " . ((int) $id);
+		$sql .= " AND entity IN (" . getEntity('product') . ")";
 
-		if (!$this->db->num_rows($query)) {
+		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->ref = $obj->ref;
-		$this->ref_ext = $obj->ref_ext;
-		$this->label = $obj->label;
-		$this->rang = $obj->position;
-		$this->position = $obj->position;
+			$this->id = $obj->rowid;
+			$this->ref = $obj->ref;
+			$this->ref_ext = $obj->ref_ext;
+			$this->label = $obj->label;
+			$this->rang = $obj->position; // deprecated
+			$this->position = $obj->position;
+		}
+		$this->db->free($resql);
 
-		return 1;
+		return $numrows;
 	}
 
 	/**
@@ -117,91 +300,104 @@ class ProductAttribute extends CommonObject
 	{
 		$return = array();
 
-		$sql = 'SELECT rowid, ref, ref_ext, label, position FROM '.MAIN_DB_PREFIX."product_attribute WHERE entity IN (".getEntity('product').')';
-		$sql .= $this->db->order('position', 'asc');
-		$query = $this->db->query($sql);
-		if ($query) {
-			while ($result = $this->db->fetch_object($query)) {
-				$tmp = new ProductAttribute($this->db);
-				$tmp->id = $result->rowid;
-				$tmp->ref = $result->ref;
-				$tmp->ref_ext = $result->ref_ext;
-				$tmp->label = $result->label;
-				$tmp->rang = $result->position;
-				$tmp->position = $result->position;
-
-				$return[] = $tmp;
-			}
-		} else {
+		$sql = "SELECT rowid, ref, ref_ext, label, position";
+		$sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element;
+		$sql .= " WHERE entity IN (" . getEntity('product') . ")";
+		$sql .= $this->db->order("position", "asc");
+
+		dol_syslog(__METHOD__, LOG_DEBUG);
+		$resql = $this->db->query($sql);
+		if (!$resql) {
+			$this->errors[] = "Error " . $this->db->lasterror();
 			dol_print_error($this->db);
+			return $return;
+		}
+
+		while ($obj = $this->db->fetch_object($resql)) {
+			$tmp = new ProductAttribute($this->db);
+
+			$tmp->id = $obj->rowid;
+			$tmp->ref = $obj->ref;
+			$tmp->ref_ext = $obj->ref_ext;
+			$tmp->label = $obj->label;
+			$tmp->rang = $obj->position; // deprecated
+			$tmp->position = $obj->position;
+
+			$return[] = $tmp;
 		}
 
 		return $return;
 	}
 
 	/**
-	 * Creates a product attribute
+	 * Updates a product attribute
 	 *
 	 * @param   User    $user      Object user
 	 * @param   int     $notrigger Do not execute trigger
-	 * @return 					int <0 KO, Id of new variant if OK
+	 * @return 	int 				<0 KO, >0 OK
 	 */
-	public function create(User $user, $notrigger = 0)
+	public function update(User $user, $notrigger = 0)
 	{
-		if (empty($notrigger)) {
-			// Call trigger
-			$result = $this->call_trigger('PRODUCT_ATTRIBUTE_CREATE', $user);
-			if ($result < 0) {
-				return -1;
-			}
-			// End call triggers
+		global $langs;
+		$error = 0;
+
+		// Clean parameters
+		$this->id = $this->id > 0 ? $this->id : 0;
+		$this->ref = strtoupper(dol_sanitizeFileName(dol_string_nospecial(trim($this->ref)))); // Ref must be uppercase
+		$this->label = trim($this->label);
+
+		// Check parameters
+		if (empty($this->id)) {
+			$this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID"));
+			$error++;
+		}
+		if (empty($this->ref)) {
+			$this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref"));
+			$error++;
+		}
+		if (empty($this->label)) {
+			$this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label"));
+			$error++;
+		}
+		if ($error) {
+			dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
+			return -1;
 		}
 
-		//Ref must be uppercase
-		$this->ref = strtoupper($this->ref);
+		$this->db->begin();
 
-		$sql = "INSERT INTO ".MAIN_DB_PREFIX."product_attribute (ref, ref_ext, label, entity, rang)
-		VALUES ('".$this->db->escape($this->ref)."', '".$this->db->escape($this->ref_ext)."', '".$this->db->escape($this->label)."', ".(int) $this->entity.", ".(int) $this->rang.")";
+		$sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET";
 
-		$query = $this->db->query($sql);
-		if ($query) {
-			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'product_attribute');
+		$sql .= "  ref = '" . $this->db->escape($this->ref) . "'";
+		$sql .= ", ref_ext = '" . $this->db->escape($this->ref_ext) . "'";
+		$sql .= ", label = '" . $this->db->escape($this->label) . "'";
+		$sql .= ", position = " . ((int) $this->position);
 
-			return $this->id;
-		}
+		$sql .= " WHERE rowid = " . ((int) $this->id);
 
-		return -1;
-	}
+		dol_syslog(__METHOD__, LOG_DEBUG);
+		$resql = $this->db->query($sql);
+		if (!$resql) {
+			$this->errors[] = "Error " . $this->db->lasterror();
+			$error++;
+		}
 
-	/**
-	 * Updates a product attribute
-	 *
-	 * @param   User    $user      Object user
-	 * @param   int     $notrigger Do not execute trigger
-	 * @return 	int 				<0 KO, >0 OK
-	 */
-	public function update(User $user, $notrigger = 0)
-	{
-		if (empty($notrigger)) {
+		if (!$error && !$notrigger) {
 			// Call trigger
 			$result = $this->call_trigger('PRODUCT_ATTRIBUTE_MODIFY', $user);
 			if ($result < 0) {
-				return -1;
+				$error++;
 			}
 			// End call triggers
 		}
 
-		//Ref must be uppercase
-		$this->ref = trim(strtoupper($this->ref));
-		$this->label = trim($this->label);
-
-		$sql = "UPDATE ".MAIN_DB_PREFIX."product_attribute SET ref = '".$this->db->escape($this->ref)."', ref_ext = '".$this->db->escape($this->ref_ext)."', label = '".$this->db->escape($this->label)."', rang = ".(int) $this->rang." 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;
 	}
 
 	/**
@@ -213,22 +409,298 @@ class ProductAttribute extends CommonObject
 	 */
 	public function delete(User $user, $notrigger = 0)
 	{
-		if (empty($notrigger)) {
+		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;
+		}
+
+		$result = $this->isUsed();
+		if ($result < 0) {
+			return -1;
+		} elseif ($result > 0) {
+			$this->errors[] = $langs->trans('ErrorAttributeIsUsedIntoProduct');
+			return -1;
+		}
+
+		$this->db->begin();
+
+		if (!$notrigger) {
 			// Call trigger
 			$result = $this->call_trigger('PRODUCT_ATTRIBUTE_DELETE', $user);
 			if ($result < 0) {
-				return -1;
+				$error++;
 			}
 			// End call triggers
 		}
 
-		$sql = "DELETE FROM ".MAIN_DB_PREFIX."product_attribute WHERE rowid = ".(int) $this->id;
+		if (!$error) {
+			// Delete values
+			$sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element_line;
+			$sql .= " WHERE " . $this->fk_element . " = " . ((int) $this->id);
 
-		if ($this->db->query($sql)) {
+			dol_syslog(__METHOD__ . ' - Delete values', LOG_DEBUG);
+			$resql = $this->db->query($sql);
+			if (!$resql) {
+				$this->errors[] = "Error " . $this->db->lasterror();
+				$error++;
+			}
+		}
+
+		if (!$error) {
+			$sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element;
+			$sql .= " WHERE rowid = " . ((int) $this->id);
+
+			dol_syslog(__METHOD__ . ' - Delete attribute', LOG_DEBUG);
+			$resql = $this->db->query($sql);
+			if (!$resql) {
+				$this->errors[] = "Error " . $this->db->lasterror();
+				$error++;
+			}
+		}
+
+		if (!$error) {
+			$this->db->commit();
 			return 1;
+		} else {
+			$this->db->rollback();
+			return -1 * $error;
+		}
+	}
+
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
+	/**
+	 * Load array lines
+	 *
+	 * @param	string		$filters	Filter on other fields
+	 *
+	 * @return	int						<0 if KO, >0 if OK
+	 */
+	public function fetch_lines($filters = '')
+	{
+		// phpcs:enable
+		global $langs;
+		$this->lines = array();
+		$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 td.rowid, td.fk_product_attribute, td.ref, td.value, td.position";
+		$sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element_line . " AS td";
+		$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . $this->table_element . " AS t ON t.rowid = td." . $this->fk_element;
+		$sql .= " WHERE t.rowid = " . ((int) $this->id);
+		$sql .= " AND t.entity IN (" . getEntity('product') . ")";
+		if ($filters) {
+			$sql .= $filters;
+		}
+		$sql .= $this->db->order("td.position", "asc");
+
+		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 -3;
+		}
+
+		$num = $this->db->num_rows($resql);
+		if ($num) {
+			$i = 0;
+			while ($i < $num) {
+				$obj = $this->db->fetch_object($resql);
+
+				$line = new ProductAttributeValue($this->db);
+
+				$line->id = $obj->rowid;
+				$line->fk_product_attribute = $obj->fk_product_attribute;
+				$line->ref = $obj->ref;
+				$line->value = $obj->value;
+				$line->position = $obj->position;
+
+				$this->lines[$i] = $line;
+				$i++;
+			}
+		}
+		$this->db->free($resql);
+
+		return $num;
+	}
+
+	/**
+	 * 	Retrieve an array of proposal lines
+	 *	@param  string              $filters        Filter on other fields
+	 *
+	 * 	@return int		>0 if OK, <0 if KO
+	 */
+	public function getLinesArray($filters = '')
+	{
+		return $this->fetch_lines($filters);
+	}
+
+	/**
+	 *    	Add a proposal line into database (linked to product/service or not)
+	 *      The parameters are already supposed to be appropriate and with final values to the call
+	 *      of this method. Also, for the VAT rate, it must have already been defined
+	 *      by whose calling the method get_default_tva (societe_vendeuse, societe_acheteuse, '' product)
+	 *      and desc must already have the right value (it's up to the caller to manage multilanguage)
+	 *
+	 * @param	string	$ref			Ref of the value
+	 * @param	string	$value			Value
+	 * @param	int		$position		Position of line
+	 * 	@param	int		$notrigger		disable line update trigger
+	 * @return	int						>0 if OK, <0 if KO
+	 */
+	public function addLine($ref, $value, $position = -1, $notrigger = 0)
+	{
+		global $langs, $user;
+		dol_syslog(__METHOD__ . " id={$this->id}, ref=$ref, value=$value, notrigger=$notrigger");
+		$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;
+		}
+
+		$this->db->begin();
+
+		//Fetch current line from the database and then clone the object and set it in $oldcopy property
+		$this->line = new ProductAttributeValue($this->db);
+
+		// Position to use
+		$positiontouse = $position;
+		if ($positiontouse == -1) {
+			$positionmax = $this->line_max(0);
+			$positiontouse = $positionmax + 1;
+		}
+
+		$this->line->context = $this->context;
+		$this->line->fk_product_attribute = $this->id;
+		$this->line->ref = $ref;
+		$this->line->value = $value;
+		$this->line->position = $positiontouse;
+
+		$result = $this->line->create($user, $notrigger);
+
+		if ($result < 0) {
+			$this->error = $this->line->error;
+			$this->errors = $this->line->errors;
+			$this->db->rollback();
+			return -1;
+		} else {
+			$this->db->commit();
+			return $this->line->id;
+		}
+	}
+
+
+	/**
+	 *  Update a line
+	 *
+	 * @param	int		$lineid       	Id of line
+	 * @param	string	$ref			Ref of the value
+	 * @param	string	$value			Value
+	 * @param	int		$notrigger		disable line update trigger
+	 * @return	int     	        	>=0 if OK, <0 if KO
+	 */
+	public function updateLine($lineid, $ref, $value, $notrigger = 0)
+	{
+		global $user;
+
+		dol_syslog(__METHOD__ . " lineid=$lineid, ref=$ref, value=$value, notrigger=$notrigger");
+
+		// Clean parameters
+		$lineid = $lineid > 0 ? $lineid : 0;
+
+		$this->db->begin();
+
+		//Fetch current line from the database and then clone the object and set it in $oldcopy property
+		$this->line = new ProductAttributeValue($this->db);
+		$result = $this->line->fetch($lineid);
+		if ($result > 0) {
+			$this->line->oldcopy = clone $this->line;
+
+			$this->line->context = $this->context;
+			$this->line->ref = $ref;
+			$this->line->value = $value;
+
+			$result = $this->line->update($user, $notrigger);
+		}
+
+		if ($result < 0) {
+			$this->error = $this->line->error;
+			$this->errors = $this->line->errors;
+			$this->db->rollback();
+			return -1;
+		} else {
+			$this->db->commit();
+			return $result;
+		}
+	}
+
+	/**
+	 *  Delete a line
+	 *
+	 * @param   User    $user      Object user
+	 * @param	int		$lineid			Id of line to delete
+	 * @param	int		$notrigger		disable line update trigger
+	 * @return	int         			>0 if OK, <0 if KO
+	 */
+	public function deleteLine(User $user, $lineid, $notrigger = 0)
+	{
+		dol_syslog(__METHOD__ . " lineid=$lineid, notrigger=$notrigger");
+
+		// Clean parameters
+		$lineid = $lineid > 0 ? $lineid : 0;
+
+		$this->db->begin();
+
+		//Fetch current line from the database
+		$this->line = new ProductAttributeValue($this->db);
+		$result = $this->line->fetch($lineid);
+		if ($result > 0) {
+			$this->line->context = $this->context;
+
+			$result = $this->line->delete($user, $notrigger);
 		}
 
-		return -1;
+		if ($result < 0) {
+			$this->error = $this->line->error;
+			$this->errors = $this->line->errors;
+			$this->db->rollback();
+			return -1;
+		} else {
+			$this->db->commit();
+			return $result;
+		}
 	}
 
 	/**
@@ -238,12 +710,40 @@ class ProductAttribute extends CommonObject
 	 */
 	public function countChildValues()
 	{
-		$sql = "SELECT COUNT(*) count FROM ".MAIN_DB_PREFIX."product_attribute_value WHERE fk_product_attribute = ".(int) $this->id;
+		global $langs;
+		$error = 0;
+		$count = 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;
+		}
 
-		$query = $this->db->query($sql);
-		$result = $this->db->fetch_object($query);
+		$sql = "SELECT COUNT(*) AS count";
+		$sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element_line;
+		$sql .= " WHERE " . $this->fk_element . " = " . ((int) $this->id);
 
-		return $result->count;
+		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;
+		}
+
+		if ($obj = $this->db->fetch_object($resql)) {
+			$count = $obj->count;
+		}
+
+		return $count;
 	}
 
 	/**
@@ -253,140 +753,649 @@ class ProductAttribute extends CommonObject
 	 */
 	public function countChildProducts()
 	{
-		$sql = "SELECT COUNT(*) count FROM ".MAIN_DB_PREFIX."product_attribute_combination2val pac2v
-		LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination pac ON pac2v.fk_prod_combination = pac.rowid WHERE pac2v.fk_prod_attr = ".((int) $this->id)." AND pac.entity IN (".getEntity('product').")";
+		global $langs;
+		$error = 0;
+		$count = 0;
+
+		// Clean parameters
+		$this->id = $this->id > 0 ? $this->id : 0;
 
-		$query = $this->db->query($sql);
+		// 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;
+		}
 
-		$result = $this->db->fetch_object($query);
+		$sql = "SELECT COUNT(*) AS count";
+		$sql .= " FROM " . MAIN_DB_PREFIX . "product_attribute_combination2val AS pac2v";
+		$sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "product_attribute_combination AS pac ON pac2v.fk_prod_combination = pac.rowid";
+		$sql .= " WHERE pac2v.fk_prod_attr = " . ((int) $this->id);
+		$sql .= " AND pac.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;
+		}
 
-		return $result->count;
-	}
+		if ($obj = $this->db->fetch_object($resql)) {
+			$count = $obj->count;
+		}
 
+		return $count;
+	}
 
 	/**
-	 * Reorders the order of the variants.
-	 * This is an internal function used by moveLine function
+	 * Test if used by a product
 	 *
-	 * @return int <0 KO >0 OK
+	 * @return int <0 KO, =0 if No, =1 if Yes
 	 */
-	protected function reorderLines()
+	public function isUsed()
 	{
-		global $user;
+		global $langs;
+		$error = 0;
 
-		$tmp_order = array();
+		// Clean parameters
+		$this->id = $this->id > 0 ? $this->id : 0;
 
-		$sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'product_attribute WHERE rang = 0';
-		$sql .= $this->db->order('rang, rowid', 'asc');
+		// 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;
+		}
 
-		$query = $this->db->query($sql);
+		$sql = "SELECT COUNT(*) AS nb FROM " . MAIN_DB_PREFIX . "product_attribute_combination2val WHERE fk_prod_attr = " . ((int) $this->id);
 
-		if (!$query) {
+		dol_syslog(__METHOD__, LOG_DEBUG);
+		$resql = $this->db->query($sql);
+		if (!$resql) {
+			$this->errors[] = "Error " . $this->db->lasterror();
 			return -1;
 		}
 
-		while ($result = $this->db->fetch_object($query)) {
-			$tmp_order[] = $result->rowid;
+		$used = 0;
+		if ($obj = $this->db->fetch_object($resql)) {
+			$used = $obj->nb;
 		}
 
-		foreach ($tmp_order as $order => $rowid) {
-			$tmp = new ProductAttribute($this->db);
-			$tmp->fetch($rowid);
-			$tmp->rang = $order + 1;
+		return $used ? 1 : 0;
+	}
 
-			if ($tmp->update($user) < 0) {
-				return -1;
-			}
+	/**
+	 *  Save a new position (field position) for details lines.
+	 *  You can choose to set position for lines with already a position or lines without any position defined.
+	 *
+	 * @param	boolean		$renum			   True to renum all already ordered lines, false to renum only not already ordered lines.
+	 * @param	string		$rowidorder		   ASC or DESC
+	 * @return	int                            <0 if KO, >0 if OK
+	 */
+	public function attributeOrder($renum = false, $rowidorder = 'ASC')
+	{
+		// Count number of attributes to reorder (according to choice $renum)
+		$nl = 0;
+		$sql = "SELECT count(rowid) FROM " . MAIN_DB_PREFIX . $this->table_element;
+		$sql .= " WHERE entity IN (" . getEntity('product') . ")";
+		if (!$renum) {
+			$sql .= " AND position = 0";
+		} else {
+			$sql .= " AND position <> 0";
 		}
 
+		dol_syslog(__METHOD__, LOG_DEBUG);
+		$resql = $this->db->query($sql);
+		if ($resql) {
+			$row = $this->db->fetch_row($resql);
+			$nl = $row[0];
+		} else {
+			dol_print_error($this->db);
+		}
+		if ($nl > 0) {
+			// The goal of this part is to reorder all attributes.
+			$rows = array();
+
+			// We first search all attributes
+			$sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . $this->table_element;
+			$sql .= " WHERE entity IN (" . getEntity('product') . ")";
+			$sql .= " ORDER BY position ASC, rowid " . $rowidorder;
+
+			dol_syslog(__METHOD__ . " search all attributes", LOG_DEBUG);
+			$resql = $this->db->query($sql);
+			if ($resql) {
+				$i = 0;
+				$num = $this->db->num_rows($resql);
+				while ($i < $num) {
+					$row = $this->db->fetch_row($resql);
+					$rows[] = $row[0]; // Add attributes into array rows
+					$i++;
+				}
+
+				// Now we set a new number for each attributes
+				if (!empty($rows)) {
+					foreach ($rows as $key => $row) {
+						$this->updatePositionOfAttribute($row, ($key + 1));
+					}
+				}
+			} else {
+				dol_print_error($this->db);
+			}
+		}
 		return 1;
 	}
 
 	/**
-	 * Internal function to handle moveUp and moveDown functions
+	 * 	Update position of line (rang)
 	 *
-	 * @param string $type up/down
-	 * @return int <0 KO >0 OK
+	 * @param	int		$rowid		Id of line
+	 * @param	int		$position	Position
+	 * @return	int					<0 if KO, >0 if OK
 	 */
-	private function moveLine($type)
+	public function updatePositionOfAttribute($rowid, $position)
 	{
-		global $user;
+		global $hookmanager;
+
+		$sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET position = " . ((int) $position);
+		$sql .= " WHERE rowid = " . ((int) $rowid);
 
-		if ($this->reorderLines() < 0) {
+		dol_syslog(__METHOD__, LOG_DEBUG);
+		if (!$this->db->query($sql)) {
+			dol_print_error($this->db);
 			return -1;
+		} else {
+			$parameters = array('rowid' => $rowid, 'position' => $position);
+			$action = '';
+			$reshook = $hookmanager->executeHooks('afterPositionOfAttributeUpdate', $parameters, $this, $action);
+			return 1;
 		}
+	}
 
-		$this->db->begin();
+	/**
+	 * 	Get position of attribute
+	 *
+	 * @param	int		$rowid		Id of line
+	 * @return	int     			Value of position in table of attributes
+	 */
+	public function getPositionOfAttribute($rowid)
+	{
+		$sql = "SELECT position FROM " . MAIN_DB_PREFIX . $this->table_element;
+		$sql .= " WHERE entity IN (" . getEntity('product') . ")";
+
+		dol_syslog(__METHOD__, LOG_DEBUG);
+		$resql = $this->db->query($sql);
+		if ($resql) {
+			$row = $this->db->fetch_row($resql);
+			return $row[0];
+		}
+
+		return 0;
+	}
+
+	/**
+	 * 	Update a attribute to have a higher position
+	 *
+	 * @param	int		$rowid		Id of line
+	 * @return	int					<0 KO >0 OK
+	 */
+	public function attributeMoveUp($rowid)
+	{
+		$this->attributeOrder(false, 'ASC');
+
+		// Get position of attribute
+		$position = $this->getPositionOfAttribute($rowid);
+
+		// Update position of attribute
+		$this->updateAttributePositionUp($rowid, $position);
+	}
+
+	/**
+	 * 	Update a attribute to have a lower position
+	 *
+	 * @param	int		$rowid		Id of line
+	 * @return	int					<0 KO >0 OK
+	 */
+	public function attributeMoveDown($rowid)
+	{
+		$this->attributeOrder(false, 'ASC');
+
+		// Get position of line
+		$position = $this->getPositionOfAttribute($rowid);
+
+		// Get max value for position
+		$max = $this->getMaxAttributesPosition();
+
+		// Update position of attribute
+		$this->updateAttributePositionDown($rowid, $position, $max);
+	}
+
+	/**
+	 * 	Update position of attribute (up)
+	 *
+	 * @param	int		$rowid		Id of line
+	 * @param	int		$position	Position
+	 * @return	void
+	 */
+	public function updateAttributePositionUp($rowid, $position)
+	{
+		if ($position > 1) {
+			$sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET position = " . ((int) $position);
+			$sql .= " WHERE entity IN (" . getEntity('product') . ")";
+			$sql .= " AND position = " . ((int) ($position - 1));
+			if ($this->db->query($sql)) {
+				$sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET position = " . ((int) ($position - 1));
+				$sql .= " WHERE rowid = " . ((int) $rowid);
+				if (!$this->db->query($sql)) {
+					dol_print_error($this->db);
+				}
+			} else {
+				dol_print_error($this->db);
+			}
+		}
+	}
+
+	/**
+	 * 	Update position of attribute (down)
+	 *
+	 * @param	int		$rowid		Id of line
+	 * @param	int		$position	Position
+	 * @param	int		$max		Max
+	 * @return	void
+	 */
+	public function updateAttributePositionDown($rowid, $position, $max)
+	{
+		if ($position < $max) {
+			$sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET position = " . ((int) $position);
+			$sql .= " WHERE entity IN (" . getEntity('product') . ")";
+			$sql .= " AND position = " . ((int) ($position + 1));
+			if ($this->db->query($sql)) {
+				$sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET position = " . ((int) ($position + 1));
+				$sql .= " WHERE rowid = " . ((int) $rowid);
+				if (!$this->db->query($sql)) {
+					dol_print_error($this->db);
+				}
+			} else {
+				dol_print_error($this->db);
+			}
+		}
+	}
+
+	/**
+	 * 	Get max value used for position of attributes
+	 *
+	 * @return     int  			Max value of position in table of attributes
+	 */
+	public function getMaxAttributesPosition()
+	{
+		// Search the last position of attributes
+		$sql = "SELECT max(position) FROM " . MAIN_DB_PREFIX . $this->table_element;
+		$sql .= " WHERE entity IN (" . getEntity('product') . ")";
+
+		dol_syslog(__METHOD__, LOG_DEBUG);
+		$resql = $this->db->query($sql);
+		if ($resql) {
+			$row = $this->db->fetch_row($resql);
+			return $row[0];
+		}
+
+		return 0;
+	}
+
+	/**
+	 * 	Update position of attributes with ajax
+	 *
+	 * 	@param	array	$rows	Array of rows
+	 * 	@return	void
+	 */
+	public function attributesAjaxOrder($rows)
+	{
+		$num = count($rows);
+		for ($i = 0; $i < $num; $i++) {
+			$this->updatePositionOfAttribute($rows[$i], ($i + 1));
+		}
+	}
+
+	/**
+	 *  Return a link to the object card (with optionaly the picto)
+	 *
+	 *  @param  int     $withpicto                  Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
+	 *  @param  string  $option                     On what the link point to ('nolink', ...)
+	 *  @param  int     $notooltip                  1=Disable tooltip
+	 *  @param  string  $morecss                    Add more css on link
+	 *  @param  int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
+	 *  @return	string                              String with URL
+	 */
+	public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
+	{
+		global $conf, $langs, $hookmanager;
+
+		if (!empty($conf->dol_no_mouse_hover)) {
+			$notooltip = 1; // Force disable tooltips
+		}
+
+		$result = '';
+
+		$label = img_picto('', $this->picto) . ' <u>' . $langs->trans("ProductAttribute") . '</u>';
+		if (isset($this->status)) {
+			$label .= ' ' . $this->getLibStatut(5);
+		}
+		$label .= '<br>';
+		$label .= '<b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
+		if (!empty($this->label)) {
+			$label .= '<br><b>' . $langs->trans('Label') . ':</b> ' . $this->label;
+		}
+
+		$url = dol_buildpath('/variants/card.php', 1) . '?id=' . $this->id;
+
+		if ($option != 'nolink') {
+			// Add param to save lastsearch_values or not
+			$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
+			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
+				$add_save_lastsearch_values = 1;
+			}
+			if ($url && $add_save_lastsearch_values) {
+				$url .= '&save_lastsearch_values=1';
+			}
+		}
+
+		$linkclose = '';
+		if (empty($notooltip)) {
+			if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
+				$label = $langs->trans("ShowProductAttribute");
+				$linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
+			}
+			$linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"';
+			$linkclose .= ' class="classfortooltip' . ($morecss ? ' ' . $morecss : '') . '"';
+		} else {
+			$linkclose = ($morecss ? ' class="' . $morecss . '"' : '');
+		}
 
-		if ($type == 'up') {
-			$newrang = $this->rang - 1;
+		if ($option == 'nolink' || empty($url)) {
+			$linkstart = '<span';
+		} else {
+			$linkstart = '<a href="' . $url . '"';
+		}
+		$linkstart .= $linkclose . '>';
+		if ($option == 'nolink' || empty($url)) {
+			$linkend = '</span>';
 		} else {
-			$newrang = $this->rang + 1;
+			$linkend = '</a>';
 		}
 
-		$sql = 'UPDATE '.MAIN_DB_PREFIX.'product_attribute SET rang = '.((int) $this->rang).' WHERE rang = '.((int) $newrang);
+		$result .= $linkstart;
 
-		if (!$this->db->query($sql)) {
-			$this->db->rollback();
-			return -1;
+		if (empty($this->showphoto_on_popup)) {
+			if ($withpicto) {
+				$result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright ' : '') . 'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+			}
+		} else {
+			if ($withpicto) {
+				require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
+
+				list($class, $module) = explode('@', $this->picto);
+				$upload_dir = $conf->$module->multidir_output[$conf->entity] . "/$class/" . dol_sanitizeFileName($this->ref);
+				$filearray = dol_dir_list($upload_dir, "files");
+				$filename = $filearray[0]['name'];
+				if (!empty($filename)) {
+					$pospoint = strpos($filearray[0]['name'], '.');
+
+					$pathtophoto = $class . '/' . $this->ref . '/thumbs/' . substr($filename, 0, $pospoint) . '_mini' . substr($filename, $pospoint);
+					if (empty($conf->global->{strtoupper($module . '_' . $class) . '_FORMATLISTPHOTOSASUSERS'})) {
+						$result .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo' . $module . '" alt="No photo" border="0" src="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $module . '&entity=' . $conf->entity . '&file=' . urlencode($pathtophoto) . '"></div></div>';
+					} else {
+						$result .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photouserphoto userphoto" alt="No photo" border="0" src="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $module . '&entity=' . $conf->entity . '&file=' . urlencode($pathtophoto) . '"></div>';
+					}
+
+					$result .= '</div>';
+				} else {
+					$result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright ' : '') . 'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
+				}
+			}
 		}
 
-		$this->rang = $newrang;
+		if ($withpicto != 2) {
+			$result .= $this->ref;
+		}
 
-		if ($this->update($user) < 0) {
-			$this->db->rollback();
-			return -1;
+		$result .= $linkend;
+		//if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
+
+		global $action, $hookmanager;
+		$hookmanager->initHooks(array('variantsdao'));
+		$parameters = array('id' => $this->id, 'getnomurl' => $result);
+		$reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+		if ($reshook > 0) {
+			$result = $hookmanager->resPrint;
+		} else {
+			$result .= $hookmanager->resPrint;
 		}
 
-		$this->db->commit();
-		return 1;
+		return $result;
 	}
 
 	/**
-	 * Shows this attribute before others
+	 *  Return the label of the status
 	 *
-	 * @return int <0 KO >0 OK
+	 *  @param  int		$mode          0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
+	 *  @return	string 			       Label of status
 	 */
-	public function moveUp()
+	public function getLabelStatus($mode = 0)
 	{
-		return $this->moveLine('up');
+		return $this->LibStatut(0, $mode);
 	}
 
 	/**
-	 * Shows this attribute after others
+	 * Return label of status of product attribute
 	 *
-	 * @return int <0 KO >0 OK
+	 * @param      int			$mode        0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto
+	 * @return     string		Label
 	 */
-	public function moveDown()
+	public function getLibStatut($mode = 0)
 	{
-		return $this->moveLine('down');
+		return $this->LibStatut(0, $mode);
 	}
 
+	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
 	/**
-	 * Updates the order of all variants. Used by AJAX page for drag&drop
+	 * Return label of a status
 	 *
-	 * @param DoliDB $db Database handler
-	 * @param array $order Array with row id ordered in ascendent mode
-	 * @return int <0 KO >0 OK
+	 * @param      int			$status		Id status
+	 * @param      int			$mode      	0=Long label, 1=Short label, 2=Picto + Short label, 3=Picto, 4=Picto + Long label, 5=Short label + Picto, 6=Long label + Picto
+	 * @return     string		Label
 	 */
-	public static function bulkUpdateOrder(DoliDB $db, array $order)
+	public function LibStatut($status, $mode = 1)
 	{
-		global $user;
+		// phpcs:enable
+		return '';
+	}
+
+	// --------------------
+	// TODO: All functions here must be redesigned and moved as they are not business functions but output functions
+	// --------------------
+
+	/* This is to show add lines */
+
+	/**
+	 *	Show add free and predefined products/services form
+	 *
+	 *  @param	int		        $dateSelector       1=Show also date range input fields
+	 *  @param	Societe			$seller				Object thirdparty who sell
+	 *  @param	Societe			$buyer				Object thirdparty who buy
+	 *  @param	string			$defaulttpldir		Directory where to find the template
+	 *	@return	void
+	 */
+	public function formAddObjectLine($dateSelector, $seller, $buyer, $defaulttpldir = '/variants/tpl')
+	{
+		global $conf, $user, $langs, $object, $hookmanager;
+		global $form;
+
+		// Output template part (modules that overwrite templates must declare this into descriptor)
+		// Use global variables + $dateSelector + $seller and $buyer
+		// Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook 'formAddObjectLine'.
+		$dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
+		foreach ($dirtpls as $module => $reldir) {
+			if (!empty($module)) {
+				$tpl = dol_buildpath($reldir . '/productattributevalueline_create.tpl.php');
+			} else {
+				$tpl = DOL_DOCUMENT_ROOT . $reldir . '/productattributevalueline_create.tpl.php';
+			}
 
-		$tmp = new ProductAttribute($db);
+			if (empty($conf->file->strict_mode)) {
+				$res = @include $tpl;
+			} else {
+				$res = include $tpl; // for debug
+			}
+			if ($res) {
+				break;
+			}
+		}
+	}
+
+	/* This is to show array of line of details */
 
-		foreach ($order as $key => $attrid) {
-			if ($tmp->fetch($attrid) < 0) {
-				return -1;
+	/**
+	 *	Return HTML table for object lines
+	 *	TODO Move this into an output class file (htmlline.class.php)
+	 *	If lines are into a template, title must also be into a template
+	 *	But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
+	 *
+	 *	@param	string		$action				Action code
+	 *	@param  string		$seller            	Object of seller third party
+	 *	@param  string  	$buyer             	Object of buyer third party
+	 *	@param	int			$selected		   	Object line selected
+	 *	@param  int	    	$dateSelector      	1=Show also date range input fields
+	 *  @param	string		$defaulttpldir		Directory where to find the template
+	 *	@return	void
+	 */
+	public function printObjectLines($action, $seller, $buyer, $selected = 0, $dateSelector = 0, $defaulttpldir = '/variants/tpl')
+	{
+		global $conf, $hookmanager, $langs, $user, $form, $object;
+		// TODO We should not use global var for this
+		global $disableedit, $disablemove, $disableremove;
+
+		$num = count($this->lines);
+
+		$parameters = array('num' => $num, 'selected' => $selected, 'table_element_line' => $this->table_element_line);
+		$reshook = $hookmanager->executeHooks('printObjectLineTitle', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+		if (empty($reshook)) {
+			// Output template part (modules that overwrite templates must declare this into descriptor)
+			// Use global variables + $dateSelector + $seller and $buyer
+			// Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook.
+			$dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
+			foreach ($dirtpls as $module => $reldir) {
+				if (!empty($module)) {
+					$tpl = dol_buildpath($reldir . '/productattributevalueline_title.tpl.php');
+				} else {
+					$tpl = DOL_DOCUMENT_ROOT . $reldir . '/productattributevalueline_title.tpl.php';
+				}
+				if (empty($conf->file->strict_mode)) {
+					$res = @include $tpl;
+				} else {
+					$res = include $tpl; // for debug
+				}
+				if ($res) {
+					break;
+				}
 			}
+		}
 
-			$tmp->rang = $key;
+		$i = 0;
 
-			if ($tmp->update($user) < 0) {
-				return -1;
+		print "<!-- begin printObjectLines() --><tbody>\n";
+		foreach ($this->lines as $line) {
+			if (is_object($hookmanager)) {   // Old code is commented on preceding line.
+				$parameters = array('line' => $line, 'num' => $num, 'i' => $i, 'selected' => $selected, 'table_element_line' => $line->table_element);
+				$reshook = $hookmanager->executeHooks('printObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
+			}
+			if (empty($reshook)) {
+				$this->printObjectLine($action, $line, '', $num, $i, $dateSelector, $seller, $buyer, $selected, null, $defaulttpldir);
 			}
+
+			$i++;
 		}
+		print "</tbody><!-- end printObjectLines() -->\n";
+	}
 
-		return 1;
+	/**
+	 *	Return HTML content of a detail line
+	 *	TODO Move this into an output class file (htmlline.class.php)
+	 *
+	 *	@param	string      		$action				GET/POST action
+	 *	@param  CommonObjectLine 	$line			    Selected object line to output
+	 *	@param  string	    		$var               	Is it a an odd line (true)
+	 *	@param  int		    		$num               	Number of line (0)
+	 *	@param  int		    		$i					I
+	 *	@param  int		    		$dateSelector      	1=Show also date range input fields
+	 *	@param  string	    		$seller            	Object of seller third party
+	 *	@param  string	    		$buyer             	Object of buyer third party
+	 *	@param	int					$selected		   	Object line selected
+	 *  @param  Extrafields			$extrafields		Object of extrafields
+	 *  @param	string				$defaulttpldir		Directory where to find the template (deprecated)
+	 *	@return	void
+	 */
+	public function printObjectLine($action, $line, $var, $num, $i, $dateSelector, $seller, $buyer, $selected = 0, $extrafields = null, $defaulttpldir = '/variants/tpl')
+	{
+		global $conf, $langs, $user, $object, $hookmanager;
+		global $form;
+		global $object_rights, $disableedit, $disablemove, $disableremove; // TODO We should not use global var for this !
+
+		$object_rights = $user->rights->produit->lire || $user->rights->service->lire;
+
+		// Line in view mode
+		if ($action != 'editline' || $selected != $line->id) {
+			// Output template part (modules that overwrite templates must declare this into descriptor)
+			// Use global variables + $dateSelector + $seller and $buyer
+			// Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
+			$dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
+			foreach ($dirtpls as $module => $reldir) {
+				if (!empty($module)) {
+					$tpl = dol_buildpath($reldir . '/productattributevalueline_view.tpl.php');
+				} else {
+					$tpl = DOL_DOCUMENT_ROOT . $reldir . '/productattributevalueline_view.tpl.php';
+				}
+
+				if (empty($conf->file->strict_mode)) {
+					$res = @include $tpl;
+				} else {
+					$res = include $tpl; // for debug
+				}
+				if ($res) {
+					break;
+				}
+			}
+		}
+
+		// Line in update mode
+		if ($action == 'editline' && $selected == $line->id) {
+			// Output template part (modules that overwrite templates must declare this into descriptor)
+			// Use global variables + $dateSelector + $seller and $buyer
+			// Note: This is deprecated. If you need to overwrite the tpl file, use instead the hook printObjectLine and printObjectSubLine.
+			$dirtpls = array_merge($conf->modules_parts['tpl'], array($defaulttpldir));
+			foreach ($dirtpls as $module => $reldir) {
+				if (!empty($module)) {
+					$tpl = dol_buildpath($reldir . '/productattributevalueline_edit.tpl.php');
+				} else {
+					$tpl = DOL_DOCUMENT_ROOT . $reldir . '/productattributevalueline_edit.tpl.php';
+				}
+
+				if (empty($conf->file->strict_mode)) {
+					$res = @include $tpl;
+				} else {
+					$res = include $tpl; // for debug
+				}
+				if ($res) {
+					break;
+				}
+			}
+		}
 	}
+
+	/* This is to show array of line of details of source object */
 }

+ 313 - 111
htdocs/variants/class/ProductAttributeValue.class.php

@@ -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 $id;
+	public $element = 'productattributevalue';
 
 	/**
-	 * Product attribute id
-	 * @var int
+	 * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
 	 */
-	public $fk_product_attribute;
+	public $table_element = 'product_attribute_value';
 
 	/**
-	 * Attribute value ref
-	 * @var string
+	 * @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 $ref;
+	public $ismultientitymanaged = 1;
+
+	/**
+	 * @var int  Does object support extrafields ? 0=No, 1=Yes
+	 */
+	public $isextrafieldmanaged = 0;
 
 	/**
-	 * Attribute value value
-	 * @var string
+	 *  '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;
+	public $fk_product_attribute;
+	public $ref;
 	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);
@@ -143,75 +304,74 @@ class ProductAttributeValue extends CommonObject
 	}
 
 	/**
-	 * Creates a value for a product attribute
+	 * Updates a product attribute value
 	 *
-	 * @param  User $user      Object user
+	 * @param  User	$user	   Object user
 	 * @param  int  $notrigger Do not execute trigger
-	 * @return int <0 KO >0 OK
+	 * @return int <0 if KO, >0 if OK
 	 */
-	public function create(User $user, $notrigger = 0)
+	public function update(User $user, $notrigger = 0)
 	{
-		if (!$this->fk_product_attribute) {
+		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;
 		}
 
-		// Ref must be uppercase
-		$this->ref = strtoupper($this->ref);
-		$this->value = $this->db->escape($this->value);
+		$this->db->begin();
 
-		$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.")";
+		$sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET";
 
-		$query = $this->db->query($sql);
+		$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);
 
-		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
-			}
+		$sql .= " WHERE rowid = " . ((int) $this->id);
 
-			return 1;
+		dol_syslog(__METHOD__, LOG_DEBUG);
+		$resql = $this->db->query($sql);
+		if (!$resql) {
+			$this->errors[] = "Error " . $this->db->lasterror();
+			$error++;
 		}
 
-		return -1;
-	}
-
-	/**
-	 * Updates a product attribute value
-	 *
-	 * @param  User	$user	   Object user
-	 * @param  int  $notrigger Do not execute trigger
-	 * @return int <0 if KO, >0 if OK
-	 */
-	public function update(User $user, $notrigger = 0)
-	{
-		if (empty($notrigger)) {
+		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;
+
+		// 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;
+		}
 
-		if (empty($notrigger)) {
+		$result = $this->isUsed();
+		if ($result < 0) {
+			return -1;
+		} elseif ($result > 0) {
+			$this->errors[] = $langs->trans('ErrorAttributeValueIsUsedIntoProduct');
+			return -1;
+		}
+
+		$this->db->begin();
+
+		if (!$error && !$notrigger) {
 			// Call trigger
 			$result = $this->call_trigger('PRODUCT_ATTRIBUTE_VALUE_DELETE', $user);
 			if ($result < 0) {
-				return -1;
+				$error++;
 			}
 			// End call triggers
 		}
-		$sql = "DELETE FROM ".MAIN_DB_PREFIX."product_attribute_value WHERE rowid = ".(int) $this->id;
-		if ($this->db->query($sql)) {
-			return 1;
+
+		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;
+		}
 	}
 
 	/**
-	 * Deletes all product attribute values by a product attribute id
+	 * Test if used by a product
 	 *
-	 * @param int  $fk_attribute Product attribute id
-	 * @param User $user         Object user
-	 * @return int <0 KO, >0 OK
+	 * @return int <0 KO, =0 if No, =1 if Yes
 	 */
-	public function deleteByFkAttribute($fk_attribute, User $user)
+	public function isUsed()
 	{
-		$sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product_attribute_value WHERE fk_product_attribute = ".(int) $fk_attribute;
+		global $langs;
+		$error = 0;
 
-		$query = $this->db->query($sql);
+		// Clean parameters
+		$this->id = $this->id > 0 ? $this->id : 0;
 
-		if (!$query) {
+		// 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;
 		}
 
-		if (!$this->db->num_rows($query)) {
-			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;
 		}
 
-		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;
-			}
+		$used = 0;
+		if ($obj = $this->db->fetch_object($resql)) {
+			$used = $obj->nb;
 		}
 
-		return 1;
+		return $used ? 1 : 0;
 	}
 }

+ 3 - 2
htdocs/variants/class/ProductCombination.class.php

@@ -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);
 

+ 11 - 10
htdocs/variants/class/ProductCombination2ValuePair.class.php

@@ -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;

+ 26 - 23
htdocs/variants/combinations.php

@@ -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) {
-						continue;
-					}
-
-					if ($prodattr_val->fetch($explode[1]) < 0) {
+					$explode = explode('-', $feature);
+					if ($prodattr->fetch($explode[0]) <= 0 || $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

+ 0 - 115
htdocs/variants/create.php

@@ -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();

+ 0 - 161
htdocs/variants/create_val.php

@@ -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();

+ 53 - 0
htdocs/variants/lib/variants.lib.php

@@ -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;
+}

+ 714 - 63
htdocs/variants/list.php

@@ -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 = '';
+}
+
+$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');
+}
+
+if (empty($reshook)) {
+	// Selection of new fields
+	include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php';
 
-	header('Location: '.$_SERVER['PHP_SELF']);
-	exit();
-} elseif ($action == 'down' && $permissiontoadd) {
-	$object->fetch($rowid);
-	$object->moveDown();
+	// 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();
+	}
 
-	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);
+	}
+}
+
+// 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);
 
-print load_fiche_titre($title, $newcardbutton, 'product');
+// 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>';
+
+if (in_array('builddoc', $arrayofmassactions) && ($nbtotalofrecords === '' || $nbtotalofrecords)) {
+	$hidegeneratedfilelistifempty = 1;
+	if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) {
+		$hidegeneratedfilelistifempty = 0;
 	}
-	print '</td>';
-	print "</tr>\n";
-}
 
-print '</table>';
+	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();

+ 3 - 0
htdocs/variants/tpl/README

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

+ 91 - 0
htdocs/variants/tpl/productattributevalueline_create.tpl.php

@@ -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 -->

+ 77 - 0
htdocs/variants/tpl/productattributevalueline_edit.tpl.php

@@ -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 -->

+ 70 - 0
htdocs/variants/tpl/productattributevalueline_title.tpl.php

@@ -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";

+ 105 - 0
htdocs/variants/tpl/productattributevalueline_view.tpl.php

@@ -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";