设置选择字段的默认值 Symfony FormType [英] Set Default value of choice field Symfony FormType

查看:31
本文介绍了设置选择字段的默认值 Symfony FormType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从用户那里选择一种问卷类型,所以我设置了一个包含问卷类型的选择.

I want from the user to select a type of questionnaire, so I set a select that contains questionnaires types.

类型从实体 QuestionType 加载.

 $builder
        ->add('questionType', 'entity', array(
              'class'    => 'QuizmooQuestionnaireBundle:QuestionType',
              'property' => 'questionTypeName',
              'multiple' => false,
              'label' => 'Question Type'))
        ->add('type', 'hidden')
    ;

无法实现的是为结果选择设置默认值.

What am not able to achieve is to set a default value to the resulted select.

我用谷歌搜索了很多,但我只有 preferred_choice解决方案仅适用于数组

I have googled a lot but I got only preferred_choice solution which works only with arrays

推荐答案

我通过在我的控制器的 newAction 中设置一个类型来实现我将设置的类型作为默认值.

I made it by setting a type in the newAction of my Controller I will get the seted type as default value.

public function newAction($id)
{
    $entity = new RankingQuestion();

    //getting values form database 
    $em = $this->getDoctrine()->getManager();
    $type =  $em->getRepository('QuizmooQuestionnaireBundle:QuestionType')->findBy(array('name'=>'Ranking Question'));
    $entity->setQuestionType($type); // <- default value is set here 

    // Now in this form the default value for the select input will be 'Ranking Question'
    $form   = $this->createForm(new RankingQuestionType(), $entity);

    return $this->render('QuizmooQuestionnaireBundle:RankingQuestion:new.html.twig', array(
        'entity' => $entity,
        'form'   => $form->createView(),
        'id_questionnaire' =>$id
    ));
}

如果您有一个恒定的默认值,您可以使用 data 属性 (http://symfony.com/doc/current/reference/forms/types/form.html)但如果您使用表单编辑实体(而不是创建新实体),这将无济于事

You can use data attribute if you have a constant default value (http://symfony.com/doc/current/reference/forms/types/form.html) but it wont be helpful if you are using the form to edit the entity ( not to create a new one )

这篇关于设置选择字段的默认值 Symfony FormType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