I'm looking for a module that will check if the current title being submitted already exists in the database and, if so, comes back with an error -- effectively preventing the submission of duplicated articles.

I can code something up but I'd first like to see if something suitable already exists.

Comments

davedelong’s picture

You could build a module along the lines of:

//unique_title.module
function unique_title_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op == 'validate') {
    $sql = "SELECT COUNT(title) as num FROM {node} WHERE title = '%s'";
    $info = db_fetch_array(db_query($sql, $node->title));
    if (intval($info['num']) > 0) {
      form_set_error('title', t('This title is already in use.  Please enter a different title'));
    }
  }
}

Edit: I just tried this, and it works great.

HTH,

Dave

nevets’s picture

A small "bug" exists in the case some edits an existing node so I think instead of

    $sql = "SELECT COUNT(title) as num FROM {node} WHERE title = '%s'";
    $info = db_fetch_array(db_query($sql, $node->title));

you want

    $sql = "SELECT COUNT(title) as num FROM {node} WHERE title = '%s' AND nid != %d";
    $info = db_fetch_array(db_query($sql, $node->title, $node->nid));

so the current node is excluded from the search

davedelong’s picture

Aha, good catch!

nvoyageur’s picture

This should work, it's very similar to what I use on my site. It will also direct the user to the original page.

//unique_title.module
function unique_title_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op == 'validate') {
    $sql = "SELECT nid,title FROM {node} WHERE title = '%s' AND nid != %d";
    if($info = db_result(db_query($sql,$node->title, $node->nid)) {
      form_set_error('title', t('This title is already in use at <a href="@node">this page</a>.', array('@node' => url("node/$info['nid']"))'));
    }
  }
}

Shane
BWCA

norio’s picture

Thanks guys! Much appreciated :)

Free Articles
Drupal Development and Design Services