Skip to content

Instantly share code, notes, and snippets.

@edutrul
Created March 17, 2018 20:28
Show Gist options
  • Save edutrul/df029a31968b8cbe736e013cb81608d5 to your computer and use it in GitHub Desktop.
Save edutrul/df029a31968b8cbe736e013cb81608d5 to your computer and use it in GitHub Desktop.
How to validate programmatically using a known constraint UniqueField
<?php
$data = [
'type' => 'article',
'title' => 'THis is an article test programmatically created',
'field_email' => [
'value' => '[email protected]'
]
];
$node = \Drupal::entityTypeManager()->getStorage('node')->create($data);
$violations = $node->validate();
// Validation failed.
if ($violations->count() > 0) {
// Display an error message helping the user fix the problem.
// These will be available indivudally in the $violations array
// and can be accessed by $violations[0]->getMessage() for each violation.
drupal_set_message($violations[0]->getMessage());
}
$node->save();
use Drupal\node\Entity\Node;
$node = Node::load(25);
$violations = $node->validate();
// Validation failed.
if ($violations->count() > 0) {
// Display an error message helping the user fix the problem.
// These will be available indivudally in the $violations array
// and can be accessed by $violations[0]->getMessage() for each violation.
drupal_set_message($violations[0]->getMessage());
}
<?php
/**
* Implements hook_entity_bundle_field_info_alter().
*/
function mymodule_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
if ($entity_type->id() === 'node' && $bundle === 'article' && !empty($fields['field_email'])) {
$fields['field_email']->addConstraint('UniqueField');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment