how to make content's title unique

折月煮酒 提交于 2019-12-04 06:29:48

You can use http://drupal.org/project/unique_field module. It performs additional validation when a node is created or updated by a user to require that a node's title or other specified fields are unique.

Scenario #1 - Unique Node

hook_node_validate() is what you need, if you are working with Drupal 7

Either you can simply use this below mentioned code in your custom module or you can take a pull from unique_title git repository which you have to pull into your modules directory of your project and then activate the module.

/**
 * Implements hook_node_validate().
 */
function unique_title_node_validate($node, $form, &$form_state) {
  if (!isset($node->nid)) {
    $title = $form_state['values']['title'];
    $results = db_select('node')->fields('node', array('title'))->condition('title', $title, '=')->execute();
    $matches = array();
    foreach ($results as $result) {
      $matches[$result->title] = check_plain($result->title);
    }
    if (isset($matches) && !empty($matches)) {
      form_set_error('title', t('Title must be unique'));
    }
  }
}

Scenario #2 - Autocomplete Node Title

hook_form_alter() & hook_menu() can help you in this for the autocomplete of Node titles while working with Drupal 7.

Either you can simply use this below mentioned code in your custom module or you can take a pull from autocomplete git repository which you have to pull into your modules directory of your project and then activate the module.

In your custom module use the below mentioned code:

/**
 * Implementation of hook_form_alter().
 */
function module_form_alter(&$form, &$form_state, $form_id) {
  $form['title']['#autocomplete_path'] = 'unique_node_autocomplete_callback';
}

/**
 * Implements hook_menu().
 */
function module_menu() {
  $items['unique_node_autocomplete_callback'] = array(
    'page callback' => 'autocomplete_unique_node_autocomplete_callback',
    'file' => 'module.inc',
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
  );

  return $items;
}

In your module.inc file use the below mentioned AJAX callback:

/**
 * AJAX Callback
 */
function module_unique_node_autocomplete_callback($string = "") {
  $matches = array();
  if ($string) {
    $result = db_select('node')
      ->fields('node', array('nid', 'title'))
      ->condition('title', db_like($string) . '%', 'LIKE')
      ->range(0, 10)
      ->execute();
    foreach ($result as $node) {
      $matches[$node->title . " [$node->nid]"] = check_plain($node->title);
    }
  }

  drupal_json_output($matches);
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!