entity
の代わりにタイプを使用choice
$builder
->add('entity_property', 'entity', array(
'class' => 'Namespace\\To\\Entity',
'query_builder' => function(EntityRepository $repository) {
return $repository->createQueryBuilder('q')
->where('q.a_field = yourvalue');
}
));
編集:
クエリでカスタム パラメータを使用する 2 つの方法。どちらの状況でも、パラメータは外部から注入されるため、FormType はセッションまたはリクエスト オブジェクトなどへの参照を必要としません。
1-必要なパラメーターをコンストラクターに渡します
class TaskType extends AbstractType
{
private $custom_value;
public function __construct($custom_value) {
$this->custom_value = $custom_value;
}
// ...
}
buildForm()
値をローカル変数にコピーして、query_builder コールバックで使用できるようにする必要があります。
public function buildForm(/*...*/) {
$my_custom_value = $this->custom_value;
// ...
'query_builder' => function(EntityRepository $repository) use ($my_custom_value) {
return $repository->createQueryBuilder('q')
->where('q.a_field = :my_custom_value')
->setParameter('my_custom_value', $my_custom_value);
}
// ...
}
2-メソッドの$options
パラメーターを使用しますbuildForm
。
まず、オーバーライドしてデフォルト値を定義する必要がありますgetDefaultOptions
:
public function getDefaultOptions(array $options)
{
return array(
'my_custom_value' => 'defaultvalue'
);
}
次に、メソッドの 3 番目の引数でコントローラーから渡すことができますcreateForm
。
$this->createForm(new YourFormType(), $entity, array('my_custom_value' => 'custom_value'));
$options
これで、 youru buildForm メソッドのパラメーターを介して値を使用できるようになります。上記のようにコールバックに渡します。