I am trying to use some data given by query string in my form. I have searched the internet and found a good explaination (http://bicknoyle.com/2014/04/passing-query-string-params-form-symfony/):
class RegistrationFormType extends BaseType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder->add('refer', 'user_refer_type');
$builder->addEventListener(FormEvents::POST_SET_DATA, function(FormEvent $event) use ($options) {
if (isset($options['request'])) {
$form = $event->getForm();
$form->get('source')->setData($options['request']->query->get('source'));
}
});
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setOptional(array(
'request'
));
$resolver->setAllowedTypes(array(
'request' => 'Symfony\Component\HttpFoundation\Request'
));
}
I found another way using the request scope:
class RegistrationFormType extends BaseType
{
private $request = null;
public function __construct(Request $request)
{
$this->request = $request;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder->add('refer', 'user_refer_type');
$builder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event)
{
$form = $event->getForm();
$form->get('refer')->setData($this->request->query->get('refer'));
});
}
I have some questions about the code:
- What is the "better" way to implement such thing?
In general I can summarize, the first approach needs access to the controller to pass the request object and the second needs request scope. - Did I miss another good way?
setOptionalandsetAllowedTypesso less code