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小节:

评论 (写第一个评论)