php - 设置选择字段 Symfony FormType 的默认值

标签 php symfony

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

类型是从实体 QuestionType 加载的。

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

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

我用谷歌搜索了很多,但我只得到 preferred_choice solution仅适用于数组

最佳答案

我通过在我的 Controller 的 newAction 中设置一个类型来实现它,我将设置的类型作为默认值。

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
    ));
}

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

关于php - 设置选择字段 Symfony FormType 的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15776867/

相关文章:

javascript - PHP fatal error : Call to undefined function esc_url()

php - PHP 中的日期格式

php - 用于 PHP 的硬件随机数生成器

php - 使用 Symfony 框架的生产服务器上的用户登录失败(由于...无法处理身份验证请求)

html - Symfony 3 - 导航栏在除一页以外的每一页上都正确显示?

javascript - JQuery GET 请求不会从 php echo 获取正确的数据

php - Wordpress 二十十二全屏响应式背景图片

symfony - 新版Sonata Admin如何覆盖 'show'模板

php - curl 错误 60 : ssl certification issue when attempting to use symfony

php - FOS Elastica嵌套过滤器不起作用