Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding 'choice' option to 'entity' type form field invalidates form -- Symfony2

I've run into this issue which I can't resolve.

On one of my forms, there is a requirement to filter the entities.

A bit of background:

The form is to add a new task to a workflow step. The tasks that can be selected depend on what stage in the workflow the user is at, what product is assigned to the workflow and the company that manages that workflow.

I tried adding in the filtering query into the 'query_builder' section, and I have tried to put the query result from the entity repository into the 'choices' section in the array.

However, the form always comes back saying that the field I'm working on is invalid. The most puzzling part is, without the 'choices' field, as in, when it's bringing in ALL the records for that entity, the select box is exactly the same (with a few extra records) - the name, and pattern of how it's written. And that works fine. So I have absolutely no idea of what's going on.

The form element code:

->add('instructionAction', 'entity', array(
            'label' => 'Action',
            'empty_value' => 'Select Action',
            'required' => true,
            'class' => 'ApplicationTrackpadCommonBundle:InstructionAction',
            'property' => 'description',
            'choices' => $this->instructionActionRepository->findAllForCaseInstruction( $options['caseInstructionId'] )
            )
)

I'm not sure how much code I can post as it is for client work. The query I use is properly populating the dropdown box like it would without the query, and even if I select all of the entity without any WHERE clauses, the same problem occurs.

Thanks for any and all help.

like image 526
jrdn Avatar asked Oct 01 '13 15:10

jrdn


2 Answers

Something like this:

->add('instructionAction', 'entity', array(
    'required' => true,
    'class' => 'ApplicationTrackpadCommonBundle:InstructionAction',
    'query_builder' => function(EntityRepository $er) use ($user) {
        return $er->createQueryBuilder('c')
            ->where('c.user = :user')
            ->setParameter('user', $user)
            ->orderBy('c.name', 'ASC');
 }))

You can pass variables using the use.

like image 140
Edmund Beinarovic Avatar answered Oct 10 '22 14:10

Edmund Beinarovic


Have you tried to use the "query_builder" instead of "choices" option ? I think that the "choices" option is directly overridden by the the "query_builder" when you use a entity type. Like described in the symfony documentation here.
If it still doesn't work, I suggest you should take a look at this.

like image 35
devict Avatar answered Oct 10 '22 13:10

devict