Skip to content

Instantly share code, notes, and snippets.

@slattery
Created July 28, 2022 19:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slattery/fe49761a85ae2c39e322f84e9733b5b3 to your computer and use it in GitHub Desktop.
Save slattery/fe49761a85ae2c39e322f84e9733b5b3 to your computer and use it in GitHub Desktop.
Enforces unique values for DOI in the drupal 9 bibcite module - very rough start!

Bibcite Unique Constraint DOI

Places a UniqueField constraint on the bibcite_doi field

v001

  • Implements hook_entity_base_field_info_alter() to add the constraint to the field
  • Implements hook_ENTITY_TYPE_presave() to insure validation is run during bulk imports

Dependencies

Needs the Bibliography & Citation module to work

name: 'Bibliography & Citation - Unique Constraint DOI'
type: module
description: Do not save more than one ref per DOI
core: 8.x
core_version_requirement: ^8 || ^9
package: Bibliography & Citation
dependencies:
- bibcite:bibcite
- bibcite:bibcite_entity
<?php
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
/**
* Implements hook_entity_base_field_info_alter()
* and hook_ENTITY_TYPE_presave()
*/
function bibcite_unique_constraint_doi_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
if ($entity_type->id() === 'bibcite_reference') {
if (isset($fields['bibcite_doi'])) {
$fields['bibcite_doi']->addConstraint('UniqueField');
}
}
}
function bibcite_unique_constraint_doi_bibcite_reference_presave(EntityInterface $entity) {
if ($entity->getEntityTypeId() != 'bibcite_reference') {
return;
}
$bibcitedoi = $entity->get('bibcite_doi')->value;
$violations = $entity->bibcite_doi->validate();
if (count($violations) > 0) {
throw new UnexpectedValueException("DOI '{$bibcitedoi}' exists.");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment