我有两个实体:
class Exercise
{
//entity
}
和
class Question
{
//entity
}
他们的关系是ManyToMany。 问题是:我如何过滤(在练习表格上)问题实体?
我有这个练习形式:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('questions', null, array(
'property' => 'name',
'multiple' => true,
'expanded' => false,
'query_builder' => function(EntityRepository $er) use ($options) {
return $er->createQueryBuilder('u')
->where('u.level = :level')
->setParameter('level',$options['level'])
->orderBy('u.dateR', 'ASC');},
))
//other fields
->add('Save','submit')
;
}
我知道我可以使用query_builder进行过滤,但是,我如何通过var $ search? 我应该创建另一种形式吗?
任何帮助将不胜感激。 最好的问候
编辑:我找到了我想要的解决方案。我在Controller Action上放了两个表单,一个表单用于实体,一个表单用于过滤。//ExerciseController.php
public function FormAction($level=null)
{
$request = $this->getRequest();
$exercise = new Exercise();
//Exercise form
$form = $this->createForm(new ExerciseType(), $exercise,array('level' => $level));
//create filter form
$filterForm = $this->createFormBuilder(null)
->add('level', 'choice', array('choices' => array('1' => '1','2' => '2','3' => '3')))
->add('filter','submit')
->getForm();
//Manage forms
if($request->getMethod() == 'POST'){
$form->bind($request);
$filterForm->bind($request);
//If exercise form is received, save it.
if ($form->isValid() && $form->get('Save')->isClicked()) {
$em = $this->getDoctrine()->getManager();
$em->persist($exercise);
$em->flush();
return $this->redirect($this->generateUrl('mybundle_exercise_id', array('id' => $exercise->getId())));
}
//If filter form is received, filter and call again the main form.
if ($filterForm->isValid()) {
$filterData = $formFiltro->getData();
$form = $this->createForm(new ExerciseType(), $exercise,array('level' => $filterData['level']));
return $this->render('MyBundle:Exercise:crear.html.twig', array(
'ejercicio' => $ejercicio,
'form' => $form->createView(),
'formFiltro' => $formFiltro->createView(),
));
}
}
return $this->render('juanluisromanCslmBundle:Ejercicio:form.html.twig', array(
'exercise' => $exercise,
'form' => $form->createView(),
'formFiltro' => $filterForm->createView(),
));
}
模仿表格 在form.html.twig
上{{ form_start(filterForm) }}
{{ form_errors(filterForm) }}
{{ form_end(filterForm) }}
{{ form_start(form) }}
{{ form_errors(form) }}
{{ form_end(form) }}
它对我有用,而且我正在寻找。
答案 0 :(得分:0)
您可能想要做的是使用表单构建器:
$search = [...]
$form = $this->createForm(new AbstractType(), $bindedEntityOrNull, array(
'search' => $search,
));
在这里,您可以提供AbstractType的builder方法的任何参数列表。
public function buildForm(FormBuilderInterface $builder, array $options)
正如您可能已经猜到的那样,您可以通过$ option变量访问options数组。
作为旁注,请记住在默认选项数组中提供回退。在 AbstractType 中,您可以执行以下操作:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'search' => 'some_valid_default_value_if_search_is_not_provided'
));
}
希望它有所帮助,问候。