Berdir doğru cevabı verdi, bir kısıtlamanın Drupal 8'deki bir alana doğrulama eklemeye devam etmenin doğru yolu olduğunu söyledi. İşte bir örnek.
Aşağıdaki örnekte podcast, tek değer alanına sahip bir tür düğümle çalışacağım field_podcast_duration. Bu alan için değer HH: MM: SS (saat, dakika ve saniye) olarak biçimlendirilmelidir.
Bir kısıtlama oluşturmak için iki sınıfın eklenmesi gerekir. Birincisi, kısıtlama tanımı ve ikincisi de kısıtlama doğrulayıcısıdır. Bunların her ikisi de isim alanı olan eklentilerdir Drupal\[MODULENAME]\Plugin\Validation\Constraint.
İlk olarak, kısıt tanımı. Eklenti kimliğinin, sınıfın ek açıklamasında (yorumunda) 'PodcastDuration' olarak verildiğini unutmayın. Bu daha aşağı kullanılacaktır.
namespace Drupal\[MODULENAME]\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
/**
* Checks that the submitted duration is of the format HH:MM:SS
*
* @Constraint(
* id = "PodcastDuration",
* label = @Translation("Podcast Duration", context = "Validation"),
* )
*/
class PodcastDurationConstraint extends Constraint {
// The message that will be shown if the format is incorrect.
public $incorrectDurationFormat = 'The duration must be in the format HH:MM:SS or HHH:MM:SS. You provided %duration';
}
Sonra, kısıtlayıcı doğrulayıcıyı sağlamamız gerekir. Bu sınıfın bu adı, üzerine Validatoreklenmiş olarak yukarıdan bir sınıf adı olacaktır :
namespace Drupal\[MODULENAME]\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Validates the PodcastDuration constraint.
*/
class PodcastDurationConstraintValidator extends ConstraintValidator {
/**
* {@inheritdoc}
*/
public function validate($items, Constraint $constraint) {
// This is a single-item field so we only need to
// validate the first item
$item = $items->first();
// If there is no value we don't need to validate anything
if (!isset($item)) {
return NULL;
}
// Check that the value is in the format HH:MM:SS
if (!preg_match('/^[0-9]{1,2}:[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}$/', $item->value)) {
// The value is an incorrect format, so we set a 'violation'
// aka error. The key we use for the constraint is the key
// we set in the constraint, in this case $incorrectDurationFormat.
$this->context->addViolation($constraint->incorrectDurationFormat, ['%duration' => $item->value]);
}
}
}
Son olarak, bizim kısıtlamayı kullanmak Drupal'i anlatmaya gerek field_podcast_durationilgili podcastdüğüm türü. Bunu biz yapıyoruz hook_entity_bundle_field_info_alter():
use Drupal\Core\Entity\EntityTypeInterface;
function HOOK_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
if (!empty($fields['field_podcast_duration'])) {
$fields['field_podcast_duration']->addConstraint('PodcastDuration');
}
}