Last active
August 21, 2018 14:23
-
-
Save briward/732301a67f7b5193dd46be8dddf73923 to your computer and use it in GitHub Desktop.
Taxonomy Term Vocabulary Exists Validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* {@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