0

I'm trying to populate a choice dropdown in Symfony using the array value of a query performed before the ->add of the form builder. I can't for the life of me get the actual label or value despite the fact that the dump($categories) shows the proper values. The dropdown is populated with just 0,1,2. The Category contains a ->getName and a ->getId but I can't reference these.

$categories = $em->getRepository('AppBundle:Category')
        ->createQueryBuilder('t')
        ->where('t.userCreate = :user_id')
        ->andWhere('t.type = :catType')
        ->setParameter('user_id',$userID)
        ->setParameter('catType',$type)
        ->getQuery()
        ->getResult();

    $builder
        ->add('taskCategory', 'choice', array(
            'choices' => $categories,
            'placeholder' => 'Choose a category',
            'choices_as_values' => true,

            ))
3
  • Any particular reason for you not to use entity form type? Commented Mar 19, 2016 at 21:21
  • I didn't quite understand the concept of the 2nd parameter. I thought "choice" was obligatory for a drop down list to be generated as the form object. Commented Mar 21, 2016 at 10:50
  • entity is part of the DoctrineBridge bundle and adds extra functionality for the choice type and lots of magic that cannot be explained in brief comment. Btw, instead of passing your categories through $options, since you're using entity type, you can include the extra option query_builder and pass the callback along with your query - symfony.com/doc/current/reference/forms/types/… Commented Mar 21, 2016 at 10:57

1 Answer 1

1

Here's how I resolved this one. I separated out the query from the label with a function:

->add('taskCategory','entity',array(
            'class'=>'AppBundle\Entity\Category',
            'choices'=>$this->fillCategories($options),
            'choice_value'=>'id',
            'choice_label'=>'name',

        ))

The "fillCategories" function just returned the data that was required. The key here was to specify the type 'entity' in place of 'choice' in the ->add.

$categories = $em->getRepository('AppBundle:Category')
        ->createQueryBuilder('t')
        ->where('t.userCreate = :user_id')
        ->andWhere('t.type = :catType')
        ->setParameter('user_id',$userID)
        ->setParameter('catType',$type)
        ->getQuery()
        ->getResult();

    return $categories;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.