Warning message

Documentation is currently being migrated into the new system. Some pages might be temporarily missing, and some guides might appear empty. Thank you for your patience while we are improving Drupal.org documentation.

Making an entity fieldable

Last updated on
October 14, 2016 - 20:56

There are a number of hooks involved in making an entity fieldable. hook_entity_info provides the info (surprise!):

/**
 * Implements hook_entity_info().
 */
function privatemsg_entity_info() {
  return array(
    'privatemsg' => array(
      'label' => t('Private messages'),
      'base table' => 'privatemsg',
      'entity keys' => array(
        'id' => 'pmid',
      ),
    ),
  );
}

There are more possible keys, see the API reference for more.

Next up, we need to provide build modes:

/**
 * Implements hook_build_modes().
 */
function privatemsg_build_modes($obj_type) {
  $modes = array();
  if ($obj_type == 'privatemsg') {
    $modes = array(
      'full' => t('Full node'),
      'teaser' => t('Teaser'),
    );
  }
  return $modes;
}

Now, the rest is just calling the field attach API on load, save, form, validate and submit.

function privatemsg_load...
  // Load the message(s)
  field_attach_load('privatemsg', $array_of_messages);
function privatemsg_save($message) {
  // $message is expected to be an object, same as for drupal_write_record.
  field_attach_presave('privatemsg', $message);
  if ( /* new message */ ) {
    // Save the message.
    ...
    // And then:
    field_attach_insert('privatemsg', $message);
  }
  else {
    // Save the message.
    ...
    // And then:
    field_attach_update('privatemsg', $message);
  }