0

I would like to store some extra (meta) data about my nodes. Exactly like the promote or sticky columns in the node_field_data table.

In Drupal 7, I sometimes solved this problem by binding an extra property onto the node object. To add an extra column to the node table, I used code something like this:

/**
 * Implements hook_install().
 */
function mymodule_install() {

  // Add foo field to node table.
  $spec = array(
    'description' => 'Some description.',
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => TRUE,
    'default' => 0,
    'initial' => 0,
  );
  $keys_new['indexes'] = array('foo' => array('foo'));
  if (!db_field_exists('node', 'foo')) {
    db_add_field('node', 'foo', $spec, $keys_new);
  }
}

/**
 * Implements hook_schema_alter().
 */
function mymodule_schema_alter(&$schema) {
  $schema['node']['fields']['foo'] = array(
    'description' => 'Some description.',
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => TRUE,
    'default' => 0,
  );
}

/**
 * Implements hook_uninstall().
 */
function mymodule_uninstall() {
  db_drop_field('node', 'foo');
}

I'd then add a field to the node form and save values, on submission, with something like node_save().

I also solved the problem using a tracking table. Simply creating a custom table schema and creating some CRUD operations to alter the values in the table via a form.

For the users table there was a special column, called data, if I remember correctly, where extra user settings could be defined and stored.

What is the best way to do this in Drupal 8?

  • 1
    The best way has to be to use fields - that's literally what they're designed for. You can use hook_entity_base_field_info to provide new ones in a few lines – Clive May 9 '18 at 10:52
  • @Clive why in a comment? You provided the correct answer. – ssibal May 9 '18 at 11:06
  • No time @ssibal, hopefully someone will be able to flesh that comment out into an answer (or I'll come back to it later) – Clive May 9 '18 at 11:19
  • Do you mean use a regular field? To be clear I'm not saving 'content', which would create a new revision. It's meta data about the node. – 24ma13wg May 9 '18 at 11:43
  • A field is definitely the easiest way to go. You can add your field and then in the form display set it to disabled so it won't appear in the back end editing form for users. But you'll still be able to easily access the field value or modify the field through the CMS like any other field – Leigh May 9 '18 at 12:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.