You are not logged in.

Announcement

 Téléchargez la dernière version stable de GLPI      -     Et vous, que pouvez vous faire pour le projet GLPI ? :  Contribuer
 Download last stable version of GLPI                      -     What can you do for GLPI ? :  Contribute

#1 2020-09-14 10:19:29

aizen
Member
Registered: 2020-09-14
Posts: 6

Création plugin GLPI 9.3.2

Bonjour,

Je viens d'installer GLPI 9.3.2 et je souhaiterais créer un plugin avec un formulaire custom pour gérer, sur le long terme, les coûts liés aux tickets. Avant d'aller si loin, je cherche surtout à comprendre le fonctionnement et la démarche à suivre pour créer un plugin GLPI. J'ai bien cherché sur internet les différentes documentations, mais je dois avouer que je suis un peu dans le flou.

EDIT : j'ai voulu poster les liens des différents documents que j'ai pu consulter, mais je ne suis pas autorisé à le faire.

Pour le moment, j'arrive à installer le plugin, à l'activer et à le désactiver/désinstaller. A l'installation/désinstallation, il ajoute/supprime une table dans la BDD. Jusque là, ça va, j'ai réussi à avancer. Mais je ne comprends pas comment je peux créer un formulaire et l'afficher (dans un premier temps) et par la suite, ajouter un onglet directement dans GLPI pour accéder au formulaire.

Voici mon code :

setup.php

<?php

define('TICKETCUSTOM_VERSION', '1.0.0');

/**
 * Init the hooks of the plugin - Needed
 * 
 * @return void
 */
function plugin_init_ticketcustom() {
    global $PLUGIN_HOOKS;

    //required!
    $PLUGIN_HOOKS['csrf_compliant']['ticketcustom'] = true;

    //some code here, like register class, populating PLUGIN_HOOK etc...
}

/**
 * Get the name and the version of the plugin - Needed
 * 
 * @return array
 */
function plugin_version_ticketcustom() {
    return [
        'name' => 'Ticket Custom',
        'version' => TICKETCUSTOM_VERSION,
        'author' => '',
        'license' => 'GLPv3',
        'homepage' => '',
        'requirements' => [
            'glpi' => [
                'min' => 9.1
            ],
            'php'    => [
               'min' => '7.0'
            ]
        ]
            ];
}

/**
 * Optional : check prerequisites before install : may print errors or add to messages after redirect
 * 
 * @return boolean
 */
function plugin_ticketcustom_check_prerequisites() {
    //do the check here
    
    return true;
}

/**
 * Check configuration process for plugin : need to return true if succeeded
 * Can display a message only if failure and $verbose is true
 * 
 * @param boolean $verbose Enable verbosity. Default to false
 * 
 * @return boolean
 */
function plugin_ticketcustom_check_config($verbose = false) {
    if(true) { // The configuration check
        return true;
    } 
    
    if($verbose) {
        echo "Installed, but not configured";
    }
    return false;
}

hook.php

<?php

/**
 * Install hook
 * 
 * @return boolean
 */
function plugin_ticketcustom_install() {
    //Do stuff like instanciating database, default values, ...
    global $DB;

    //Instanciate migration with version
    $migration = new Migration(100);

    //Create table only if it doesn't exist yet
    if(!$DB->tableExists("glpi_plugin_ticketcustom_configs")) {
        //Table creation query
        $query = "CREATE TABLE `glpi_plugin_ticketcustom_configs` (
            `id` INT(11) NOT NULL AUTO_INCREMENT,
            `name` VARCHAR(255) NOT NULL,
            PRIMARY KEY  (`id`)
         ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
        $DB->queryOrDie($query, $DB->error());
    }

    if($DB->tableExists("glpi_plugin_ticketcustom_configs")) {
        //Add missed value for configuration
        $migration->addField(
            'glpi_plugin_ticketcustom_configs',
            'value',
            'string'
        );

        $migration->addKey(
            'glpi_plugin_ticketcustom_configs',
            'name'
        );
    }

    //Execute the whole migration
    $migration->executeMigration();

    return true;
}

/**
 * Uninstall hook
 * 
 * @return boolean
 */
function plugin_ticketcustom_uninstall() {
    //Do stuff like removing tables, generated files, ... 
    global $DB;

    $tables = [
        'configs'
    ];

    foreach($tables as $table) {
        $tablename = 'glpi_plugin_ticketcustom_' . $table;
        //Create table only if it doesn't exist yet
        if($DB->tableExists($tablename)) {
            $DB->queryOrDie(
                "DROP TABLE `$tablename`",
                $DB->error()
            );
        }
    }

    return true;
}

config.class.php :

<?php

class TicketCustomConfig extends CommonDBTM {
    public function showForm($ID, $options = []) {
        global $CFG_GLPI;
        
        $this->initForm($ID, $options);
        $this->showFormHeader($options);

        if(!isset($options['display'])) {
            //display per default
            $options['display'] = true;
        }

        $params = $options;

        //Do not display called elements per default; they'll be displayed or returned here
        $params['display'] = false;

        $out = '<tr>';
        $out .= '<th>' . __('My label', 'ticketcustom') . '</th>';

        $objectName = autoName(
            $this->fields["name"],
            "name",
            (isset($options['withtemplate']) && $options['withtemplate'] == 2),
            $this->getType(),
            $this->fields["entities_id"]
        );

        $out .= '<td>';
        $out .= Html::autocompletionTextField(
            $this,
            'name',
            [
                'value' => $objectName,
                'display' => false
            ]
        );
        $out .= '</td>';

        $out .= $this->showFormButtons($params);
    }
}

config.php

<?php

include ("../../../inc/includes.php");

//Check if plugin is activated...
$plugin = new Plugin();
if(!$plugin->isInstalled('ticketcustom') || !$plugin->isActivated('ticketcustom')) {
    Html::displayNotFoundError();
}

//Check for ACL
if(TicketCustomConfig::canView()) {
    //View is Granted: display the list.

    //Add page header
    Html::header(
        __('Ticket Custom', 'ticketcustom'),
        $_SERVER['PHP_SELF'],
        'assets',
        'ticketcustomconfig',
        'config'
    );

    Search::show('TicketCustomConfig');

    Html::footer();
} else {
    //View is not granted
    Html::displayRightError();
}

config.form.php

<?php
include ("../../../inc/includes.php");

// Check if plugin is activated...
$plugin = new Plugin();
if (!$plugin->isInstalled('ticketcustom') || !$plugin->isActivated('ticketcustom')) {
   Html::displayNotFoundError();
}

$object = new TicketCustomConfig();

if (isset($_POST['add'])) {
    //Check CREATE ACL
    $object->check(-1, CREATE, $_POST);
    //Do object creation
    $newid = $object->add($_POST);
    //Redirect to newly created object form
    Html::redirect("{$CFG_GLPI['root_doc']}/plugins/front/config.form.php?id=$newid");
 } else if (isset($_POST['update'])) {
    //Check UPDATE ACL
    $object->check($_POST['id'], UPDATE);
    //Do object update
    $object->update($_POST);
    //Redirect to object form
    Html::back();
 } else if (isset($_POST['delete'])) {
    //Check DELETE ACL
    $object->check($_POST['id'], DELETE);
    //Put object in dustbin
    $object->delete($_POST);
    //Redirect to objects list
    $object->redirectToList();
 } else if (isset($_POST['purge'])) {
    //Check PURGE ACL
    $object->check($_POST['id'], PURGE);
    //Do object purge
    $object->delete($_POST, 1);
    //Redirect to objects list
    Html::redirect("{$CFG_GLPI['root_doc']}/plugins/front/config.php");
 } else {
    //per default, display object
    $withtemplate = (isset($_GET['withtemplate']) ? $_GET['withtemplate'] : 0);
    $object->display(
       [
          'id'           => $_GET['id'],
          'withtemplate' => $withtemplate
       ]
    );
 }

C'est tout ce que j'ai pour le moment en ayant suivi la documentation officielle. Mais là, je suis bloqué. J'aimerais donc procéder pas à pas :

- Afficher un formulaire avec des champs
- Récupérer les valeurs
- Les ajouter en BDD

Ça me servira de bonne base pour la suite des choses. Si vous avez des conseils, je suis preneur. Merci !

Last edited by aizen (2020-09-14 10:20:57)

Offline

#2 2020-10-15 11:36:54

Xamdev
Member
Registered: 2020-10-09
Posts: 6

Re: Création plugin GLPI 9.3.2

Salut aizen !
Je me permets d'up ton post, parce qu'il est super intéressant !

Je suis dans la même situation que toi pour la création d'un plugin.
As-tu trouvé la solution à ton problème ?

Est-ce que tu pourrais expliquer comment tu as réussi à afficher/à avancer dans ton plugin ?
Ce serait top, merci d'avance.

Xam.

Offline

#3 2020-10-16 17:10:14

yllen
GLPI-DEV
From: Sillery (51)
Registered: 2008-01-14
Posts: 15,278

Re: Création plugin GLPI 9.3.2

Ma doc est un peu vieille mais le principe reste le même : https://forge.glpi-project.org/projects … ePlugin084


CentOS 6.5 - CentOS 7.x
PHP 5.6 - PHP 7.x - MySQL 5.6  - MariaDB 10.2 + APC + oOPcache
GLPI from 0.72 to dev version
Certifiée ITIL (ITV2F, ITILF, ITILOSA)

Offline

Board footer

Powered by FluxBB