如何使用 symfony formbuilder 显示必填字段错误(验证)消息?

How can I display required fields error (validation) message with symfony formbuilder?

PagesController.php

$id = $request->request->get('id');
$target = $request->request->get('target');
$EntityName = 'App\Entity\' . ucwords($slug);

$em = $this->getDoctrine()->getManager();
$cmf = $em->getMetadataFactory();
$classes = $cmf->getMetadataFor($EntityName);


if($request->request->get('target')){

  $item = new $EntityName();
  $item= $this->getDoctrine()->getRepository($EntityName)->find($id);

  $formBuilder = $this->createFormBuilder($item);

  foreach ($classes->fieldMappings as $fieldMapping) {
      $formBuilder->add($fieldMapping['fieldName'], TextType::class, array('attr' => array('class' => 'form-control'), 'required'   => true,));
  }

  $formBuilder->add('cancel', ButtonType::class, array('label' => 'Cancel','attr' => array('class' => 'cancel form-btn btn btn-default pull-right close_sidebar close_h')))
  ->add('save', SubmitType::class, array('label' => 'Save','attr' => array('id' => 'submit-my-beautiful-form','class' => 'form-btn btn btn-info pull-right','style' => 'margin-right:5px')));
  $form = $formBuilder->getForm();

  $form->handleRequest($request);


  $response = new JsonResponse(
    array(
      'message' => 'Success',
      'output' => $this->renderView('form.html.twig',
      array(
        'target' => $target,
        'entity' => $item,
        'form' => $form->createView(),
      ))), 200);
      return $response;



} else {

   $em = $this->getDoctrine()->getManager();
    foreach ($classes->fieldMappings as $fieldMapping) {
      $func = 'set'.$fieldMapping['fieldName'];
      $args = $data['form['.$fieldMapping['fieldName'].']'];
      $entity->$func($args);
    }
   $em->persist($entity);
   $em->flush();
  $response = new JsonResponse(array('id' => $data['form[id]']), 200);
  return $response;
}

form.html.twig

<section class="content-header" style="margin-bottom:20px">
  <h1 style="float:left;margin-bottom:30px">Create Entry </h1>
</section>
<section class="content" style="clear:left">
  <div class="form-group">
    {{ form_start(form) }}
    {{ form_end(form) }}
  </section>

我的表格运行良好,当我填写并按下 "Save" 按钮时,它存储在数据库中。 当我将所有字段留空并按 "Save" 时,没有任何反应,我收到 500 错误

An exception occurred while executing 'INSERT INTO members (username, password, email, is_active) VALUES (?, ?, ?, ?)' with params ["", null, "", "1"]:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'password' cannot be null

这其实没问题,因为字段是必填的,但是错误没有显示在我的表单中,即使我添加了 "required" = "true".

因此,在使用表单生成器时,您可以访问:

$form->isSubmitted()

$form->isValid()

因此,您可以执行以下操作:

if ($form->isSubmitted() && $form->isValid()) {
    // save to database
}

我们想在检查表单是否有效之前先检查表单是否已提交,就好像表单未提交一样,没有必要检查它是否有效,因为它会是假的。

这将防止您的 MySQL 错误,因为您的表单在技术上是无效的并且您正在尝试刷新无效数据。我们显然只想在数据有效时保存我们的数据。

当然,如果表单失败,您可以 return 查看并在模板中访问

{{ form_errors() }}

这可能会涵盖您需要的内容,但您也可以将类似

的内容传递给您的模板
'formHasErrors' => $form->isSubmitted() && !$form->isValid(),

然后在您的模板中

{% if formHasErrors %}

您可能还想做一些其他事情,这样您就可以更好地控制自己的字段,将字段分开,如下所示:

{{ form_start(form) }}
    {{ form_label(form.name) }}
    {{ form_errors(form.name, {'attr': {'class': 'form-input'}}) }}
    {{ form_widget(form.name) }}
{{ form_end(form) }}

捕获错误并正确处理它们非常重要。您的实施未验证表单是否有效,这就是您收到 500 条错误的原因。