<?php
//$Id$ 
//gen openMairie le 29/12/2023 18:02

require_once "../gen/obj/om_tables.class.php";

class om_tables extends om_tables_gen {

	var $tab;
	
    var $required_field = array(
        "table_name",
    );


    function init_class_actions() {
        parent::init_class_actions();
		// modifier
        //$this->class_actions[1] = array(); // pas de méthode modifier
		
		// generer
		$this->class_actions[4] = array(
			"identifier" => "generer",
			"portlet" => array(
				"type" => "action-direct-with-confirmation",
				"libelle" => _("générer le formulaire"),
				"order" => 40,
				"class" => "copy-16",
				),
            "method" => "generer",
            "permission_suffix" => "om_tables",
            //"condition" => array(
            //    "is_valider")
			); 
			
		// supprimer script generer  
		$this->class_actions[5] = array(
			"identifier" => "supprimer_form",
			"portlet" => array(
				"type" => "action-direct-with-confirmation",
				"libelle" => _("supprimer le formulaire"),
				"order" => 45,
				"class" => "copy-16",
				),
            "method" => "supprimer_formulaire",
            "permission_suffix" => "om_tables",
            //"condition" => array(
            //    "is_formulaire_existant")
			);   
		
		// vider la table
 		$this->class_actions[6] = array(
			"identifier" => "vider",
			"portlet" => array(
				"type" => "action-direct-with-confirmation",
				"libelle" => _("vider la table"),
				"order" => 50,
				"class" => "copy-16",
				),
            "method" => "vider",
            "permission_suffix" => "om_tables",
            "condition" => array(
                "is_table_non_vide")
			);  

 		// mettre en ordre les champs en liste et form
 		$this->class_actions[7] = array(
			"identifier" => "ordre",
			"portlet" => array(
				"type" => "action-direct-with-confirmation",
				"libelle" => _("Ordre des champs par défaut"),
				"order" => 55,
				"class" => "copy-16",
				),
            "method" => "ordonner_champs",
            "permission_suffix" => "om_tables",
			);  
        
	}
	
    /**
     *
     * @return string
     */
    function get_default_libelle() {
        return $this->getVal($this->clePrimaire)."&nbsp;".$this->getVal("table_schema");
    }	


    function get_var_sql_forminc__champs() {
        return array(
            "table_name",
            "table_schema",
            "table_type",
            "comment",
            "libelle",
            "affichage",
            "nombre_colonne",
            "col1",
            "col2",
            "col3",
            "recherche",
        );
    }


	
	function setvalF($val = array()) {
        //affectation valeur formulaire
        // traitement de la clé
        // le libelle prend la valeur de la table à l origine
        parent::setvalF($val);
        if($this->getParameter('maj')==0){
			// traitement du nom de champs
			// caractères spéciaux
			// la sequence \ (echappement n est pas traitée)
			$temp = str_replace( array( '%', '@', '\'', ';', '<', '>','@','[',']',' '), '_', $val['table_name']);
			$temp = str_replace( array( '#', '{', '}','&', '$' , '£', 'µ','*','|','?',':'), '_', $temp);
			// enlever le " qui se transforme en ' ?
			// accents
			$temp = str_replace(array( 'é', 'è', 'ê'), 'e',$temp);
			$temp = str_replace(array( 'ô'), 'o',$temp);  
			$temp = str_replace(array( 'ù'), 'u',$temp);
			$temp = str_replace(array( 'à'), 'a',$temp);
			$temp = str_replace(array( 'ç'), 'c',$temp);
			// transformation en minuscule  
			$temp = strtolower($temp);
			// 1er caractère ne doit pas être un chiffre -> remplacer par "_"
			if(is_numeric(substr($temp,0,1))){
				$temp="_".(substr($temp,1,strlen($temp)-1));				
			}
			$this->valF['table_name'] = $temp;
			$this->tab->libelle=$val['table_name'];
		}
		// traitement de l'apostrophe pour comment A voir ? 
		$this->valF['col1']=str_replace("'","''",$val['col1']);
		$this->valF['col2']=str_replace("'","''",$val['col2']);
		$this->valF['col3']=str_replace("'","''",$val['col3']);
		$this->valF['libelle']=str_replace("'","''",$val['libelle']);
	}

    function setType(&$form,$maj) {
        parent::setType($form, $maj); 
        if($maj==0){
			$form->setType("libelle", "hidden");
		}      
        if($maj<2){
            $form->setType("table_schema", "hidden"); 
            $form->setType("table_type", "hidden");       
			$form->setType("nombre_colonne", "select");
			$form->setType("affichage", "select");
			$form->setType("recherche", "select");
		} 
		if($maj==3){
			if ($this->tab->nombre_colonne==1){
				$form->setType("col2", "hidden"); 
				$form->setType("col3", "hidden");       
			}
			if ($this->tab->nombre_colonne==2){
				$form->setType("col3", "hidden");        
			}
		} 
		$form->setType("comment", "hidden");  
    }

    function setOnchange(&$form, $maj) {
		//javascript controle client
        $form->setOnchange('nombre_colonne','VerifNum(this)');
    }

    function set_form_default_values(&$form, $maj, $validation) {
		// définition des paramètres par défaut
		If($maj==0){
			$form->setVal('nombre_colonne',1);
			$form->setVal('col1','colonne 1');
			$form->setVal('col2','colonne 2');
			$form->setVal('col3','colonne 3');
			$form->setVal('affichage',1);
			$form->setVal('recherche',0);
		}
		
    }


    function setLib(&$form,$maj) {
        parent :: setLib($form,$maj);
		$form->setLib('table_name',_("Nom de la table"));
		$form->setLib('table_schema',_("Nom du schema"));
		$form->setLib('table_type',_("Type de table"));
		$form->setLib('comment',_("paramètres"));
		$form->setLib('nombre_colonne',_("nombre de colonnes"));
		$form->setLib('col1',_("libellé colonne 1"));
		$form->setLib('col2',_("libellé colonne 2"));
		$form->setLib('col3',_("libellé colonne 3"));
		$form->setLib('affichage',_("affichage en menu"));
		$form->setLib('libelle',_("libellé de la table"));
		$form->setLib('recherche',_("moteur de recherche"));
	}

    function setSelect(&$form, $maj, &$dnu1 = NULL, $dnu2 = NULL) {
        parent :: setSelect($form, $maj, $dnu1, $dnu2);
        if($maj<2){
            // nombre colonnes
            $contenu=array();
            $contenu[0]=array('1','2','3');
            $contenu[1]=array('1 colonne','2 colonnes','3 colonnes');
            $form->setSelect("nombre_colonne",$contenu);
            // affichage
            $contenu=array();
            $contenu[0]=array('1','0');
            $contenu[1]=array('afficher en menu',"pas d'affichage'");
            $form->setSelect("affichage",$contenu);
            // recherche
            $contenu=array();
            $contenu[0]=array('0','1');
            $contenu[1]=array('sans',"avec");
            $form->setSelect("recherche",$contenu);
		}
	}





