Drupal drush : comment ajouter un champ lié à un vocabulaire

La solution est simple mais pas forcément évidente.

Imaginez que vous ayez un vocabulaire “MonDico”.

Dans ce dictionnaire (ou “vocabulaire“, pour reprendre l’expression Drupal), vous avez ajouté plein de mots. Enfin, pas des mots, des “termes“, pour reprendre l’expression Drupal.

Imaginez que vous vouliez créer des champs pour ce “vocabulaire“.

Voici le code qui permet de faire cela :

<?php
$vocabulary = new stdClass();
$vocabulary->name = 'PAA';
$vocabulary->description = 'Paa - Description';
$vocabulary->machine_name = 'paa';
$vocabulary->help = 'Vocabulaire related to Paa';
$vocabulary->nodes = array();
$vocabulary->weight = 0;
taxonomy_vocabulary_save($vocabulary);

$vmn = $vocabulary->machine_name;
$vvid = $vocabulary->vid;
$term = new stdClass();
$term->vid = $vvid;
$term->name = 'MonTerme';
$term->description = 'Description of terme';
$term->format = 'text';
$term->parent = 0;
$term->vocabulary_machine_name = $vmn;
taxonomy_term_save($term);

$field = array(
    'field_name' => 'test_mon_type', 
    'type' => 'text', 
);
field_create_field($field);

// Create the instance on the bundle.
$instance = array(
    'field_name' => 'test_mon_type',
    'entity_type' => 'taxonomy_term',
    'label' => 'Mon nom de champ',
    'bundle' => 'taxonomy', 
    'required' => TRUE,
    'widget' => array(
        'type' => 'textfield',
    ), 
);
field_create_instance($instance);

Rien de plus simple (mais, comme pour toute chose concernant Drupal en général) : encore fallait-il le savoir !

Post a comment

You may use the following HTML:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.