使用Symfony 3在表单中映射false

时间:2017-05-28 14:19:36

标签: php forms symfony

我的应用服务器出了问题。服务器在PHP,Symfony 3下。我的控制器中有以下表格:

public function addAction($id, Request $request)
{
    if (!$request->isMethod("POST")) {
        $response = new JsonResponse("POST only");
        $response->setStatusCode(Response::HTTP_BAD_REQUEST);
        return $response;
    }

    if ($id != 0) {
        $cr = $this->getDoctrine()->getRepository('AppBundle:Cr')->find($id);
    } else {
        $cr = new Cr();
    }

    $form = $this->createFormBuilder($cr, array('csrf_protection' => false))
        ->add('date', DateType::class, array(
                'required' => true,
                'widget' => 'single_text',
            )
        )
        ->add('description', TextareaType::class, array('required' => true))
        ->add('todo', TextareaType::class, array('required' => true))
        ->add('typeVisite', IntegerType::class, array('required' => true))
        ->add('project', IntegerType::class, array('mapped' => false))
        ->getForm();

    if ($request->isMethod('POST')) {
        $form->submit($request->request->get($form->getName()));

        if ($form->isValid()) {

            $em = $this->getDoctrine()->getManager();

            $em->persist($cr);

            $this->updateMobilisationHebdo($cr);
            $this->updateSuiviBenevoles($cr);
            if (isset($request->request->get($form->getName())['project']) && $cr->getTypevisite() != 0) {
                $this->updateSuiviproject($cr, $request->request->get($form->getName())['project']);
            }

            $em->flush();

            return new JsonResponse('ok');
        } else {
            $errors = [];
            foreach ($form->getErrors(true, true) as $error) {
                $errors[] = $error->getOrigin()->getName() . ' : ' . $error->getMessage();
            }

            $response = new JsonResponse($errors);
            $response->setStatusCode(Response::HTTP_NOT_ACCEPTABLE);
            return $response;
        }
    }
}

我的问题是,如果我为字段project选择一个项目,它不会获取此项的ID,但默认保留为0。

我该如何解决这个问题?

0 个答案:

没有答案