Let’s say I have ordinary *Type class:
class LocationType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add(...)
...
}
}
and one of the fields is a choice type. The values that need to be used as choice items are supposed to be retrieved from the database (from some particular entity repository).
So the question is: how to get the repository in the LocationType class? Is passing it through the constructor the only way to get it?
UPD:
I know about entity type but unfortunately I cannot use it, because my property is not and cannot be defined as one-to-one relation due to very complex relation conditions that Doctrine doesn’t support (yet?). See How to specify several join conditions for 1:1 relationship in Doctrine 2 for additional details
You can specify an entity field type as an option like so:
EDIT:
Actually the ‘class’ option is the only required field option. You can read a bit more about the entity field type here: http://symfony.com/doc/2.0/reference/forms/types/entity.html
Hope this helps.
EDIT:
Further to discussion below, here’s an example
In the controller:
The
$optionsarray is passed to theFooType::buildForm()method, sofoo_repositoryshould then be available in this method like so:Symfony 4 and 5:
Symfony Form Types are services so you can use dependency injection:
or inject specific repository: