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

99封情书 提交于 2020-07-22 06:52:53

问题


I have a TextType field which is set as below

Type:

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

When the data loads from the database the field is null. I just attempt to submit the form and I get

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,

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

Related code below, let me know if you need something further:

Twig:

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

Controller:

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()
    ]);
}

回答1:


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

According to the exception message, the method Patients::setZipCode does not accept null values. It would seem that the value is correctly passed as null to your entity, but the Patients class does not accept the value.

I assume the setZipCode signature looks somewhat like this:

public function setZipCode(string $zipCode): void

You can make it accept null values by adding a question mark:

public function setZipCode(?string $zipCode): void


来源:https://stackoverflow.com/questions/52298736/symfony-4-texttype-required-false-getting-expected-argument-of-type-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!