I’m building a custom form field type extending from ‘EntityType’. I always want to return a subset of elements based on option passed.
In my Type:
$builder->add('Categories','choice_category', array('code'=> 'CAT1', 'multiple'=> true)) ;
I’ve declared choice_category as service. work ok!.
bt.form.type.category:
class: My\MBundle\Form\Type\CategoryType
tags:
- { name: form.type, alias: choice_category }
In CategoryChoiceType.php
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(
array(
'class'=> 'CmComunBundle:Comun\Nomenclador',
'code' => null,
)
);
}
public function getParent()
{
return 'entity';
}
I’m thinking about use query_builder option, but I don’t know how to pass code option to setDefaultOptions method, I don’t access to $options array here.
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(
array(
'class'=> 'CmComunBundle:Comun\Nomenclador',
'code' => null,
'query_builder' => function(\Doctrine\ORM\EntityRepository $er) use ($options['code']) {
return $er->createQueryBuilder('c')
->where('c.parent_code = :code')
->orderBy('c.name', 'ASC')
->setParameter('code', $options['code']);;
}
)
);
);
You almost got it right, but you need to make “query_builder” dependent on the other option “code” by using this special syntax:
So in your specific example:
This is also documented in the OptionsResolver README.