Symfony 4 TextType required = false getting Expected argument of type "string", "NULL" 给定

Symfony 4 TextType required = false getting Expected argument of type "string", "NULL" given

我有一个 TextType 字段,设置如下

类型:

        ->add('zipCode',TextType::class, array(
                'attr' => array('maxlength' => 10),
                'required' => false,
                'empty_data' => null
            )
        )

当从数据库加载数据时,该字段为空。我只是尝试提交表格,然后我得到了

Expected argument of type "string", "NULL" given.

at vendor/symfony/property-access/PropertyAccessor.php:174 at Symfony\Component\PropertyAccess\PropertyAccessor::throwInvalidArgumentException('Argument 1 passed to App\Entity\Patients::setZipCode() must be of the type string, null given,

我不确定如何解决这个问题?我希望该值为空...?也许是因为我没有在表单上加载初始数据?

下面是相关代码,如果您需要进一步的信息,请告诉我:

树枝:

{{ form_widget(view_form.zipCode, { 'attr': {'class': 'mb-2 mb-sm-0 w-100'} }) }}

控制器:

public function view(Request $request)
{
    $patientId = $request->query->get('id');

    if (!empty($patientId)) {
        $search = $this->getDoctrine()
            ->getRepository(Patients::class)
            ->find($patientId);

        if (is_null($search))
            $this->addFlash('danger', 'Invalid Patient');

        $form = $this->createForm(PatientViewType::class,$search);
    }
    else
        $form = $this->createForm(PatientViewType::class);

    dump($request);

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $view = $form->getData()();

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($view);
        $entityManager->flush();

        $this->addFlash('success', 'Patient record updated successfully!');
    }

    return $this->render('patient/view.html.twig', [
        'view_form' => $form->createView()
    ]);
}

I WANT the value to be null...? Perhaps it's cause I'm not loading the initial data right on the form?

根据异常消息,方法Patients::setZipCode 不接受空值。该值似乎已作为 null 正确传递给您的实体,但 Patients class 不接受该值。

我认为 setZipCode 签名看起来有点像这样:

public function setZipCode(string $zipCode): void

您可以通过添加问号使其接受空值:

public function setZipCode(?string $zipCode): void