1

i'm creating a unique field module which restrict a user with specific role to create one node per year. it works first but after installing some modules Automatic Nodetitles, Cancel Button, Field Permissions, View profiles permissions, More Buttons Content my custom module does not work. its hook_form_alter function works but hook_form_validate function does not work.

function uniquefield_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'target_achieved_node_form' || $form_id ==  'target_node_form') {
    $form['#validate'][]  = 'uniquefield_form_validate';
  }
}
function uniquefield_form_validate($form, &$form_state) {
  $user = user_load_by_name($form_state['values']['name']);
  if ($user) {
    if($form_state['values']['type'] == 'target_achieved' &&  in_array('vidyakjatha', $user->roles)) {
      $query = new EntityFieldQuery();
      $query->entityCondition('entity_type', 'node')
     ->entityCondition('bundle', 'target_achieved')
     ->propertyCondition('status', 1)
     ->propertyCondition('uid', $user->uid , '=');
     if ($form_state['values']['nid'] != '')
       $query->propertyCondition('nid', $form_state['values']['nid'] , '<>');
       $query->fieldCondition('field_achieved_year', 'value', $form_state['values']['field_achieved_year'][LANGUAGE_NONE][0]['value'], '=');
       $result = $query->execute();
     if (isset($result['node'])) {
       form_set_error('field_achieved_year', t('You have already added target achived status for year !year.', array('!year' => date('Y', strtotime($form_state['values']['field_achieved_year'][LANGUAGE_NONE][0]['value'])))));
     }
   }
  }
}
1
  • put the code of calling validation function and the validation function in your question.
    – M a m a D
    Jul 4, 2015 at 6:34

1 Answer 1

0

as your validating just one field - at least, it seems like it; consider using:

function uniquefield_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'target_achieved_node_form' || $form_id ==  'target_node_form') {
    $form['your_desired_field']['#element_validate']  = array('uniquefield_validate');
  }
}

on the fileds in your alter hook

2
  • where to use this line? Jul 4, 2015 at 10:02
  • i just edited the answer ;)
    – rémy
    Jul 4, 2015 at 10:43

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.