【发布时间】:2016-07-14 06:42:43
【问题描述】:
我尝试使用 EntityType 创建带有 html 选择元素的表单。我必须通过某些条件获取值,并且在此条件下必要的默认值不是从数据库中选择的。所以我得到所有选项值,没有一个,必须是默认值。所以我试图找到一种方法来选择这个值。我尝试了什么......
在表单中设置值:
$growing = $em->getRepository('FarmBundle:Growing')->findGrowing($user_id);
$garden = $em->getRepository('FarmBundle:Garden')->find(7);
$tableForm = $this->createForm('FarmBundle\Form\GrowingType', $growing, ['user_id' => $user_id]);
$tableForm->get('garden')->setData($garden);
$form = $tableForm->createView()
然后我尝试在实体中设置数据:
$growing = $em->getRepository('FarmBundle:Growing')->findGrowing($user_id);
$garden = $em->getRepository('FarmBundle:Garden')->find(7);
$growing->setGarden($garden);
$tableForm = $this->createForm('FarmBundle\Form\GrowingType', $growing, ['user_id' => $user_id]);
$form = $tableForm->createView()
然后我尝试使用“数据”属性在 form_builder 中设置默认选择值:
$growing = $em->getRepository('FarmBundle:Growing')->findGrowing($user_id);
$garden = $em->getRepository('FarmBundle:Garden')->find(7);
$tableForm = $this->createForm('FarmBundle\Form\GrowingType', $grow, [
'user_id' => $user_id,
'selected_choice' => $garden
]);
$form = $tableForm->createView();
Form_builder 代码:
class GrowingType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('id', HiddenType::class)
->add('garden', EntityType::class , [
'class' => 'FarmBundle\Entity\Garden',
'query_builder' => function (GardenRepository $gr) use ($options) {
return $gr->queryFreeGardens($options['user_id']);
},
'attr' => [
'data-type' => 'text',
'class' => 'table-select',
'disabled' => true
],
'required' => false,
'data' => $options['selected_choice']
]);
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'FarmBundle\Entity\Growing',
'selected_choice' => null,
'user_id' => null
));
}
}
以及查询生成器的查询代码:
class GardenRepository extends \Doctrine\ORM\EntityRepository
{
public function queryFreeGardens($user_id)
{
$qb = $this->createQueryBuilder('g')
->leftJoin('g.growing', 'grow')
->where('grow.plantDate is NULL')
->orWhere('grow.endDate is not NULL')
->andWhere('g.user = :user_id')
->orderBy('g.name')
->setParameter('user_id', $user_id);
return $qb;
}
}
这 3 种方法都不起作用。结果是一个,如果实体没有在查询生成器中进行查询,我无法设置此实体。如果我将实体设置为默认值,那在查询生成器中一切都会正常工作。
我该如何解决这个问题?
【问题讨论】:
-
对不起,你的意思是当这个下拉菜单不包含这个选项时,你想在下拉菜单中设置默认选项?
-
@DenisAlimov 是的,我需要了解如何做到这一点。那是因为选择的规则是,如果已经选择了某个值,则无法选择它。所以选择只有没有选择的值+自己选择的值。
-
那么您应该将此值添加到选项中。那么,你想知道怎么做吗?
-
@DenisAlimov 是的。我试图通过将 form_widget() 替换为简单的 html 代码来做到这一点,但这是一个不好的方法(
标签: symfony-forms symfony