Created
April 3, 2019 21:44
-
-
Save ger86/dbc39ed561f5094f9fb0f4cbabba5c49 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 App\Form\Type; | |
use Symfony\Component\Form\AbstractType; | |
use Symfony\Component\Form\FormBuilderInterface; | |
use Symfony\Component\OptionsResolver\OptionsResolver; | |
use Symfony\Component\Routing\RouterInterface; | |
use Symfony\Component\Form\FormEvents; | |
use Symfony\Component\Form\FormEvent; | |
use Symfony\Component\Form\FormInterface; | |
use App\Model\Person; | |
use App\Form\Type\Select2Type; | |
class PersonFormType extends AbstractType { | |
public function __construct(RouterInterface $router) { | |
$this->router = $router; | |
} | |
public function buildForm(FormBuilderInterface $builder, array $options) { | |
$formModifier = function (FormInterface $form, ?int $jobId = 0, string $jobName = '') { | |
$choices = empty($jobId) ? null : [$jobName => $jobId]; | |
$form->add('job', Select2Type::class, [ | |
'label' => '¿Cuál es tu profesión?', | |
'required' => true, | |
'attr' => ['data-autocomplete-url' => $this->router->generate('search_jobs')], | |
'choices' => $choices, | |
'data' => $jobId | |
]); | |
}; | |
$builder->addEventListener( | |
FormEvents::PRE_SET_DATA, | |
function (FormEvent $event) use ($formModifier) { | |
$data = $event->getData(); | |
$jobId = empty($data) ? 0 : $data->getJob(); | |
$jobName = empty($data) ? '' : $data->getJobName(); | |
$formModifier($event->getForm(), $jobId, $jobName); | |
} | |
); | |
$builder->addEventListener( | |
FormEvents::PRE_SUBMIT, | |
function (FormEvent $event) use ($formModifier) { | |
$data = $event->getData(); | |
$formModifier($event->getForm(), empty($data['job']) ? 0 : $data['job']); | |
} | |
); | |
} | |
public function configureOptions(OptionsResolver $resolver) | |
{ | |
$resolver->setDefaults(['data_class' => Person::class]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment