Explorar el Código

add class default values

Florian HENRY hace 4 años
padre
commit
0edae6e19a
Se han modificado 2 ficheros con 414 adiciones y 55 borrados
  1. 55 55
      htdocs/admin/defaultvalues.php
  2. 359 0
      htdocs/core/class/defaultvalues.class.php

+ 55 - 55
htdocs/admin/defaultvalues.php

@@ -30,6 +30,7 @@ require '../main.inc.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/defaultvalues.class.php';
 
 // Load translation files required by the page
 $langs->loadLangs(array('companies', 'products', 'admin', 'sms', 'other', 'errors'));
@@ -67,6 +68,7 @@ $value = GETPOST('value', 'restricthtml');
 $hookmanager->initHooks(array('admindefaultvalues', 'globaladmin'));
 
 
+$object = new DefaultValues($db);
 /*
  * Actions
  */
@@ -133,27 +135,41 @@ if (($action == 'add' || (GETPOST('add') && $action != 'update')) || GETPOST('ac
 
 		if ($action == 'add' || (GETPOST('add') && $action != 'update'))
 		{
-			$sql = "INSERT INTO ".MAIN_DB_PREFIX."default_values(type, user_id, page, param, value, entity) VALUES ('".$db->escape($mode)."', 0, '".$db->escape($defaulturl)."','".$db->escape($defaultkey)."','".$db->escape($defaultvalue)."', ".$db->escape($conf->entity).")";
+			$object->type=$mode;
+			$object->user_id=0;
+			$object->page=$defaulturl;
+			$object->param=$defaulturl;
+			$object->value=$defaultvalue;
+			$object->entity=$conf->entity;
+			$result=$object->create($user);
+			if ($result<0) {
+				$action = '';
+				setEventMessages($object->error,$object->errors,'errors');
+			} else {
+				setEventMessages($langs->trans("RecordSaved"), null, 'mesgs');
+				$action = "";
+				$defaulturl = '';
+				$defaultkey = '';
+				$defaultvalue = '';
+			}
 		}
 		if (GETPOST('actionmodify'))
 		{
-			$sql = "UPDATE ".MAIN_DB_PREFIX."default_values SET page = '".$db->escape($urlpage)."', param = '".$db->escape($key)."', value = '".$db->escape($value)."'";
-			$sql .= " WHERE rowid = ".$id;
-		}
-
-		$result = $db->query($sql);
-		if ($result > 0)
-		{
-			$db->commit();
-			setEventMessages($langs->trans("RecordSaved"), null, 'mesgs');
-			$action = "";
-			$defaulturl = '';
-			$defaultkey = '';
-			$defaultvalue = '';
-		} else {
-			$db->rollback();
-			setEventMessages($db->lasterror(), null, 'errors');
-			$action = '';
+			$object->id=$id;
+			$object->page=$defaulturl;
+			$object->param=$key;
+			$object->value=$defaultvalue;
+			$result=$object->update($user);
+			if ($result<0) {
+				$action = '';
+				setEventMessages($object->error,$object->errors,'errors');
+			} else {
+				setEventMessages($langs->trans("RecordSaved"), null, 'mesgs');
+				$action = "";
+				$defaulturl = '';
+				$defaultkey = '';
+				$defaultvalue = '';
+			}
 		}
 	}
 }