	// création de la table et de la clé primaire (= le nom de la table)
	// création des paramètres en comment
    function ajouter($val = array(), &$dnu1 = null, $dnu2 = null) {		
        // Begin
        $this->begin_treatment(__METHOD__);
        // Mutateur de valF
        $this->setValF($val);
        // verifier
        // si le nom de la table n'existe pas
        $this->verifier($val, $this->f->db, null);
        //$this->setValFAjout($val); -> ne marche pas et pas de remontée de messages -> mis en verifier()
        if ($this->correct) {
			// creation de la table + clé primaire			
			$sql  = "create table ".DB_PREFIXE.$this->valF['table_name']." ( ";
			$sql .= $this->valF['table_name']." integer not null, ";
			$sql .= " PRIMARY KEY (".$this->valF['table_name']."))";			 
			$res = $this->f->db->query($sql);			
			if ($this->f->isDatabaseError($res, true)) {
				// Appel de la methode de recuperation des erreurs
				$this->addToMessage($this->valF['table_name']." ".__("Table non créé")." ".$sql);
				$this->addToMessage($res->getDebugInfo());
				$this->correct = false;
				// Return
				return $this->end_treatment(__METHOD__, false);
			}else{
				// parametres supplementaires en om_tables_parametre			
				$this->tab->col1 = $val['col1'];
				$this->tab->col2 = $val['col2'];
				$this->tab->col3 = $val['col3'];
				$this->tab->affichage = $val['affichage'];
				$this->tab->nombre_colonne = $val['nombre_colonne'];
				$this->tab->recherche = $val['recherche'];
				$insert=json_encode($this->tab);
				// version 2 en comment -> eventuellement à rajouter dans un champ texte
				//$sql  = "comment on table ".DB_PREFIXE.$this->valF['table_name']." IS ";
				$sql = "insert into ".DB_PREFIXE."om_tables_parametre ";
				$sql .= " VALUES ( '".$this->valF['table_name']."',";
				$sql .= "'".$insert."')";
				$res2 = $this->f->db->query($sql);
				if ($this->f->isDatabaseError($res2, true)) {
					// Appel de la methode de recuperation des erreurs
					$this->addToMessage($this->valF['table_name']." "
						.__("les paramètres ne sont pas  créés en om_tables_parametre"));
					$this->addToMessage($res2->getDebugInfo());
					$this->correct = false;
					// Return
					return $this->end_treatment(__METHOD__, false); 
				}else				
					$this->addToMessage("".__("les paramètres da la table par défaut dans om_tables_parametre")."");
				
				// Execution du trigger 'after' specifique au MODE 'insert'
                // Le premier parametre est vide car en MODE 'insert'
                // l'enregistrement n'existe pas encore donc il n'a pas
                // d'identifiant
                if($this->triggerajouterapres($this->valF[$this->clePrimaire], $this->f->db, $val, null) === false) {
                    $this->correct = false;
                    $this->addToLog(__METHOD__."(): ERROR", DEBUG_MODE);
                    // Return
                    return $this->end_treatment(__METHOD__, false);
                }
				$this->addToMessage("creation table ".$this->valF['table_name']);
			} 
		}else {
            // Message d'echec (saut d'une ligne supplementaire avant le
            // message pour qu'il soit mis en evidence)
            $this->addToMessage("<br/>".__("Table non créé")."<br/>");
            $this->addToLog(__METHOD__."(): ".$message, VERBOSE_MODE);
            // Return
            return $this->end_treatment(__METHOD__, false);
        }	
        return $this->end_treatment(__METHOD__, true);
    }
    
