Правило IsNull
Правило IsNull относится к классу ограничений валидации Symfony.
Оно используется для проверки того, что значение поля формы
строго равно null. В отличие от правила NotNull, которое
запрещает null, данное правило требует, чтобы значение
обязательно было null. Правило можно применять как
к свойствам сущности, так и непосредственно к полям формы.
Синтаксис
#[IsNull(message: 'text')]
Пример
Давайте создадим сущность с полем deletedAt, которое
должно быть строго null, и применим правило IsNull:
<?php
namespace AppEntity;
use SymfonyComponentValidatorConstraints as Assert;
class Article
{
#[AssertIsNull(message: 'The value must be null.')]
private ?DateTimeImmutable $deletedAt = null;
public function getDeletedAt(): ?DateTimeImmutable
{
return $this->deletedAt;
}
public function setDeletedAt(?DateTimeImmutable $deletedAt): self
{
$this->deletedAt = $deletedAt;
return $this;
}
}
?>
Пример
Давайте проверим работу правила с помощью валидатора:
<?php
namespace AppController;
use AppEntityArticle;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAttributeRoute;
use SymfonyComponentValidatorValidatorValidatorInterface;
class ArticleController extends AbstractController
{
#[Route('/article/validate', name: 'article_validate')]
public function validate(ValidatorInterface $validator): Response
{
$article = new Article();
$article->setDeletedAt(new DateTimeImmutable('2024-01-01'));
$errors = $validator->validate($article);
return new Response((string) $errors);
}
}
?>
Результат выполнения кода:
"Object(AppEntityArticle).deletedAt: The value must be null."
Пример
Давайте применим правило непосредственно к полю формы
через опцию constraints:
<?php
namespace AppForm;
use SymfonyComponentFormAbstractType;
use SymfonyComponentFormExtensionCoreTypeTextType;
use SymfonyComponentFormFormBuilderInterface;
use SymfonyComponentOptionsResolverOptionsResolver;
use SymfonyComponentValidatorConstraintsIsNull;
class ArticleType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options): void
{
$builder->add('deletedAt', TextType::class, [
'constraints' => [
new IsNull([
'message' => 'The value must be null.',
]),
],
]);
}
public function configureOptions(OptionsResolver $resolver): void
{
$resolver->setDefaults([
'data_class' => null,
]);
}
}
?>