Set Default value of choice field Symfony FormType

后端 未结 5 1940
野性不改
野性不改 2021-01-21 03:12

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

Types are loaded from a an entity QuestionType

5条回答
  •  遇见更好的自我
    2021-01-21 03:43

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

    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 )

提交回复
热议问题