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

评论 (写第一个评论)