@@ -161,14 +177,12 @@ if (($action == 'add' || (GETPOST('add') && $action != 'update')) || GETPOST('ac
 // Delete line from delete picto
 if ($action == 'delete')
 {
-	$sql = "DELETE FROM ".MAIN_DB_PREFIX."default_values WHERE rowid = ".$db->escape($id);
-	// Delete const
-	$result = $db->query($sql);
-	if ($result >= 0)
-	{
-		setEventMessages($langs->trans("RecordDeleted"), null, 'mesgs');
-	} else {
-		dol_print_error($db);
+	$object->id=$id;
+	$result=$object->delete($user);
+	$result=$object->update($user);
+	if ($result<0) {
+		$action = '';
+		setEventMessages($object->error,$object->errors,'errors');
 	}
 }
 
@@ -323,39 +337,27 @@ print '<input type="submit" class="button"'.$disabled.' value="'.$langs->trans("
 print "</td>\n";
 print '</tr>';
 
+$result=$object->fetchAll( $sortorder, $sortfield, 0, 0, array('t.type'=>$mode,'t.entity'=>array($user->entity,$conf->entity)));
 
-// Show constants
-$sql = "SELECT rowid, entity, type, page, param, value";
-$sql .= " FROM ".MAIN_DB_PREFIX."default_values";
-$sql .= " WHERE type = '".$db->escape($mode)."'";
-$sql .= " AND entity IN (".$user->entity.",".$conf->entity.")";
-$sql .= $db->order($sortfield, $sortorder);
-
-dol_syslog("translation::select from table", LOG_DEBUG);
-$result = $db->query($sql);
-if ($result)
-{
-	$num = $db->num_rows($result);
-	$i = 0;
-
-	while ($i < $num)
+if (!is_array($result) && $result<0) {
+	setEventMessages($object->error, $object->errors,'errors');
+} else {
+	foreach($result as $key=>$defaultvalue)
 	{
-		$obj = $db->fetch_object($result);
-
 		print "\n";
 
 		print '<tr class="oddeven">';
 
 		// Page
 		print '<td>';
-		if ($action != 'edit' || GETPOST('rowid', 'int') != $obj->rowid) print $obj->page;
-		else print '<input type="text" name="urlpage" value="'.dol_escape_htmltag($obj->page).'">';
+		if ($action != 'edit' || GETPOST('rowid', 'int') != $defaultvalue->rowid) print $defaultvalue->page;
+		else print '<input type="text" name="urlpage" value="'.dol_escape_htmltag($defaultvalue->page).'">';
 		print '</td>'."\n";
 
 		// Field
 		print '<td>';
-		if ($action != 'edit' || GETPOST('rowid') != $obj->rowid) print $obj->param;
-		else print '<input type="text" name="key" value="'.dol_escape_htmltag($obj->param).'">';
+		if ($action != 'edit' || GETPOST('rowid') != $defaultvalue->rowid) print $defaultvalue->param;
+		else print '<input type="text" name="key" value="'.dol_escape_htmltag($defaultvalue->param).'">';
 		print '</td>'."\n";
 
 		// Value
@@ -367,8 +369,8 @@ if ($result)
     		print '<input type="hidden" name="const['.$i.'][name]" value="'.$obj->transkey.'">';
     		print '<input type="text" id="value_'.$i.'" class="flat inputforupdate" size="30" name="const['.$i.'][value]" value="'.dol_escape_htmltag($obj->transvalue).'">';
     		*/
-			if ($action != 'edit' || GETPOST('rowid') != $obj->rowid) print dol_escape_htmltag($obj->value);
-			else print '<input type="text" name="value" value="'.dol_escape_htmltag($obj->value).'">';
+			if ($action != 'edit' || GETPOST('rowid') != $defaultvalue->rowid) print dol_escape_htmltag($defaultvalue->value);
+			else print '<input type="text" name="value" value="'.dol_escape_htmltag($defaultvalue->value).'">';
 			print '</td>';
 		}
 
@@ -376,14 +378,14 @@ if ($result)
 
 		// Actions
 		print '<td class="center">';
-		if ($action != 'edit' || GETPOST('rowid') != $obj->rowid)
+		if ($action != 'edit' || GETPOST('rowid') != $defaultvalue->id)
 		{
-			print '<a class="editfielda marginleftonly marginrightonly" href="'.$_SERVER['PHP_SELF'].'?rowid='.$obj->rowid.'&entity='.$obj->entity.'&mode='.$mode.'&action=edit&token='.newToken().((empty($user->entity) && $debug) ? '&debug=1' : '').'">'.img_edit().'</a>';
-			print '<a class="marginleftonly marginrightonly" href="'.$_SERVER['PHP_SELF'].'?rowid='.$obj->rowid.'&entity='.$obj->entity.'&mode='.$mode.'&action=delete&token='.newToken().((empty($user->entity) && $debug) ? '&debug=1' : '').'">'.img_delete().'</a>';
+			print '<a class="editfielda marginleftonly marginrightonly" href="'.$_SERVER['PHP_SELF'].'?rowid='.$defaultvalue->id.'&entity='.$defaultvalue->entity.'&mode='.$mode.'&action=edit&token='.newToken().((empty($user->entity) && $debug) ? '&debug=1' : '').'">'.img_edit().'</a>';
+			print '<a class="marginleftonly marginrightonly" href="'.$_SERVER['PHP_SELF'].'?rowid='.$defaultvalue->id.'&entity='.$defaultvalue->entity.'&mode='.$mode.'&action=delete&token='.newToken().((empty($user->entity) && $debug) ? '&debug=1' : '').'">'.img_delete().'</a>';
 		} else {
 			print '<input type="hidden" name="page" value="'.$page.'">';
 			print '<input type="hidden" name="rowid" value="'.$id.'">';
-			print '<div name="'.(!empty($obj->rowid) ? $obj->rowid : 'none').'"></div>';
+			print '<div name="'.(!empty($defaultvalue->id) ? $obj->rowid : 'none').'"></div>';
 			print '<input type="submit" class="button" name="actionmodify" value="'.$langs->trans("Modify").'">';
 			print '<input type="submit" class="button button-cancel" name="actioncancel" value="'.$langs->trans("Cancel").'">';
 		}
@@ -393,8 +395,6 @@ if ($result)
 		print "\n";
 		$i++;
 	}
-} else {
-	dol_print_error($db);
 }
 
 print '</table>';

+ 359 - 0
htdocs/core/class/defaultvalues.class.php

@@ -0,0 +1,359 @@
+<?php
+/* Copyright (C) 2017  Laurent Destailleur <eldy@users.sourceforge.net>
+ * Copyright (C) 2021  Florian HENRY <florian.henry@scopen.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/>.
+ */
+
+/**
+ * \file        htdocs/code/class/defaultvalues.class.php
+ * \brief       This file is a CRUD class file for DefaultValues (Create/Read/Update/Delete)
+ */
+
+// Put here all includes required by your class file
+require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
+//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
+
+/**
+ * Class for MyObject
+ */
+class DefaultValues extends CommonObject
+{
+	/**
+	 * @var string ID to identify managed object.
+	 */
+	public $element = 'defaultvalues';
+
+	/**
+	 * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
+	 */
+	public $table_element = 'default_values';
+
+	/**
+	 * @var int  Does this object support multicompany module ?
+	 * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
+	 */
+	public $ismultientitymanaged = 1;
+
+	/**
+	 * @var int  Does object support extrafields ? 0=No, 1=Yes
+	 */
+	public $isextrafieldmanaged = 0;
+
+	/**
+	 * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
+	 */
+	public $picto = '';
+
+	/**
+	 *  '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.
+	 *  'arraykeyval' 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.
+	 */
+
+	// BEGIN MODULEBUILDER PROPERTIES
+	/**
+	 * @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, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
+		'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>15, 'index'=>1),
+		'type' =>array('type'=>'varchar(10)', 'label'=>'Type', 'enabled'=>1, 'visible'=>-1, 'position'=>20),
+		'user_id' =>array('type'=>'integer', 'label'=>'Userid', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25),
+		'page' =>array('type'=>'varchar(255)', 'label'=>'RelativeURL', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
+		'param' =>array('type'=>'varchar(255)', 'label'=>'Field', 'enabled'=>1, 'visible'=>-1, 'position'=>35),
+		'value' =>array('type'=>'varchar(128)', 'label'=>'Value', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
+	);
+
+	/**
+	 * @var int ID
+	 */
+	public $rowid;
+
+	/**
+	 * @var int Entity
+	 */
+	public $entity;
+
+	/**
+	 * @var string Type
+	 */
+	public $type;
+
+	/**
+	 * @var int User Id
+	 */
+	public $user_id;
+
+	/**
+	 * @var string Page
+	 */
+	public $page;
+
+	/**
+	 * @var string Param
+	 */
+	public $param;
+
+	/**
+	 * @var string Value
+	 */
+	public $value;
+	// END MODULEBUILDER PROPERTIES
+
+	/**
+	 * Constructor
+	 *
+	 * @param DoliDb $db Database handler
+	 */
+	public function __construct(DoliDB $db)
+	{
+		global $conf, $langs;
+
+		$this->db = $db;
+
+		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);
+					}
+				}
+			}
+		}
+	}
+
+	/**
+	 * Create object into database
+	 *
+	 * @param  User $user      User that creates
+	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
+	 * @return int             <0 if KO, Id of created object if OK
+	 */
+	public function create(User $user, $notrigger = false)
+	{
+		return $this->createCommon($user, $notrigger);
+	}
+
+	/**
+	 * Clone an object into another one
+	 *
+	 * @param  	User 	$user      	User that creates
+	 * @param  	int 	$fromid     Id of object to clone
+	 * @return 	mixed 				New object created, <0 if KO
+	 */
+	public function createFromClone(User $user, $fromid)
+	{
+		global $langs, $extrafields;
+		$error = 0;
+
+		dol_syslog(__METHOD__, LOG_DEBUG);
+
+		$object = new self($this->db);
+
+		$this->db->begin();
+
+		// Load source object
+		$result = $object->fetchCommon($fromid);
+		if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines();
+
+
+		// Reset some properties
+		unset($object->id);
+
+		// Create clone
+		$object->context['createfromclone'] = 'createfromclone';
+		$result = $object->createCommon($user);
+		if ($result < 0) {
+			$error++;
+			$this->error = $object->error;
+			$this->errors = $object->errors;
+		}
+
+		unset($object->context['createfromclone']);
+
+		// End
+		if (!$error) {
+			$this->db->commit();
+			return $object;
+		} else {
+			$this->db->rollback();
+			return -1;
+		}
+	}
+
+	/**
+	 * Load object in memory from the database
+	 *
+	 * @param int    $id   Id object
+	 * @param string $ref  Ref
+	 * @return int         <0 if KO, 0 if not found, >0 if OK
+	 */
+	public function fetch($id, $ref = null)
+	{
+		$result = $this->fetchCommon($id, $ref);
+		return $result;
+	}
+
+	/**
+	 * Load list of objects in memory from the database.
+	 *
+	 * @param  string      $sortorder    Sort Order
+	 * @param  string      $sortfield    Sort field
+	 * @param  int         $limit        limit
+	 * @param  int         $offset       Offset
+	 * @param  array       $filter       Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
+	 * @param  string      $filtermode   Filter mode (AND or OR)
+	 * @return array|int                 int <0 if KO, array of pages if OK
+	 */
+	public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
+	{
+		global $conf;
+
+		dol_syslog(__METHOD__, LOG_DEBUG);
+
+		$records = array();
+
+		$sql = 'SELECT ';
+		$sql .= $this->getFieldList();
+		$sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
+		if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
+		else $sql .= ' WHERE 1 = 1';
+		// Manage filter
+		$sqlwhere = array();
+		if (count($filter) > 0) {
+			foreach ($filter as $key => $value) {
+				if ($key == 't.rowid') {
+					$sqlwhere[] = $key.'='.$value;
+				} elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
+					$sqlwhere[] = $key.' = \''.$this->db->idate($value).'\'';
+				} elseif ($key == 'customsql') {
+					$sqlwhere[] = $value;
+				} elseif (is_array($value)) {
+					$sqlwhere[] = $key.' IN ('.implode(',',$value).')';
+				} else {
+					$sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
+				}
+			}
+		}
+		if (count($sqlwhere) > 0) {
+			$sql .= ' AND ('.implode(' '.$filtermode.' ', $sqlwhere).')';
+		}
+
+		if (!empty($sortfield)) {
+			$sql .= $this->db->order($sortfield, $sortorder);
+		}
+		if (!empty($limit)) {
+			$sql .= ' '.$this->db->plimit($limit, $offset);
+		}
+
+		$resql = $this->db->query($sql);
+		if ($resql) {
+			$num = $this->db->num_rows($resql);
+			$i = 0;
+			while ($i < ($limit ? min($limit, $num) : $num))
+			{
+				$obj = $this->db->fetch_object($resql);
+
+				$record = new self($this->db);
+				$record->setVarsFromFetchObj($obj);
+
+				$records[$record->id] = $record;
+
+				$i++;
+			}
+			$this->db->free($resql);
+
+			return $records;
+		} else {
+			$this->errors[] = 'Error '.$this->db->lasterror();
+			dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
+
+			return -1;
+		}
+	}
+
+	/**
+	 * Update object into database
+	 *
+	 * @param  User $user      User that modifies
+	 * @param  bool $notrigger false=launch triggers after, true=disable triggers
+	 * @return int             <0 if KO, >0 if OK
+	 */
+	public function update(User $user, $notrigger = false)
+	{
+		return $this->updateCommon($user, $notrigger);
+	}
+
+	/**
+	 * Delete object in database
+	 *
+	 * @param User $user       User that deletes
+	 * @param bool $notrigger  false=launch triggers after, true=disable triggers
+	 * @return int             <0 if KO, >0 if OK
+	 */
+	public function delete(User $user, $notrigger = false)
+	{
+		return $this->deleteCommon($user, $notrigger);
+	}
+
+	/**
+	 * Initialise object with example values
+	 * Id must be 0 if object instance is a specimen
+	 *
+	 * @return void
+	 */
+	public function initAsSpecimen()
+	{
+		$this->initAsSpecimenCommon();
+	}
+}