Skip to content

Instantly share code, notes, and snippets.

@briward
Last active August 21, 2018 14:23
Show Gist options
  • Save briward/732301a67f7b5193dd46be8dddf73923 to your computer and use it in GitHub Desktop.
Save briward/732301a67f7b5193dd46be8dddf73923 to your computer and use it in GitHub Desktop.
Taxonomy Term Vocabulary Exists Validation
<?php
namespace Drupal\taxonomy\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
/**
* Checks that the submitted value is a existing vocabulary.
*
* @Constraint(
* id = "VocabularyExists",
* label = @Translation("Vocabulary Exists", context = "Validation"),
* type = {"entity"}
* )
*/
class VocabularyExists extends Constraint {
// The message that will be shown if the vocabulary does not exist.
public $message = '%vocabulary does not exist';
}
<?php
namespace Drupal\taxonomy\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Validates the VocabularyExists constraint.
*/
class VocabularyExistsValidator extends ConstraintValidator {
/**
* {@inheritdoc}
*/
public function validate($items, Constraint $constraint) {
foreach ($items as $item) {
// Check if the supplied vocabulary exists.
if (!$this->exists($item->value)) {
$this->context->addViolation($constraint->message, ['%value' => $item->value]);
}
}
}
/**
* Vocabulary exists?
*
* @param string $value
*/
private function exists($value) {
return FALSE;
}
}
/**
* {@inheritdoc}
*/
public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
/** @var \Drupal\Core\Field\BaseFieldDefinition[] $fields */
$fields = parent::baseFieldDefinitions($entity_type);
$fields['tid']->setLabel(t('Term ID'))
->setDescription(t('The term ID.'));
$fields['uuid']->setDescription(t('The term UUID.'));
$fields['vid']->setLabel(t('Vocabulary'))
->setDescription(t('The vocabulary to which the term is assigned.'))
->addPropertyConstraints('value', [
'VocabularyExists'
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment