Question

I have a form generated directly in my controller action :

$repoQuestions = $this->getDoctrine()->getRepository('QuizzBundle:Questions');
$questions = $repoQuestions->findBy(array('quizz'=>$quizz));

$formBuilder = $this->createFormBuilder();

foreach($questions as $q){
    $formBuilder
        ->add('rep'.$q->getId(), 'entity', array(
         'label'=>$q->getTitre(),
         'property' => 'titre',
         'query_builder' => function(\MyApp\QuizzBundle\Entity\ReponsesRepository $r)  use($q){
              return $r->getReponsesByQuestion($q);
          },
         'multiple'=>false,
         'expanded'=>true,
         'required'=>true
          ));
}
$formQuizz = $formBuilder->getForm();
if ($request->getMethod() == 'POST') {
          $formQuizz->bind($request);
          $data = $formQuizz->getData();

          if ($formQuizz->isValid()) {
            $em = $this->getDoctrine()->getManager();

            $repoRep = $this->getDoctrine()->getRepository('QuizzBundle:Reponses');

            return $this->render('QuizzBundle:Quizz:resultat-quizz.html.twig', array(
                'data'=>$data
            ));
          }
        }

in my view i have :

<form method="POST" action="{{path('quizz_quizz', {'cat':quizz.categorie.nom, 'id':quizz.id})}}" {{form_enctype(formQuizz)}} id='formQuizz' novalidate>
{% for q in questions %}
                <div id="question">
                    <img src="{{asset('bundles/site/images/quizz-' ~quizz.id~ '/'~q.slug~'.png')}}"><br>
                    {{form_label(attribute(formQuizz, 'rep' ~ q.id)) }}<br>
                    {{form_widget(attribute(formQuizz, 'rep' ~ q.id))}}
                </div>
            {% endfor %}
            {{ form_rest(formQuizz) }}
            </form>

but when I submit my form function isValid() is true but I can't get my form datas...

when I try :

$data = $formQuizz->getData();
print_r($data);

I got :

Array ( [rep11] => [rep12] => [rep13] => [rep14] => [rep15] => [rep16] => [rep17] => [rep18] => [rep19] => [rep20] => )

Was it helpful?

Solution

you don't seem to be using the entity type correctly. you need to specify an entity class. The class is of the entity you are displaying so you'll probably want the Responses class. You might also want to consider having the responses as a collection for each question so you can got $q->getResponses() instead of having to do a query for every field.

$formBuilder->add('rep'.$q->getId(), 'entity', array(
    'class' => 'QuizzBundle:Responses',
    'label'=>$q->getTitre(),
    'property' => 'response_field_you_want_displayed',
    'choices' => $q->getResponses(),
    'multiple'=>false,
    'expanded'=>true,
    'required'=>true
));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top