You are here

unique_field.module in Unique field 8

File

unique_field.module
View source
<?php

// query scope definitions
define('UNIQUE_FIELD_SCOPE_NODE', 'node');
define('UNIQUE_FIELD_SCOPE_TYPE', 'type');
define('UNIQUE_FIELD_SCOPE_LANGUAGE', 'language');
define('UNIQUE_FIELD_SCOPE_ALL', 'all');

// query comparison definitions
define('UNIQUE_FIELD_COMP_EACH', 'each');
define('UNIQUE_FIELD_COMP_ALL', 'all');

// query field definitions
define('UNIQUE_FIELD_FIELDS_TITLE', 'title');
define('UNIQUE_FIELD_FIELDS_AUTHOR', 'name');
define('UNIQUE_FIELD_FIELDS_LANGUAGE', 'language');

// setting definition
define('UNIQUE_FIELD_SHOW_MATCHES', 'show_matches');
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\field\Entity;
use Drupal\field\Entity\FieldConfig;
use Drupal\Core\Entity\EntityManager;
use Drupal\Core\Entity\EntityInterface;
use Drupal\node\NodeTypeInterface;
use Drupal\node\NodeInterface;

/**
 * Implements hook_help().
 */
function unique_field_help($route_name, RouteMatchInterface $route_match) {
  switch ($route_name) {
    case 'help.page.unique_field':
      $output = '<p>' . t("The Unique Field module allows administrators to require that content supplied for specified fields is unique. For example, you may require that each node has a unique title or a different author. For configuration options, please see the <em>Unique Field restrictions</em> section of a content type's administration page.") . '</p>';
      return $output;
  }
}

/**
 * Implements hook_form_alter().
 */
function unique_field_form_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id) {
  if ($form_id === 'node_type_edit_form' && \Drupal::currentUser()
    ->hasPermission('unique_field_perm_admin') && isset($form['type'])) {
    unique_field_node_settings_form($form, $form_state);
  }
  elseif (strpos($form_id, 'node_form') !== FALSE && \Drupal::currentUser()
    ->hasPermission('unique_field_perm_bypass')) {
    $form['unique_field_override'] = array(
      '#type' => 'hidden',
      '#default_value' => '0',
    );
  }
}

/**
 * Add the unique field settings form to content type forms (node_type_form).
 */
