Récupération objet créé par formulaire

Bonjour,

Je suis entrain de progresser dans la façon de concevoir un module Dolibarr et j’essaye d’attaquer la partie concernant l’affichage de la fiche d’un objet que je viens de créer au travers d’un formulaire.

Le principe me semble simple :

Remplissage du formulaire -> validation -> création de l’objet -> récupération de l’ID dans l’URL -> affichage des attributs de l’objets via l’ID récupéré.

Je bloque sur cette dernière partie, c’est-à-dire d’afficher la fiche d’un simple objet créé par mon formulaire.

Voici mon code (card.php) :

[code]

<?php /* Copyright (C) 2017 Laurent Destailleur * Copyright (C) ---Put here your own copyright and developer email--- * * 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 . */ /** * \file htdocs/modultest/card.php * \ingroup moduletest * \brief Page to create my object */ // Load Dolibarr environment $res=0; // Try main.inc.php into web root known defined into CONTEXT_DOCUMENT_ROOT (not always defined) if (! $res && ! empty($_SERVER["CONTEXT_DOCUMENT_ROOT"])) $res=@include($_SERVER["CONTEXT_DOCUMENT_ROOT"]."/main.inc.php"); // Try main.inc.php into web root detected using web root caluclated from SCRIPT_FILENAME $tmp=empty($_SERVER['SCRIPT_FILENAME'])?'':$_SERVER['SCRIPT_FILENAME'];$tmp2=realpath(__FILE__); $i=strlen($tmp)-1; $j=strlen($tmp2)-1; while($i > 0 && $j > 0 && isset($tmp[$i]) && isset($tmp2[$j]) && $tmp[$i]==$tmp2[$j]) { $i--; $j--; } if (! $res && $i > 0 && file_exists(substr($tmp, 0, ($i+1))."/main.inc.php")) $res=@include(substr($tmp, 0, ($i+1))."/main.inc.php"); if (! $res && $i > 0 && file_exists(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php")) $res=@include(dirname(substr($tmp, 0, ($i+1)))."/main.inc.php"); // Try main.inc.php using relative path if (! $res && file_exists("../main.inc.php")) $res=@include("../main.inc.php"); if (! $res && file_exists("../../main.inc.php")) $res=@include("../../main.inc.php"); if (! $res && file_exists("../../../main.inc.php")) $res=@include("../../../main.inc.php"); if (! $res) die("Include of main fails"); include_once(DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'); //include_once(DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'); dol_include_once('/moduletest/class/myobject.class.php'); dol_include_once('/moduletest/lib/myobject.lib.php'); // Load traductions files requiredby by page $langs->loadLangs(array("moduletest@moduletest","other")); // Get parameters $id = GETPOST('id', 'int'); $ref = GETPOST('ref', 'alpha'); $action = GETPOST('action', 'alpha'); $cancel = GETPOST('cancel', 'aZ09'); $backtopage = GETPOST('backtopage', 'alpha'); // Initialize technical objects $object=new MyObject($db); $extrafields = new ExtraFields($db); $diroutputmassaction=$conf->moduletest->dir_output . '/temp/massgeneration/'.$user->id; $hookmanager->initHooks(array('myobjectcard')); // Note that conf->hooks_modules contains array // Fetch optionals attributes and labels $extralabels = $extrafields->fetch_name_optionals_label('myobject'); $search_array_options=$extrafields->getOptionalsFromPost($extralabels,'','search_'); // Initialize array of search criterias $search_all=trim(GETPOST("search_all",'alpha')); $search=array(); foreach($object->fields as $key => $val) { if (GETPOST('search_'.$key,'alpha')) $search[$key]=GETPOST('search_'.$key,'alpha'); } if (empty($action) && empty($id) && empty($ref)) $action='view'; // fetch optionals attributes and labels $extralabels = $extrafields->fetch_name_optionals_label($object->table_element); // Load object include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals /* * Actions * * Put here all code to do according to value of "action" parameter */ // If create a request if ($action == 'create') { $db->begin(); $nom = GETPOST('nom'); $prenom = GETPOST('prenom'); $datenaissance = GETPOST('datenaissance'); $adresse = GETPOST('adresse'); $country_id = GETPOST('country_id'); // We set country_id, country_code and country for the selected country $object->country_id=GETPOST('country_id')!=''?GETPOST('country_id'):$object->country_id; if ($object->country_id) { $tmparray=getCountry($object->country_id,'all'); $object->country_code=$tmparray['code']; $object->country=$tmparray['label']; } // If no name if (empty($nom)) { setEventMessages($langs->trans("Pas de nom"), null, 'errors'); $error++; $action='create'; } // If no firstname if (empty($prenom)) { setEventMessages($langs->trans("Pas de prénom"), null, 'errors'); $error++; $action='create'; } // If no datenaissance if (empty($datenaissance)) { setEventMessages($langs->trans("Pas de date de naissance"), null, 'errors'); $error++; $action='create'; } // If no adresse if (empty($adresse)) { setEventMessages($langs->trans("Pas d'adresse"), null, 'errors'); $error++; $action='create'; } // If no fk_country if (empty($country_id)) { setEventMessages($langs->trans("Pas de pays"), null, 'errors'); $error++; $action='create'; } $result = 0; if (! $error) { $object->nom = $nom; $object->prenom = $prenom; $datenaissance = dol_mktime(0, 0, 0, GETPOST('datenaissancemonth'), GETPOST('datenaissanceday'), GETPOST('datenaissanceyear')); $object->datenaissance = $datenaissance; $object->adresse = $adresse; $object->country_id = GETPOST('country_id', 'int'); $result = $object->create($user); //return int if ($result <= 0) { setEventMessages($object->errors, 'errors'); $error++; } } // If no SQL error we redirect to the request card if (! $error) { $db->commit(); $db->close(); header("Location: ".$_SERVER['PHP_SELF'].'?id='.$id); exit; } else { $db->rollback(); } } /* ************************ View *********************** */ llxHeader('', $langs->trans('Formulaire de test')); // Part to create if ($action == 'create' && ($user->rights->moduletest->creer )) { // Formulaire de test print load_fiche_titre($langs->trans('Formulaire de test'), '', 'title_hrm.png'); // Formulaire de test print ''."\n"; print ''."\n"; dol_fiche_head(); print ''; print ''; // Nom print ''; print ''; print ''; // Prenom print ''; print ''; print ''; // Date Naissance print ''; print ''; // Adresse print ''; print ''; print ''; // Country print ''; print ''; print '
'.$langs->trans("Nom").''; print ''; print '
'.$langs->trans("Prenom").''; print ''; print '
'.$langs->trans("Date de Naissance").''; echo $form->select_date(GETPOST('datenaissance'),'datenaissance',0,0,1,'form'.'datenaissance',1,0,1); print '
'.$langs->trans("Adresse").''; print ''; print '
'.fieldLabel('Country','selectcounty_id').' '; print $form->select_country((GETPOST('country_id')!=''?GETPOST('country_id'):$object->country_id),'country_id'); if ($user->admin) print info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1); print '
'; dol_fiche_end(); print '
'; print ''; print '    '; print ''; print '
'; print ''."\n"; } /* * Moduletest card */ else { if ($id > 0) { $head=product_prepare_head($object); $titre=$langs->trans("Fiche Identité".$object->type); dol_fiche_head($head, 'card', $titre, -1, $picto); $linkback = ''.$langs->trans("Retour vers Accueil").''; print '
'; print '
'; print '
'; print ''; print '
'; print ''."\n"; // Nom print ''; // Prénom print ''; // Date de naissance print ''; // Adresse print ''; // Zip print ''; // Pays print ''; print "
'; print $langs->trans("BarcodeType"); print '
'; print $langs->trans("Nom"); print ' '; print $_GET['nom']; print '
'; print $langs->trans("Prénom"); print ' '; print $_GET['prenom']; print '
'; print $langs->trans("Date de Naissance"); print ' '; print $_GET['datenaissance']; print '
'; print $langs->trans("Adresse"); print ' '; print $_GET['adresse']; print '
'; print $langs->trans("Code Postal"); print ' '; print $_GET['codepostal']; print '
'; print $langs->trans("Pays"); print ' '; print $_GET['country_id']; print '
\n"; print ''; print ''; print '
'; dol_fiche_end(); } } // End of page llxFooter();[/code] Ma question est donc : Comment je peux récupérer et afficher les informations d'un objet que je viens de créer et pour lequel j'ai pu récupérer l'ID. Egalement, dès que j'accède à mon formulaire, j'ai un message d'erreur comme quoi les champs sont vides (normal, je ne l'ai pas encore remplis), est-il possible d'enlever ce message ? D'avance merci !

