Skip to content

Instantly share code, notes, and snippets.

@zball

zball/BeerType.php

Created Feb 7, 2018
Embed
What would you like to do?
Upsert
<?php
namespace AppBundle\Form;
use AppBundle\Entity\Brewery;
use AppBundle\Entity\State;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\PercentType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
use AppBundle\Entity\Beer;
class BeerType extends AbstractType
{
protected $em;
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('description')
->add('abv', PercentType::class, [
'scale' => 2
])
->add('brewery', EntityType::class, [
'class' => Brewery::class,
'attr' => [
'class' => 'select-two'
]
])
->add('beerType', EntityType::class, [
'class' => \AppBundle\Entity\BeerType::class,
'attr' => [
'class' => 'select-two',
'data-tags' => true
]
]);
$builder->addEventListener(FormEvents::PRE_SUBMIT, function(FormEvent $event){
$data = $event->getData();
$tag = $this->em->getRepository(\AppBundle\Entity\BeerType::class)->findOneBy(['name' => $data['beerType']]);
if(!$tag){
$beerType = ( new \AppBundle\Entity\BeerType() )->setName($data['beerType']);
$this->em->persist($beerType);
$this->em->flush();
$data['beerType'] = $beerType->getId();
$event->setData($data);
}
});
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Beer::class
]);
}
public function getBlockPrefix()
{
return 'app_bundle_beer';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.