15

When saving / updating node, i need to validate if certain fields combination is unique. Unique field module is supposed to allow this, but that feature is not working (validating only single field). So i created my own hook:

function mymodule_node_presave(\Drupal\Core\Entity\EntityInterface $node) {

  if ($node->bundle() == 'mycontent') {

    $term = \Drupal\taxonomy\Entity\Term::load($node->get('field_mytaxonomy')->target_id);

    $query = \Drupal::entityQuery('node');
    $query->condition('type', 'mycontent');
    $query->condition('field_mydate', $node->get('field_mydate')->value, '=');
    $query->condition('field_mytaxonomy', $term->id(), '=');

    $nids = $query->execute();

    if ($nids) {
      drupal_set_message('Fields are not unique!', 'error');
      // I need to prevent saving of node here      
    }  
  }
}

Detection of node with duplicite values being created works. How do i prevent saving that node?

3 Answers 3

14

How do i prevent saving that node?

If you want to prevent that the node is saved in a presave method or hook you have to throw an exception:

throw new \Exception(t('Fields are not unique!'));

More user friendly would be to check this in the form first and give the user a chance to correct the input before you throw an exception.

Double checking this in presave is still a good idea to make sure, that no incorrect node content gets saved, no matter which form, Rest API or code is used. If someone gets past the first level of checks in the form you have no other option than to throw an exception.

Edit:

In case an exception is raised, you can replace the default 500 response with a custom error handling in an exception subscriber, see Handle database connection exception via custom handler

5
  • Ok, it stops node from being saved, save exception to DB log, but it "breaks" page with an error (The website encountered an unexpected error. Please try again later.) for front end user. Any way to modify this to return to content add page?
    – tdd
    Commented Dec 18, 2016 at 15:29
  • If it is your code that saves the entity you can enclose the ->save() method in a try/catch. - But I'm not sure if you read to complete answer. If it is a form, that is saving the data, then use form validation to prevent that the form is trying to save incorrect data.
    – 4uk4
    Commented Dec 18, 2016 at 16:11
  • An example would be a division by zero. You would tell the user in form validation, that he should not enter a zero. But if this first level of check fails, then you get an exception later. That's the same here, the check in presave should be the second level of checks and should only be raised, if something unexpected goes wrong.
    – 4uk4
    Commented Dec 18, 2016 at 16:19
  • Actually a more appropriate exception type might be EntityStorageException (or a custom subclass of it), because Entity::save() has a @throws doc declaring that this exception type can be thrown.
    – donquixote
    Commented Oct 30, 2022 at 16:20
  • 2
    @donquixote, this is not necessary. The save operation catches any exception, rollbacks the database transaction and throws an EntityStorageException with the message of the original exception and also keeps the original exception object if you need it later to react on it in an event subscriber. See drupal.stackexchange.com/a/311935/47547
    – 4uk4
    Commented Oct 30, 2022 at 16:39
7

That is not the right hook to do validations. Use hook_form_FORM_ID_alter() to add a validation function.

$form['#validate'][] = 'my_custom_validate';

Then in your custom validation function:

$term = $form_state->getValue('field_mytaxonomy');
// Your logic here.
$form_state->setErrorByName('field_mytaxonomy', t('Fields are not unique!'));
1

Ideally, for such needs - a Constraints should be implemented.

See documentation at Defining Constraints (Validations) on Entities and/or Fields

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.