Personne pour me donner un petit coup de main ? …

Bonjour :happy:
l’action d’affichage du formulaire devrait être différente de la mise a jour dans la table.
ex pour afficher le form action edit et pour valider action create

D’accord je vois, mais le point qui me bloque maintenant depuis quelques temps c’est de pouvoir récupérer les informations de l’objet créé (via son $id) et afficher cela dans une fiche. J’ai beau m’inspirer des codes existants, j’obtiens soit une page complètement blanche, soit l’environnement dolibarr sans contenu :confused:

Vérifie tes error_log php et ta fonction create

Ma fonction create n’a pas de problème puisqu’elle enregistre bien l’objet dans la BDD. C’est comment je le récupère sous forme de fiche :confused:

Ça devrait être un truc du genre :

$object=new MyObject($db);
$object->fetch($id);

$object->ref
$object->titre

etc
Si tu n’as pas de fichier de traduction tu peux ecrire directement

"Pas de date de naissance" au lieu de

[code]
$langs->trans(« Pas de date de naissance »)[/code

J’ai pris en compte tes conseils sur la différenciation ‹ edit › et ‹ create ›.

/*
 * Actions
 *
 * Put here all code to do according to value of "action" parameter
 */

// If create a request
if ($action == 'create')
{
 ...
}
/* ************************ 
 View
 *********************** */


llxHeader('',"Formulaire de test"));


// Part to create
if ($action == 'edit')
{
...
}

Et maintenant c’est la partie sur la récupération de l’objet. L’id est stocké dans l’url donc je le récupère et j’affiche ensuite les attributs de l’objet correspond à l’id.

else
{
    if ($id > 0)
    {
        $object=new MyObject($db);
        $object->fetch($id);
        dol_fiche_head($head, 'Fiche_Test', $title, -1, 'Fiche_Test');
        dol_banner_tab($object,'id');
         
        print '<div class="fichecenter">';
        print '<div class="fichehalfleft">';
         
         print '<div class="underbanner clearboth"></div>';
         print '<table class="border tableforfield" width="100%">';
         
         // Nom
         print '<tr><td class="titlefield">'."Nom".'</td>';
         print '<td>'.$object->nom.'</td>';

         print '</tr>'."\n";
         print '</table>';
         print '</div></div>';
         dol_fiche_end();
    }
}

Et j’obtiens cela :

Il faut vérifier avant tout ce que fait/renvoie ta fonction fetch()

J’ai écrit :

$head = user_prepare_head($object);
$object=new MyObject($db);
$resultat = $object->fetch($id);
print $resultat;

Mais je n’ai aucun retour écran de la variable $resultat.

Bon avec error.log il commence à y avoir du mieux, mais pas encore ca :

il te manque donc un champ date_creation

Oui je dois le rajouter, et également voir pourquoi le tableau est mal initialisé.
Sachant qu’il ne m’a pas retourné également l’attribut ‹ Nom › de mon objet

Je ne suis pas très loin, peut être que maintenant je dois prendre en compte le CSS pour gérer cela.

Apparemment l’erreur provenait du fait que j’avais une class gichehalfleft, mais pas de class fichehalfright et ficheaddleft

J’obtiens désormais ça :

Quelqu’un peut peut-être juste me dire comme récupérer le nom du pays à partir de l’ID ?

 // Pays
        print '<tr><td class="titlefield">'."Pays".'</td>';
        print '<td>'.$object->country_id.'</td>';
        print '</tr>'."\n";

