I am using hook_node_presave to add this validation and its working fine for most of the scenario.

But sometime, this validation is not working so duplicate node is generated.

I am using following code Using node_presave

 * Implementing hook_node_validate
function sample_changes_node_presave($node) {
  if ($node->type == 'daily') {
    global $user;
    $userdata = user_load($user->uid);
    $cid = $userdata->field_profile_center['und'][0]['target_id'];
    $dated = date("Y-m-d", strtotime($node->field_daily_report_date["und"][0]["value"]));
    if (empty($node->nid) && (daily_report_exist($dated, $cid) == TRUE)) {
      drupal_set_message(t('Daily Report is already Created for this date.'), 'error');

Where daily_report_exist() is Boolean function to return TRUE/FALSE.

Using form_alter

 * Implaments hook_form_alter.
function sample_changes_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'daily_node_form') {
array_unshift($form['#validate'], 'daily_report_exist_validation');

function daily_report_exist_validation($form, &$form_state) {
   if (is_duplicate($form, $form_state)) {
      form_set_error('title', 'Daily Report is already Created for this date.');

Where is_duplicate is Boolean function to return TRUE/FALSE same as daily_report_exist(). One thing i also notice, whenever validation failed and duplicate node is created, the node-created time difference is only 1 or 2 sec.

May be someone help me to fix this.

  • 2
    This is not a right way to apply a validation. Have you tried adding validate function using HOOK_form_alter ? – Shubham Mar 17 '16 at 9:30
  • Yes, i also added same validation with array_unshift($form['#validate'], 'daily_report_exist_validation'); in HOOK_form_alter – visabhishek Mar 17 '16 at 9:54
  • Is that worked? – Shubham Mar 17 '16 at 9:57
  • Yes both validation is working fine, individually (in Presave and form alter). Me and my QA team is also tested properly. But after some time while we are checking the reports on production site we have some duplicate nodes. which is unexpected. That is the thing i want to figure out. – visabhishek Mar 17 '16 at 10:03
  • First thing is use form_set_error instead of drupal_set_message when you are applying the validation using form_alter. Second thing is please make sure you are not resubmitting the node object 2 times. – Shubham Mar 17 '16 at 10:06

Your Answer

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

Browse other questions tagged or ask your own question.