function unique_field_node_settings_form(&$form, \Drupal\Core\Form\FormStateInterface &$form_state) {
  $entity_type_id = 'node';
  $bundle = !empty($form['type']['#default_value']) ? $form['type']['#default_value'] : '';
  foreach (\Drupal::entityManager()
    ->getFieldDefinitions($entity_type_id, $bundle) as $field_name => $field_definition) {
    if (!empty($field_definition
      ->getTargetBundle())) {
      $bundleFields[$entity_type_id][$field_name]['type'] = $field_definition
        ->getType();
      $bundleFields[$entity_type_id][$field_name]['label'] = $field_definition
        ->getLabel();
    }
  }

  // load fields for content type
  $fieldopts = array();
  $fieldopts[UNIQUE_FIELD_FIELDS_TITLE] = !empty($form['submission']['title_label']['default_value']) ? check_plain($form['submission']['title_label']['default_value']) . ' (' . t('title') . ')' : t('Title');
  $fieldopts[UNIQUE_FIELD_FIELDS_AUTHOR] = t('Author');
  if (\Drupal::moduleHandler()
    ->moduleExists('language') && isset($form['language'])) {
    $fieldopts[UNIQUE_FIELD_FIELDS_LANGUAGE] = t('Language');
  }
  if (!empty($bundleFields)) {
    $fieldException = array(
      'comment',
      'image',
    );
    foreach ($bundleFields['node'] as $key => $value) {
      if (!in_array($value['type'], $fieldException)) {
        $fieldopts[$key] = $value['label'] . '(' . $key . ')';
      }
    }
  }

  /** @var \Drupal\node\NodeTypeInterface $type */
  $type = $form_state
    ->getFormObject()
    ->getEntity();
  $fields = $type
    ->getThirdPartySetting('unique_field', 'type_fields', array(
    '',
  ));

  // build the form
  $form['unique_field'] = array(
    '#type' => 'details',
    '#title' => t('Unique Field restrictions'),
    '#weight' => 1,
    '#group' => 'additional_settings',
  );
  $form['unique_field']['unique_field_fields'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Choose the fields that should be unique'),
    '#options' => $fieldopts,
    '#default_value' => $type
      ->getThirdPartySetting('unique_field', 'type_fields', array(
      '',
    )),
    '#description' => t('After designating that certain fields should be unique, users will not be able to submit the content form to create a new node or update an existing one if it contains values in the designated fields that duplicate others.'),
  );
  $form['unique_field']['unique_field_scope'] = array(
    '#type' => 'radios',
    '#title' => t('Choose the scope for the unique values'),
    '#options' => array(
      UNIQUE_FIELD_SCOPE_TYPE => t('Content type'),
      UNIQUE_FIELD_SCOPE_LANGUAGE => t('Language'),
      UNIQUE_FIELD_SCOPE_ALL => t('All nodes'),
      UNIQUE_FIELD_SCOPE_NODE => t('Single node only'),
    ),
    '#default_value' => $type
      ->getThirdPartySetting('unique_field', 'field_scope', ''),
    '#description' => t('Choose whether the values in the specified fields must be unique among nodes of this content type, among nodes of the same language, among all nodes, or only among the fields of the present node.'),
  );
  $form['unique_field']['unique_field_comp'] = array(
    '#type' => 'radios',
    '#title' => t('Choose whether values must be unique individually or in combination'),
    '#options' => array(
      UNIQUE_FIELD_COMP_EACH => t('Each of the specified fields must have a unique value'),
      UNIQUE_FIELD_COMP_ALL => t('The combination of values from the specified fields must be unique'),
    ),
    '#default_value' => $type
      ->getThirdPartySetting('unique_field', 'field_comb', ''),
    '#description' => t('For example, if you have fields for the parts of a street address (street number and name, city, and zip code) on a node, and want to allow only one node per complete address, but not only one node per city or per zip code, then you would want to choose that the fields must be unique in combination.'),
  );
  $form['unique_field']['unique_field_show_matches'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Check this box to show which nodes match when duplicate values are found'),
    '#options' => array(
      UNIQUE_FIELD_SHOW_MATCHES => t('Enabled'),
    ),
    '#default_value' => $type
      ->getThirdPartySetting('unique_field', 'show_match', array(
      '',
    )),
  );
  $form['#entity_builders'][] = 'unique_field_form_node_type_form_builder';
}

/**
 * Entity builder for the node type form with Unique field options.
 *
 * @see unique_field_node_settings_form().
 */
function unique_field_form_node_type_form_builder($entity_type, NodeTypeInterface $type, &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $type
    ->setThirdPartySetting('unique_field', 'type_fields', array_values(array_filter($form_state
    ->getValue('unique_field_fields'))));
  $type
    ->setThirdPartySetting('unique_field', 'field_scope', $form_state
    ->getValue('unique_field_scope'));
  $type
    ->setThirdPartySetting('unique_field', 'field_comb', $form_state
    ->getValue('unique_field_comp'));
  $type
    ->setThirdPartySetting('unique_field', 'show_match', array_values(array_filter($form_state
    ->getValue('unique_field_show_matches'))));
}

/**
 * Implements hook_entity_bundle_field_info_alter().
 */
function unique_field_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type
    ->id() == 'node') {
    $node_type = \Drupal\node\Entity\NodeType::load($bundle);
    $selected_fields = $node_type
      ->getThirdPartySetting('unique_field', 'type_fields', '');
    $field_scope = $node_type
      ->getThirdPartySetting('unique_field', 'field_scope', '');
    $field_comb = $node_type
      ->getThirdPartySetting('unique_field', 'field_comb', '');
    $show_match = $node_type
      ->getThirdPartySetting('unique_field', 'show_match', '');
    $options = array(
      'bundle' => $bundle,
      'fields' => $selected_fields,
      'scope' => $field_scope,
      'comb' => $field_comb,
      'match' => $show_match,
    );
    foreach ($selected_fields as $key => $field) {
      if (!empty($fields[$field])) {
        $fields[$field]
          ->addConstraint('UniqueField', $options);
      }
    }
  }
}

/**
 * Implements hook_entity_base_field_info_alter().
 */
function unique_field_entity_base_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type
    ->id() == 'node') {

    // $node_type = \Drupal\node\Entity\NodeType::load($bundle);
    // $selected_fields = $node_type->getThirdPartySetting('unique_field', 'type_fields', '');
    // foreach ($selected_fields as $key => $field) {
    //   if(!empty($fields[$field])) {
    //     $fields[$field]->addConstraint('UniqueField', []);
    //   }
    // }
  }
}