dravpuso44681
2018-12-11 23:15
浏览 105
已采纳

如何从Symfony3中提交的表单中获取数据?

I faced up with some non-ordinary situation for me.

1) I have a dependent list that rendering by Symfony FormType like this: enter image description here

2) Location and Instruction fields are depend from Company field.

3) When I change Company field (onchange event js) then goes ajax request that retrieves data from the database and build a dropdown list.

4) But when form is submitted I have an error: enter image description here

Please help me to resolve this. Thanks in advance.

My formType:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('hours')
        ->add('messageText', null, ['required' => false])
        ->add('company', null, [
            'choice_label' => 'name',
            'placeholder' => 'Please select company',
            'required' => true
        ])
        ->add('procedure', TextType::class, ['attr' => ['placeholder' => 'Please type code or description'] ])
        ->add('instruction', ChoiceType::class, ['mapped' => false])
        ->add('location', ChoiceType::class, ['mapped' => false])

    ;
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => InstructionNotification::class
    ));
}

Action from controller:

/**
 * @Route("/admin/api/instructions", name="admin_api_instructions")
 * @param Request $request
 * @return JsonResponse
 */
public function getInstructionsByCompanyId(Request $request)
{
    $id = $request->get('id');
    if (!$id) {
        return new JsonResponse('No data', 404);
    }

    $instructions = $this->getDoctrine()->getRepository('OctaneBundle:Instruction')->findInstructionsByCompanyId($id);

    return new JsonResponse($instructions);
}

findInstructionsByCompanyId($id):

public function findInstructionsByCompanyId($id)
{
    $qb = $this->createQueryBuilder('i');
    if ($id) {
        $qb
            ->where('i.company = :id')
            ->setParameter('id', $id);
    }

    return $qb->getQuery()->getResult();
}

response from api (i.e.: admin/api/instructions?id=1):

[{"id":2,"label":"First instruction"},{"id":3,"label":"First instruction"}]

If you need any additional information please leave comments below. Thanks

2条回答 默认 最新

相关推荐 更多相似问题