how to make content's title unique

2019-04-07 18:50发布

问题:

I am new to drupal and i want my content title unique so is there any module available for it or if i can implement autocomplete to view my past title name. please give answer in detail

Thanks in advance :)

回答1:

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.



回答2:

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);
}