add('zipCode',TextType::class, array( 'attr' => -6ren">
gpt4 book ai didi

php - Symfony 4 TextType required = false 获取 "string"类型的预期参数,给定 "NULL"

转载 作者:行者123 更新时间:2023-12-03 22:53:31 25 4
gpt4 key购买 nike

我有一个 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,



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

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

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

最佳答案

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类不接受该值。

我假设 setZipCode签名看起来有点像这样:
public function setZipCode(string $zipCode): void

您可以通过添加问号使其接受空值:
public function setZipCode(?string $zipCode): void

关于php - Symfony 4 TextType required = false 获取 "string"类型的预期参数,给定 "NULL",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52298736/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com