Bonjour
Il faut fouiller dans la classe qui génère ton objet et voir quel champs sont retournés.

Dans la class qui créé mon objet, voici ce que j’ai :

        public $fields=array(
                'rowid'         =>array('type'=>'integer',      'label'=>'TechnicalID',      'enabled'=>1, 'visible'=>-2, 'notnull'=>1,  'index'=>1, 'position'=>1, 'comment'=>'Id'),
                'nom'           =>array('type'=>'varchar(255)', 'label'=>'Nom',              'enabled'=>1, 'visible'=>1,  'notnull'=>1,  'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Nom de la personne'),
                'prenom'        =>array('type'=>'varchar(255)', 'label'=>'Prenom',           'enabled'=>1, 'visible'=>1,  'notnull'=>1,  'index'=>1, 'position'=>20, 'comment'=>'Prenom de la personne'),
                'datenaissance' =>array('type'=>'datetime',     'label'=>'DateNaissance',    'enabled'=>1, 'visible'=>1,  'position'=>30, 'comment'=>'Date de Naissance de la personne'),
                'adresse'       =>array('type'=>'varchar(255)', 'label'=>'Adresse',          'enabled'=>1, 'visible'=>1,  'notnull'=>1, 'comment'=>'Adresse de la personne'),
                'country_id'    =>array('type'=>'integer', 'label'=>'Pays',             'enabled'=>1, 'visible'=>1,  'position'=>60, 'notnull'=>1),
                'date_creation' =>array('type'=>'datetime',     'label'=>'DateCreation',     'enabled'=>1, 'visible'=>0,  'position'=>32, 'comment'=>'Date de creation'),       
                'tms'           =>array('type'=>'datetime',     'label'=>'tms',    'enabled'=>1, 'visible'=>0,  'position'=>33, 'comment'=>'tms'),
                );

        public $rowid;
        public $nom;
        public $prenom;
        public $datenaissance;
        public $adresse;
        public $country_id;
        public $date_creation;
        public $tms;

Faut que je vois de quelle manière je peux faire apparaître non pas l’ID du pays, mais bien son label.

J’ai trouvé cette discussion ([url=www.dolibarr.fr/forum/t/ajout-dune-colonne-pays-dans-la-liste-clients/20407/1 l’obtention du label Pays à partir de l’ID, mais je me demande si je dois modifier ma requete SQL dans ce fichier : moduletestmyobject.class.php

Sachant que mon fichier possède :

function create($user, $notrigger=0)
    {
    	global $conf, $langs;
		$error=0;
		// Clean parameters
        if (isset($this->prop1)) $this->prop1=trim($this->prop1);
        if (isset($this->prop2)) $this->prop2=trim($this->prop2);
		// Check parameters
		// Put here code to add control on parameters values
        // Insert request
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."moduletest_myobject(";
		$sql.= " field1,";
		$sql.= " field2";
        $sql.= ") VALUES (";
        $sql.= " '".$this->prop1."',";
        $sql.= " '".$this->prop2."'";
		$sql.= ")";
		$this->db->begin();
	   	dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG);
        $resql=$this->db->query($sql);

J’ai personnalisé la commande sql :

function fetch($id)
    {
        global $langs;
        $sql = "SELECT";
           $sql.=" t.field1 ";
           $sql.=" t.field2 ";
           $sql.= " FROM ".MAIN_DB_PREFIX."moduletest_myobject as t";
           $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON t.country_id = c.rowid";
           $sql.= " WHERE t.rowid = ".$id;
           $sql.= " AND c.rowid=t.country_id";
        dol_syslog(get_class($this)."::fetch sql=".$sql, LOG_DEBUG);
        $resql=$this->db->query($sql);

Elle fonctionne bien dans phpmyadmin, mais impossible d’obtenir le label dans ma fiche dolibarr.

// Pays
        print '<tr><td class="titlefield">'."Pays".'</td>';
        $tmparray=getCountry($obj->country_id,'all');
        $obj->country_code=$tmparray['code'];
        print '<td>'.$obj->country=$tmparray['label'].'</td>';
        print '</tr>'."\n";