Created
March 17, 2018 20:28
-
-
Save edutrul/df029a31968b8cbe736e013cb81608d5 to your computer and use it in GitHub Desktop.
How to validate programmatically using a known constraint UniqueField
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 | |
$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()); | |
} |
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 | |
/** | |
* 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