Last active
April 3, 2019 21:36
-
-
Save ger86/a5a8be394bb63446861f0b17e6cf52da 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) { | |
$data = $builder->getData(); | |
$builder | |
->add('job', Select2Type::class, [ | |
'label' => '¿Cuál es tu profesión?', | |
'required' => true, | |
'attr' => ['data-autocomplete-url' => $this->router->generate('search_jobs')], | |
'choices' => [$data->getName() => $data->getId()] | |
]); | |
->add('submit', SubmitType::class, [ | |
'label' => 'Enviar', | |
'attr' => ['class' => 'btn-primary btn-submit'] | |
]); | |
$formModifier = function (FormInterface $form, ?int $jobId = 0) { | |
$choices = empty($jobId) ? null : [$jobId => $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_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