11.6 实体验证

龹龶龴龱龯龬龪龧龦龥龡龠龟龜龛龚龙龘龔龐龏龎龌龉龇龅

龡龠龉龇龄龁龀龉龇齽齼龛齹龙齷齳龡龠龉龇API齭齬齨龅

1齠龉龇API

齞齛齗龟龜齓齐龔龐龘齏龹齎齳validate()鼴鼳龡鼯龉龇龛鼭:

$definition = DataDefinition::create('integer')
   ->addConstraint('Range', ['min' => 5]);
$typed_data = \Drupal::typedDataManager()->create($definition, 10);
$violations = $typed_data->validate();

黟黜黙龦龥龉龇黗龁龛鼭黖黓黐龦龥黏齐龉龇龛黋龉龇黇黃龅

if ($violations->count() > 0) {
   // Validation failed.
}

齞麺龥麷麶龴龛齞龔龐麳麱龴麰麳龧龦龥Range麬麫龅麨齹麺龥龟麤麢麞麝麚齨龦麖麓黟龉龇龛麐麍麋龦麖龔龐龟龜麈麄齐龉龇麬麫龅麂龦龥麷麶龛龦龥e-mail龟龜鹿麍麋鹾鹺鹸龉龇鹴鹱龎鹰e-mail鹭鹫龉龇龅麤鹪鹩齎齳$type_data->getConstraints()黜黙鹧龎鹦鹢齳齐龉龇麬麫龅

齞龟龜齓龔龐龘齏龹齎齳validate()鹠鹜龦龥Symfony龉龇鹘鹗龉龇龔龐龙鹓鹒鹐齐龛鹎鹍Symfony龉龇鹘龘齏鹦鹌鹈鹅鹍龟龜齓龔龐龅$type_data->validate()鹄鹀鸿:

return \Drupal::typedDataManager()->getValidator()->validate($typed_data);

2齠龡龠龉龇

龡龠鹾鸻鸸鹾鸻鸴龙龟龜齓齐龔龐龘齏龛鹎鸳麢鸰鸬龉龇龛鼭:

$violations = $entity->field_text->validate();

鸪龡龠鸦鹍龦龥鸤龠齭龉龇:

$violations = $entity->validate();

$violations鸣鸟鸞鸛龧龉龇黇黃齐鸗鸓齐鸒鸏龛麺龥鸒鸏鹄龘鸿龉龇鸌鸈齐鹭鼴龅麷鼭龛鼭黖鹾鸻齐龶鸇鸅($field[0]->value)龉龇黇黃龛齞鸂龦龥麷麶龴$violation->getPropertyPath()齐鸗鸓鸒鸏鹍鷽0.value鷽龛齞鸂鷻龥麷麶龴黟龙鷽field_text.0.value鷽龅

3齠鷶鹾鸻鷵鹅麬麫

鹪鹩setPropertyConstraints鼴鼳龛麤鹴鹓鼴鷴齐鷶鹾鸻鷵鹅麬麫龛鼭鷶鹾鸻鷵鹅龦龥鷲鷮鷭鷫齐麬麫鷩

$fields['name'] = BaseFieldDefinition::create('string')
  ->setLabel(t('Name'))
  ->setPropertyConstraints('value', array('Length' => array('max' => 32)));

本书共79小节:

评论 (写第一个评论)