Creating relation types programmatically

Last updated on
2 May 2019

Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites

Assisted programmatic creation

If CTools is present, an export link is provided for each relation type you have created. The export creates an object $relation_type and relation_type_create($relation_type); plus relation_type_save($relation_type); will make a relation type out of that object. The function to do so would look like this:

/**
 * Create the relation type for books <=> collection.
 */
function example_loan_create_relation_type_borrow() {
  $relation_type = new stdClass();
  $relation_type->disabled = FALSE; /* Edit this to true to make a default relation_type disabled initially */
  $relation_type->api_version = 1;
  $relation_type->relation_type = 'example_loan_relationship_type_borrow';
  $relation_type->label = 'borrows';
  $relation_type->reverse_label = 'is loaned to';
  $relation_type->directional = 1;
  $relation_type->transitive = 0;
  $relation_type->r_unique = 1;
  $relation_type->min_arity = 2;
  $relation_type->max_arity = 2;
  $relation_type->source_bundles = array(
    0 => 'user:*',
  );
  $relation_type->target_bundles = array(
    0 => 'node:libcat_book',
  );
  // Relation type create adds default keys.  It also handles casting to array.
  $relation_type = relation_type_create($relation_type);
  // Yes, in relation.module 'save' is a distinct step from 'create'.
  relation_type_save($relation_type);
}

Help improve this page

Page status: No known problems

You can: