I have a content type with an address field in it. My client has requested that when saving, the site should check whether another node (of the same content type) already has that address.

I.e., I want the content type to validate if and only if the address being given hasn't been used.

How do I do this? Using Drupal 6, by the way.


1 Answer 1


You should be able to use hook_nodeapi for this!

In this example I'm assuming the node type is blah

In a custom module just write something along the lines of:

function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op == 'validate' && $node->type == 'blah') {
    $sql = db_query("SELECT bl.field_address 
           FROM {content_type_blah} bl
           WHERE bl.field_address = '%s'", $node->field_address)

    if ($sql != '') {
        form_set_error($node->field_address, t('This address is already being used'));

That way, before a node is saved (during the validation) it runs an SQL query to see if the address field is duplicated anywhere else on any other node with the type blah. If it is, then it throws an error on the form field! You will need to tweak the query dependant on your table names etc.

I'm only writing that code from the top of my head, and I've not tested it (sorry) but it should definately be a starting point! I may have the $node->field_address part wrong!

If all else fails, put a die(print_r($node)); after the if ($op == 'validate'... line and you can get the right part from that!

Hope this helps :)


http://api.drupal.org/api/drupal/developer--hooks--core.php/function/hook_nodeapi/5 http://api.drupal.org/api/drupal/includes--form.inc/function/form_set_error/6

  • 1
    Rather than hardcoding the table name, you should use CCK's API to get it. You can use content_fields($field_name, $content_type_name) to get the field definition, and then pass that to content_database_info() to get both the table and column name reliably.
    – Andy
    Oct 26, 2011 at 12:49
  • Nice, hadn't thought of that! If it works then it's definately more portable/userful :)
    – Chapabu
    Oct 26, 2011 at 14:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.