You are here

unique_node_title.module in Unique Content Title 7

Alter content type and node form hooks.

File

unique_node_title.module
View source
<?php

/**
 * @file
 * Alter content type and node form hooks.
 */

/**
 * Implements hook_help().
 */
function unique_node_title_help($path, $arg) {
  switch ($path) {
    case 'admin/help#unique_node_title':
      $output = t("Unique node title module provides a facility");
      $output .= t("&nbsp;to validate uniqueness of each node of");
      $output .= t("&nbsp;specific content type.");
      $output .= t("Unique node title setting is available under");
      $output .= t("&nbsp;<em>submission form settings</em> of content type.");
      return $output;
  }
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function unique_node_title_form_node_type_form_alter(&$form, $form_state) {
  if (isset($form['type'])) {
    $form['submission']['unique_title_mode'] = array(
      '#type' => 'checkbox',
      '#title' => t('Unique title'),
      '#default_value' => variable_get('unique_title_mode_' . $form['#node_type']->type, 0),
      '#description' => t('Content title will be unique for each content type.'),
    );
  }
}

/**
 * Implements hook_form_alter().
 */
function unique_node_title_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['type']) && isset($form['#node_edit_form'])) {
    $type = $form['type']['#value'];
    $config = variable_get('unique_title_mode_' . $type, 0);
    if ($config) {
      $form['#validate'][] = 'unique_node_title_form_validate';
    }
  }
}

/**
 * Implements hook_form_validate().
 */
function unique_node_title_form_validate($form, &$form_state) {
  $node_types = array_keys(node_type_get_types());
  $config_types = array();
  $nid = 0;
  foreach ($node_types as $type) {
    $unique = variable_get('unique_title_mode_' . $type, 0);
    if ($unique) {
      $config_types[] = $type;
    }
  }
  if (!empty($form['nid']['#value'])) {
    $nid = $form['nid']['#value'];
  }
  $query = db_select('node', 'n');
  $query
    ->fields('n', array(
    'title',
  ));
  $query
    ->condition('n.type', $config_types, 'IN');
  $query
    ->condition('n.nid', $nid, '<>');
  $result = $query
    ->execute()
    ->fetchAll();
  if ($result) {
    $title = strtolower(str_replace(' ', '', $form_state['values']['title']));
    foreach ($result as $value) {
      $value->title = strtolower(str_replace(' ', '', $value->title));
      if ($value->title == $title) {
        form_set_error('title', t("<em>@title</em> is already exists.", array(
          '@title' => $form_state['values']['title'],
        )));
      }
    }
  }
}