	// en modifier : modification uniquement des paramètres du commentaire
	function modifier($val = array(), &$dnu1 = null, $dnu2 = null) {
       // Begin
        $this->begin_treatment(__METHOD__);
        // Mutateur de valF
        $this->setValF($val);
        // verifier si existe des champs     
        $this->verifier($val, $this->f->db, null);
        if ($this->correct) {
			// modifier		
			$this->tab->col1 = $this->valF['col1'];
			$this->tab->col2 = $this->valF['col2'];
			$this->tab->col3 = $this->valF['col3'];
			$this->tab->libelle =$this->valF['libelle'];
			$this->tab->affichage = $val['affichage'];
			$this->tab->nombre_colonne = $val['nombre_colonne'];
			$this->tab->recherche = $val['recherche'];
			$insert=json_encode($this->tab);
			// $insert = $this->tab;
			// pas de mise à jour du comment version 2
			//$sql  = "comment on table ".DB_PREFIXE.$this->valF['table_name']." IS ";
			$sql .= "update ".DB_PREFIXE."om_tables_parametre set parametres = ";
			$sql .= "'".$insert."'";
			$sql .= " where table_name = '".$this->valF['table_name']."'";
			
			$res = $this->f->db->query($sql);    
			if ($this->f->isDatabaseError($res, true)) {
				// Appel de la methode de recuperation des erreurs
				$this->addToMessage($res->getDebugInfo());
				$this->erreur_db($res->getDebugInfo(), $res->getMessage(), '');
				$this->correct = false;
				// Return
				return $this->end_treatment(__METHOD__, false);
			}else{
				$this->addToMessage("modification de la table ".$this->valF['table_name']);
                if($this->triggermodifierapres($id, $this->f->db, $val, null) === false) {
                    $this->correct = false;
                    $this->addToLog(__METHOD__."(): ERROR", DEBUG_MODE);
                    // Return
                    return $this->end_treatment(__METHOD__, false);
                } 	
			} 				
		}else {
            // Message d'echec (saut d'une ligne supplementaire avant le
            // message pour qu'il soit mis en evidence)
            $this->addToMessage("<br/>".__("modification non effectués")."<br/>");
            $message = __("table non modifiée");
            $this->addToLog(__METHOD__."(): ".$message, VERBOSE_MODE);
            // Return
            return $this->end_treatment(__METHOD__, false);
        }	
        return $this->end_treatment(__METHOD__, true);      
    }



    
   // drop  table supprime index, règle, déclencheur ou contrainte qui existe sur la table cible.
   // sauf : la sequence, l'om_droit et le formulaire 
   // ne vérifie pas que la table est vide
   // comment est supprimé
   function supprimer($val = array(), &$dnu1 = null, $dnu2 = null) {
        // Begin
        $this->begin_treatment(__METHOD__);
        // Mutateur de valF
        $this->setValF($val);
        // verifier si existe des champs 
        $this->verifier($val, $this->f->db, null);
        if ($this->correct) {
			// destruction de la table -> CASCADE ?
			$sql  = "drop table ".DB_PREFIXE.$this->valF['table_name']." ";
			$res = $this->f->db->query($sql);    
			if ($this->f->isDatabaseError($res, true)) {
				// Appel de la methode de recuperation des erreurs
				$this->addToMessage($res->getDebugInfo());
				$this->correct = false;
				// Return
				return $this->end_treatment(__METHOD__, false);
			}else{
                if($this->triggersupprimerapres($id, $this->f->db, $val, null) === false) {
                    $this->correct = false;
                    $this->addToLog(__METHOD__."(): ERROR", DEBUG_MODE);
                    // Return
                    return $this->end_treatment(__METHOD__, false);
                }
				$this->addToMessage("destruction de la table ".$this->valF['table_name']);
			} 
		}else {
            // Message d'echec (saut d'une ligne supplementaire avant le
            // message pour qu'il soit mis en evidence)
            $this->addToMessage("<br/>".__("destruction de la table ")." ".
								$this->valF['table_name']." ".__("non effectué"));
            $this->addToLog(__METHOD__."(): ".$message, VERBOSE_MODE);
            // Return
            return $this->end_treatment(__METHOD__, false);
        }	
        return $this->end_treatment(__METHOD__, true);
    }
 
