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

评论 (写第一个评论)