forms - Symfony 检查表单验证时两个字段中是否至少有一个不为空

标签 forms constraints symfony4

我已经在我的脑海中扭转了很长一段时间,但仍然无法找到解决我的问题的方法。使用 Symfony 4 表单和约束我无法设置一个检查来说明在提交包含子表单的表单时至少两个字段中的一个不能为空。

我有一个 Booking 实体,其中包含一个 Visitor 实体,该实体具有一个 phoneNumber 属性和一个 email 属性。我希望能够创建一个具有“访问者”CollectionType 的 Booking(允许我从 BookingType 表单添加访问者)。

我的 BookingType 表单(有点简化):

class BookingType extends AbstractType
{
    private $router;
    private $translator;

    public function __construct(UrlGeneratorInterface $router, TranslatorInterface $translator)
    {
        $this->router = $router;
        $this->translator = $translator;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('bookableTimeSlot', EntityType::class, [
                'label' => 'entity.booking.bookable-time-slot',
                'class' => BookableTimeSlot::class,
                'choice_label' => function ($bookableTimeSlot) {
                    return $bookableTimeSlot->getStartDateTime()->format('d.m.Y h\hi');
                }
            ])
            ->add('visitors', CollectionType::class, [
                'entry_type' => VisitorType::class,
                'label' => 'entity.booking.visitors',
                'allow_add' => true,
                'by_reference' => false,
                'entry_options' => ['label' => false]
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Booking::class,
            'user' => User::class,
        ]);
    }
}

我的访客实体(有点简化):

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

/**
 * @ORM\Entity(repositoryClass="App\Repository\VisitorRepository")
 */
class Visitor
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $firstName;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $lastName;

    /**
     * @ORM\Column(type="string", length=45, nullable=true)
     */
    private $phone;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Booking", inversedBy="visitors")
     * @ORM\JoinColumn(nullable=false)
     */
    private $booking;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $email;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getFirstName(): ?string
    {
        return $this->firstName;
    }

    public function setFirstName(string $firstName): self
    {
        $this->firstName = $firstName;

        return $this;
    }

    public function getLastName(): ?string
    {
        return $this->lastName;
    }

    public function setLastName(string $lastName): self
    {
        $this->lastName = $lastName;

        return $this;
    }

    public function getPhone(): ?string
    {
        return $this->phone;
    }

    public function setPhone(string $phone): self
    {
        $this->phone = $phone;

        return $this;
    }

    public function getBooking(): ?Booking
    {
        return $this->booking;
    }

    public function setBooking(?Booking $booking): self
    {
        $this->booking = $booking;

        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(?string $email): self
    {
        $this->email = $email;

        return $this;
    }
}

最后我的 VisitorType 表单(有点简化):

class VisitorType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstName', TextType::class, [
                'label' => 'entity.visitor.first-name',
            ])
            ->add('lastName', TextType::class, [
                'label' => 'entity.visitor.last-name',
            ])
            ->add('phone', TextType::class, [
                'label' => 'entity.visitor.phone-number',
                'required' => false,
            ])
            ->add('email', TextType::class, [
                'label' => 'entity.visitor.email',
                'required' => false,
                'constraints' => [
                    new Email()
                ]
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Visitor::class,
        ]);
    }
}

我尝试向电子邮件和电话字段添加表达式约束,如下所示:
new Expression([
    'expression' => 'this.getPhone() == null && this.getEmail() == null'
])

还尝试直接向实体添加约束,但对我来说似乎没有任何效果。

任何帮助将不胜感激。

更新
我没有指定这一点,但我的问题来自这样一个事实,即我想从另一个表单中验证 VisitorType 表单,该表单将 VisitorType 添加为 CollectionType。

最佳答案

尝试回调

/**
 * @Assert\Callback
 */
public function validate(ExecutionContextInterface $context, $payload)
{

    if (null === $this->getEmail() && null === $this->getPhone())
        $context->buildViolation('Your message here.')
            ->atPath('email')
            ->addViolation();

   // you can add onther "if" if you like

}

关于forms - Symfony 检查表单验证时两个字段中是否至少有一个不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60720662/

相关文章:

php - 文件类型为 create 的 symfony 4 表单集合实体

php - 使用Api-Platform,如何在创建时自动将授权用户添加为资源所有者?

mysql - 使用默认值创建表会出现错误

c# - 检测通用类型中的接口(interface)

C# WebApiConfig MapHttpRoutes 与 Action AND optional DateTime(-string) AND optional id

symfony - 如何在 Symfony 4 中验证数组数组

javascript - 为什么表单元素中的 Javascript 会失败?

php - 将 PHP session 变量传递到 HTML 表单

jquery - 在表单验证的提交处理程序ajax中出现Uncaught TypeError : form.序列化不是函数

php - 使用 Cookie 预填充 PHP 表单