You are here

crm_core_relationship.install in CRM Core 8

Install, update and uninstall functions for the relationship module.

File

modules/crm_core_relationship/crm_core_relationship.install
View source
<?php

/**
 * @file
 * Install, update and uninstall functions for the relationship module.
 */
use Drupal\relation\Entity\RelationType;
use Drupal\relation\Entity\Relation;

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

  // Add default relationships.
  $relation_types_info = [
    [
      'relation_type' => 'crm_friend',
      'label' => t('Friend of'),
      'source_bundles' => [
        'crm_core_contact:individual',
      ],
      'r_unique' => TRUE,
    ],
    [
      'relation_type' => 'crm_employee',
      'label' => t('Employee of'),
      'reverse_label' => t('Employer of'),
      'directional' => TRUE,
      'r_unique' => TRUE,
      'source_bundles' => [
        'crm_core_contact:individual',
      ],
      'target_bundles' => [
        'crm_core_contact:organization',
      ],
    ],
    [
      'relation_type' => 'crm_member',
      'label' => t('Member of'),
      'reverse_label' => t('Household for'),
      'directional' => TRUE,
      'r_unique' => TRUE,
      'source_bundles' => [
        'crm_core_contact:individual',
      ],
      'target_bundles' => [
        'crm_core_contact:household',
      ],
    ],
  ];
  foreach ($relation_types_info as $relation_type_info) {
    RelationType::create($relation_type_info)
      ->save();
  }
}

/**
 * Implements hook_uninstall().
 */
function crm_core_relationship_uninstall() {

  // Get all the relationship_types (bundles), find all fields
  // delete them.
  $query = db_select('relation_bundles', 'rb')
    ->fields('rb', [
    'relation_type',
  ])
    ->condition('rb.entity_type', 'crm_core_contact')
    ->distinct()
    ->execute();
  while ($record = $query
    ->fetchAssoc()) {
    $relationship_type[] = $record['relation_type'];
  }
  foreach ($relationship_type as $type) {

    // Look into the database for each type.
    $relationship_query = db_select('relation', 'r')
      ->fields('r', [
      'relation_id',
    ])
      ->condition('r.relation_type', $type)
      ->execute();
    while ($result = $relationship_query
      ->fetchAssoc()) {

      // Delete all the relationships of that type.
      Relation::load($result['relation_id'])
        ->delete();
    }

    // Finally delete the relationshp_type.
    RelationType::load($type)
      ->delete();
  }
}