Require unique node title

Public

This code attaches to the node submit form and checks for other nodes with the same title. If one is found, an error is set.

Get raw version
php
  1. /**
  2.  * Helper function to check for duplicate node titles
  3.  */
  4. function _MODULE_check_duplicate_title($title, $bundle = null, $excluded_nids = null) {
  5. $query = new EntityFieldQuery;
  6. $query
  7. ->entityCondition('entity_type', 'node')
  8. ->propertyCondition('title', $title);
  9. if (!empty($bundle)) {
  10. $query->entityCondition('bundle', $bundle);
  11. }
  12. if (!empty($excluded_nids)) {
  13. $query->propertyCondition('nid', $excluded_nids, is_array($excluded_nids) ? 'NOT IN' : '!=');
  14. }
  15. return (bool) $query->range(0, 1)->count()->execute();
  16. }
  17.  
  18.  
  19.  
  20. /**
  21.  * Implement hook_form_alter for the form BUNDLE_node_form
  22.  */
  23. function MODULE_form_BUNDLE_node_form_alter(&$form, &$form_state) {
  24. $form['#validate'][] = '_MODULE_form_BUNDLE_node_form_alter_validate';
  25. }
  26.  
  27.  
  28.  
  29. /**
  30.  * Form validation for form BUNDLE_node_form
  31.  */
  32. function _MODULE_form_BUNDLE_node_form_alter_validate($form, &$form_state) {
  33. $nid = isset($form_state['node']->nid) ? $form_state['node']->nid : NULL;
  34. $type = $form_state['node']->type;
  35.  
  36. // Check for duplicate node titles
  37. $title = $form_state['values']['title'];
  38. if (_MODULE_check_duplicate_title($title, $type, $nid)) {
  39. form_set_error('title', t('A @type with the name <em>@name</em> already exists. Please choose another name.', array('@type' => $type, '@name' => $title)));
  40. }
  41. }

Comments

test's picture

But first it require nid before check but nid only creates after node is saved

thirdender's picture

The nid is pulled from the $form_state if it is available (if it is a node edit form, not a node add form). If a nid is not available, then the function _MODULE_check_duplicate_title gets NULL as the value of $excluded_nids. You can see that function also checks to make sure $excluded_nids is an array before it adds the node IDs to the database query. Basically, what the function is doing is checking to make sure there are no nodes in the database already with the node title that you're saving now. You need the nid to exclude the existing node that you are editing from that query, otherwise the function would always return false if you edited a node and didn't change the title.