2

How can I check the database table for specific node entries by date before inserting a new node?

I want to check the node table for any node with the current date, if found, I want to delete the old one and insert a new node.

How can I achieve this.

2

This should do the trick:

Make a module and insert following code, switch "foo" with your module name.

    /**
    * Implements hook_node_presave($node).
    */
    function foo_node_presave($node) {
      // Lets search for nodes on the current date.
      $somedate = strtotime(date('Y-m-d'));

      $query = new EntityFieldQuery();
      $query->entityCondition('entity_type', 'node');
      $query->propertyCondition('created', $somedate, '>=');
      $query->propertyCondition('created', $somedate + (60 * 60 * 24), '<');
      $result = $query->execute();

      if (!empty($result)) {
        node_delete_multiple(array_keys($result['node']));
      }
    }

Obviously you might want to do some additional checks before deleting the nodes:

// Nodes of the same type
$query->propertyCondition('type', $node->type);

//Only delete published nodes
$query->propertyCondition('status', 1);
  • Thank you. It works. Please let me know how to get the date from the node form field instead of taking current date. – rongok Sep 3 '12 at 10:23
  • You can access the date using the $node variable. Just do a print_r($node) or dpm($node) to see its contents, then convert the date value to a Unix timestamp. – Bart Sep 3 '12 at 10:27
  • Thanks again for the suggestion. Is there any hook which run when click on save/submit the node. – rongok Sep 3 '12 at 11:05
  • @rongok Please open a new question if you have a different question. – Letharion Sep 3 '12 at 12:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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