One more form subscriber
<?php
namespace AppBundle\Form\EventListener;
use AppBundle\Entity\Listing;
use AppBundle\Entity\Property;
use AppBundle\Entity\Reservation;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormInterface;
/**
* Class AddReservationListingsSubscriber
* @package AppBundle\Form\EventListener
*/
class AddReservationListingsSubscriber implements EventSubscriberInterface
{
private $em;
/**
* AddReservationListingsSubscriber constructor.
* @param EntityManagerInterface $em
*/
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
/**
* Returns an array of event names this subscriber wants to listen to.
*
* @return array The event names to listen to
*/
public static function getSubscribedEvents()
{
return [
FormEvents::PRE_SET_DATA => 'onPreSetData',
FormEvents::PRE_SUBMIT => 'onPreSubmit',
];
}
/**
* @param FormEvent $event
*/
public function onPreSubmit(FormEvent $event)
{
$form = $event->getForm();
$data = $event->getData();
if (! isset($data['property'])) return;
$property = $this->em->getRepository(Property::class)->findOneById($data['property']);
$this->addListingsElement($form, $property);
}
/**
* @param FormEvent $event
*/
public function onPreSetData(FormEvent $event)
{
/** @var Reservation $reservation */
$reservation = $event->getData();
$form = $event->getForm();
if (null == $reservation) return;
$property = $reservation->getProperty();
$this->addListingsElement($form, $property);
}
/**
* @param FormInterface $form
* @param Property $property
*/
protected function addListingsElement(FormInterface $form, Property $property = null)
{
$form
->add('property', 'entity', [
'class' => 'AppBundle:Property',
'data' => $property,
'property' => 'descriptiveName',
'mapped' => false,
'empty_value' => '-- Choose --',
'attr' => ['class' => 'app-dynamic-property'],
]
);
$listings = $property ? $property->getListings()->toArray() : [];
$form->add('listing', 'entity', array(
'class' => Listing::class,
'property' => 'descriptiveName',
// 'empty_value' => '-- Select a property --',
'choices' => $listings,
'attr' => [ 'startRow' => true, 'groupClass' => 'col-xs-6 col-tight', 'class' => 'app-dynamic-listing']
));
}
}