    function verifier($val = array(), &$dnu1 = null, $dnu2 = null) {
		parent::verifier($val, $dnu1, $dnu2);
		if($this->getParameter('maj')==0){ // ajouter
			// clé non vide
			if ($this->valF[$this->clePrimaire] == "") {
				$this->correct = false;
				$this->addToMessage( __("L'\"identifiant\" est obligatoire")."&nbsp;");
				$this->addToMessage("[&nbsp;".__($this->clePrimaire)."&nbsp;]");
			}
			// la clé doit être différente
			if ($this->typeCle == "A") {
				$sql = "select count(*) from ".DB_PREFIXE.$this->table." ";
				$sql .= "where ".$this->clePrimaire."='".$this->valF[$this->clePrimaire]."' ";
				// Exécution de la requête
				$nb = $this->f->db->getone($sql);
				// Logger
				$this->addToLog(__METHOD__."(): db->getone(\"".$sql."\");", VERBOSE_MODE);
				// Vérification d'une éventuelle erreur de base de données
				$this->f->isDatabaseError($nb);
				//
				if ($nb > 0) {
					$this->correct = false;
					$this->addToMessage($nb." ");
					$this->addToMessage( __("cle primaire existante"));
					$this->addToMessage(" ".$this->table."<br />");
				}
			}
		}

		if($this->getParameter('maj')==2){ // supprimer
			// la table doit être vidée
			$sql  = "select count(*) from ".DB_PREFIXE.$this->valF['table_name'];	
			$res=  $this->f->db->getOne($sql);
			$this->addToLog("vider() : db->query(\"".$sql."\")", VERBOSE_MODE);
			if ($this->f->isDatabaseError($res, true)) {
				$this->addToMessage($res->getDebugInfo());
			}else{
				if($res>0){
					$this->correct = false;
					$this->addToMessage(_("Il y a")." ".$res." "._("enregistrement(s)"));
					$this->addToMessage(_("Vous devez vider la table")." ".$this->valF['table_name'].
						" "._("avant de la détruire"));
				}
			} 
			// le formulaire doit être détruit 
			$path_to_file="../gen/obj/".$this->valF['table_name'].".class.php";
			if(file_exists($path_to_file)) {
                $this->addToMessage(__('Formulaire existant à détruire')." : ".$path_to_file);
                $this->correct = false; 
            }
			$path_to_file="../gen/sql/pgsql/".$this->valF['table_name'].".inc.php";
			if(file_exists($path_to_file)) {
                $this->addToMessage(__('Liste existante à détruire')." : ".$path_to_file);
                $this->correct = false; 
            }
		}
	}
 
    
    function triggerajouterapres($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
		// recherche du profil de l'utilisateur
		$sql  = "select om_profil from ".DB_PREFIXE."om_utilisateur ";
		$sql .= " where login = '".$_SESSION['login']."'";		
		$profil=  $this->f->db->getOne($sql);
		$this->addToLog("triggerajouterapres() : db->getOne(\"".$sql."\")", VERBOSE_MODE);
		if ($this->f->isDatabaseError($res, true)) {
			$this->addToMessage($res->getDebugInfo());
		}
		// insert du droit (si il existe -> message d'erreur)  		
		$sql  = "insert into ".DB_PREFIXE."om_droit (om_droit, libelle, om_profil) VALUES";
		$sql .= "(nextval('".DB_PREFIXE."om_droit_seq'), '".$this->valF['table_name']."','".$profil."')";
		$res  =  $this->f->db->query($sql);
		$this->addToLog("triggerajouterapres() : db->query(\"".$sql."\")", VERBOSE_MODE);
		if ($this->f->isDatabaseError($res, true)) {
			$this->addToMessage($res->getDebugInfo());
		}else 		
			$this->addToMessage(_("creation om_droit")." ".$_SESSION['login']." ".$profil);
			
		// creation de sequence 		
		$sql  = "create sequence ".DB_PREFIXE.$this->valF['table_name']."_seq ";
		$sql .= " START WITH 1 ";
		$sql .= " INCREMENT BY 1 ";
        $sql .= " NO MINVALUE ";
		$sql .= " NO MAXVALUE ";
        $sql .= " CACHE 1 ";
		$res  =  $this->f->db->query($sql);
		$this->addToLog("triggerajouterapres() : db->query(\"".$sql."\")", VERBOSE_MODE);
		if ($this->f->isDatabaseError($res, true)) {
			$this->addToMessage($res->getDebugInfo());
		}else 		
			$this->addToMessage(_("creation sequence")." ".$this->valF['table_name']."_seq ");
    }

    function triggersupprimerapres($id, &$dnu1 = null, $val = array(), $dnu2 = null) {
		// destruction de la sequence
		$sql  = "drop sequence if exists ".DB_PREFIXE.$this->valF['table_name']."_seq";
		$res  =  $this->f->db->query($sql);
		$this->addToLog("triggersupprimerapres() : db->query(\"".$sql."\")", VERBOSE_MODE);
		if ($this->f->isDatabaseError($res, true)) {
			$this->addToMessage($res->getDebugInfo());
		}else 		
			$this->addToMessage(_("suppression sequence")." ".DB_PREFIXE.$this->valF['table_name']."_seq");
		// destruction des om_droits
		$sql  = "delete from ".DB_PREFIXE."om_droit ";
		$sql .= " where libelle = '".$this->valF['table_name']."'";
		$res  =  $this->f->db->query($sql);
		$this->addToLog("triggersupprimerapres() : db->query(\"".$sql."\")", VERBOSE_MODE);
		if ($this->f->isDatabaseError($res, true)) {
			$this->addToMessage($res->getDebugInfo());
		}else 		
			$this->addToMessage(_("suppression om_droit")." ".DB_PREFIXE.$this->valF['table_name']." effectué");
		// destruction d'om_tables_parametre
		$sql  = "delete from ".DB_PREFIXE."om_tables_parametre";
		$sql  .= " where table_name = '".$this->valF['table_name']."'";
		$res  =  $this->f->db->query($sql);
		$this->addToLog("triggersupprimerapres() : db->query(\"".$sql."\")", VERBOSE_MODE);
		if ($this->f->isDatabaseError($res, true)) {
			$this->addToMessage($res->getDebugInfo());
		}else 		
			$this->addToMessage(_("suppression enregistrement om_tables_parametre pour")." ".DB_PREFIXE.$this->valF['table_name']."");		
		// destruction d'om_forms
		$sql  = "delete from ".DB_PREFIXE."om_forms";
		$sql  .= " where SPLIT_PART(om_forms.column_name, '.', 1) = '".$this->valF['table_name']."'";
		$res  =  $this->f->db->query($sql);
		$this->addToLog("triggersupprimerapres() : db->query(\"".$sql."\")", VERBOSE_MODE);
		if ($this->f->isDatabaseError($res, true)) {
			$this->addToMessage($res->getDebugInfo());
		}else 		
			$this->addToMessage(_("suppression enregistrement om_forms pour")." ".DB_PREFIXE.$this->valF['table_name']."");		
    }


	// =======
	// actions
	// =======
	
	// generation des 2 fichiers principaux
	// methode on table_obj_class_gen ../gen/obj/"table".class.php 
	// methode on table_sql_inc_gen ../gen/sql/pgsql/"table".inc.php
	// la génération créé la sequence 	
	function generer(){
		$table = $this->getParameter('idx');
        $om_gen = $this->f->get_inst__om_gen();
        $om_gen->init_generation_for_table($table);
        $params = $om_gen->get_gen_parameters();
        if ($om_gen->is_generable() != true) {
			$this->addToMessage($table." "._("n'est pas generable")); 
			die();
		}else{
			$this->addToMessage($table." "._("est generable"));
		}
		// suppression
		$path = "../gen/sql/pgsql/".$table.".inc.php";
		$om_gen->ecrirefichier(
			$path,
			$om_gen->table_sql_inc_gen()
        );
        $path = "../gen/obj/".$table.".class.php";
		$om_gen->ecrirefichier(
			$path,
			$om_gen->table_obj_class_gen()
        );
        $this->f->displayMessage("valid", $om_gen->msg);
	}

	// supprimer  les 2 fichiers générés pour liste et formulaire
	// ../gen/obj/"table".class.php 
	// ../gen/sql/pgsql/"table".inc.php	
	function supprimer_formulaire(){
		$table = $this->getParameter('idx');
        $om_gen = $this->f->get_inst__om_gen();
        $path = "../gen/sql/pgsql/".$table.".inc.php";
        $om_gen->supprimerfichier($path);
        $path = "../gen/obj/".$table.".class.php";
        $om_gen->supprimerfichier($path);
        // Affichage du message de validation du traitement
        $this->f->displayMessage("valid", $om_gen->msg);        
	}

	// vider la table
	// nécessaire avant DROP table
	function vider(){
		$table = $this->getParameter('idx');
		$sql  = "delete from ".DB_PREFIXE.$table;	
		$res=  $this->f->db->query($sql);
		$this->addToLog("vider() : db->query(\"".$sql."\")", VERBOSE_MODE);
		if ($this->f->isDatabaseError($res, true)) {
			$this->addToMessage($res->getDebugInfo());
		}else{
			$this->f->db->commit();
			$this->addToMessage(_("table")." ".$table." "._("vidée"));
		}
	}

	function ordonner_champs(){
		$table = $this->getParameter('idx');
		$this->addToMessage(_("remise en ordre des champs par défaut"));
		// position en formulaire 
		$sql = " select om_forms.column_name, om_forms.table_name, data_type, ";
		$sql .= " parametres->>'bloc' as bloc, parametres->>'position' as position, "; 
		$sql .= " parametres->>'type' as type ";
		$sql .= " FROM ".DB_PREFIXE."om_forms left join ".DB_PREFIXE."om_champs ";
		$sql .= " on om_champs.column_name=om_forms.column_name ";
		$sql .= " where om_forms.table_name = '".$table."'"; 
		//$this->addToMessage($sql);	
		$res = $this->f->db->query($sql);
		$this->f->addToLog("app/om_champs_class.php: db->query(".$sql."\", ".print_r($temp, true).");", DEBUG_MODE);
		$this->f->isDatabaseError($res);
		$position=0;
		$bloc= 'C1';
		$this->addToMessage("<b>"._("formulaire")."</b>");
		while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC)) {
			$position++;			
			// update bloc 
			$sql = " update ".DB_PREFIXE."om_forms set parametres = jsonb_set(parametres, '{bloc}', '\"".$bloc."\"')";
			$sql .= " WHERE column_name = '".$row['column_name']."'" ; 
			$res3 = $this->f->db->query($sql);    
			$this->f->addToLog(__METHOD__."(): mode update(\"".$sql."\", ".print_r($temp, true).");", DEBUG_MODE);
			$this->f->isDatabaseError($res3);
			// update position
			$sql = " update ".DB_PREFIXE."om_forms set parametres = jsonb_set(parametres, '{position}', '\"".$position."\"')";
			$sql .= " WHERE column_name = '".$row['column_name']."'" ; 
			$res2 = $this->f->db->query($sql);    
			$this->f->addToLog(__METHOD__."(): mode update(\"".$sql."\", ".print_r($temp, true).");", DEBUG_MODE);
			$this->f->isDatabaseError($res2);			
			$this->addToMessage(" - ".$row['column_name']." : "._("position")." -> ".$position." | "._("bloc")." -> ".$bloc);
		}
		// position en liste
		//$this->addToMessage($position." ".intval($res));		
		$sql = " select om_forms.column_name, om_forms.table_name, data_type, ";
		$sql .= " parametres->>'position_liste' as position_liste, "; 
		$sql .= " parametres->>'type' as type, parametres->>'liste' as liste ";
		$sql .= " FROM ".DB_PREFIXE."om_forms left join ".DB_PREFIXE."om_champs ";
		$sql .= " on om_champs.column_name=om_forms.column_name ";
		$sql .= " where om_forms.table_name = '".$table."' and parametres->>'liste'='1' "; 
		//$this->addToMessage($sql);	
		$res = $this->f->db->query($sql);
		$this->f->addToLog("app/om_champs_class.php: db->query(".$sql."\", ".print_r($temp, true).");", DEBUG_MODE);
		$this->f->isDatabaseError($res);
		$position=0;
		$this->addToMessage("<b>"._("liste")."</b>");
		$this->f->db->autoCommit(false);			
		while ($row =& $res->fetchRow(DB_FETCHMODE_ASSOC)) {					
			$position++;			
			// update position
			$sql = " update ".DB_PREFIXE."om_forms set parametres = jsonb_set(parametres, '{position_liste}', '\"".$position."\"')";
			$sql .= " WHERE column_name = '".$row['column_name']."'" ; 
			// $this->addToMessage($sql);
			$res2 = $this->f->db->query($sql);    
			//$this->f->addToLog(__METHOD__."(): mode update(\"".$sql."\", ".print_r($temp, true).");", DEBUG_MODE);
			$this->f->isDatabaseError($res2);
			$this->addToMessage(" - ".$row['column_name']." : "._("position")." -> ".$position); 	 
		}
		$this->db->commit();		

	}
	

}
