Symfony Проверьте, не является ли хотя бы одно из двух полей пустым при проверке формы - PullRequest
0 голосов
/ 17 марта 2020

Я уже давно переворачиваю это в своей голове и все еще не смог найти решение своей проблемы. Используя Symfony 4 формы и ограничения, я не могу установить проверку, чтобы сказать, что по крайней мере одно из двух полей не должно быть пустым при отправке формы, содержащей подформу.

У меня есть объект Booking который содержит сущность Visitor, которая имеет свойство phoneNumber и свойство электронной почты. Я хотел бы иметь возможность создать 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,
        ]);
    }
}

Я пытался добавьте ограничение Expression к полю электронной почты и телефона, которое выглядело примерно так:

new Expression([
    'expression' => 'this.getPhone() == null && this.getEmail() == null'
])

Также пытался добавить ограничение непосредственно к сущности, но мне кажется, что ничего не работает правильно.

Любая помощь будет принята с благодарностью.

ОБНОВЛЕНИЕ Я не указал это, но моя проблема заключается в том, что я хотел бы проверить форму VisitorType из другой формы, которая добавляет VisitorType в качестве CollectionType.

1 Ответ

1 голос
/ 18 марта 2020

попробуй с обратным вызовом

/**
 * @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

}
...