Created
February 7, 2018 07:56
-
-
Save zball/db18b16f4a941bd3a71afcfe28564d55 to your computer and use it in GitHub Desktop.
Upsert
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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