Drupal - Prevent node from being saved in hook_node_presave
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
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!'));
I had a similar requirement, and wanted a nicer solution than simply throwing an exception. The following seemed to work well for me, in my hook_node_presave()
:
$response = new RedirectResponse(\Drupal::request()->getRequestUri());
$response->send();
drupal_set_message(t('This is my error message'), 'error', TRUE);
exit;