Php Symfony2表单验证始终返回错误:此值不应为空

Php Symfony2表单验证始终返回错误:此值不应为空,php,forms,validation,symfony,symfony-forms,Php,Forms,Validation,Symfony,Symfony Forms,我在使用Symfony2中的表单时遇到了一个奇怪的问题 首先,我在实体类Job中添加了验证作为annotations,如下所示: class Job { /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\Column(type="string", l

我在使用Symfony2中的表单时遇到了一个奇怪的问题

首先,我在实体类
Job
中添加了验证作为
annotations
,如下所示:

class Job
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Assert\NotBlank()
     * @Assert\Choice(callback="getTypeValues")
     */
    protected $type;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank()
     */
    protected $company;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    protected $logo;

    /**
     * @Assert\Image()
     */
    protected $file;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Assert\Url()
     */
    protected $url;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank()
     */
    protected $position;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank()
     */
    protected $location;

    /**
     * @ORM\Column(type="text")
     * @Assert\NotBlank()
     */
    protected $description;

    /**
     * @ORM\Column(type="text")
     * @Assert\NotBlank()
     */
    protected $how_to_apply;

    /**
     * @ORM\Column(type="string", length=255, unique=true)
     * @Assert\NotBlank()
     */
    protected $token;

    /**
     * @ORM\Column(type="boolean", nullable=true)
     */
    protected $is_public;

    /**
     * @ORM\Column(type="boolean", nullable=true)
     */
    protected $is_activated;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank()
     * @Assert\Email()
     */
    protected $email;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $expires_at;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $created_at;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     */
    protected $updated_at;

    /**
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="jobs")
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
     * @Assert\NotBlank()
     */
    protected $category;
}
我创建了一个
JobType
类,并在表单中使用它。这样我就可以增加工作了

class JobType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('type', 'choice', array('choices' => Job::getTypes(), 'expanded' => true))
            ->add('category')
            ->add('company')
            ->add('file', 'file', array('label' => 'Company logo', 'required' => false))
            ->add('url')
            ->add('position')
            ->add('location')
            ->add('description')
            ->add('how_to_apply', null, array('label' => 'How to apply?'))
            ->add('is_public', null, array('label' => 'Public?'))
            ->add('email')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
                'data_class' => 'Ibw\JobeetBundle\Entity\Job',
            ));
    }

    public function getName()
    {
        return 'job';
    }
}
这是我的控制器:

public function createAction(Request $request)
{
    $entity = new Job();
    $form = $this->createForm(new JobType(), $entity);
    $form->handleRequest($request);

    if($form->isValid())
    {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('ibw_job_preview', array(
                'company'   => $entity->getCompanySlug(),
                'location'  => $entity->getLocationSlug(),
                'position'  => $entity->getPositionSlug(),
                'token'     => $entity->getToken(),
            )));
    } else {
        return new Response(var_dump($form->getErrorsAsString()));
//            return new Response($form->getErrorsAsString());
//          return $this->render('IbwJobeetBundle:Job:new.html.twig', array(
//                  'form' => $form->createView(),
//              ));
    }
}
现在,当我执行
var\u dump($form->getErrorsAsString())
时,我得到:

string 'ERROR: This value should not be blank.
type:
    0:
        No errors
    1:
        No errors
    2:
        No errors
category:
    No errors
company:
    No errors
file:
    No errors
url:
    No errors
position:
    No errors
location:
    No errors
description:
    No errors
how_to_apply:
    No errors
is_public:
    No errors
email:
    No errors
' (length=355)
array (size=1)
  0 => 
    object(Symfony\Component\Form\FormError)[614]
      private 'message' => string 'This value should not be blank.' (length=31)
      protected 'messageTemplate' => string 'This value should not be blank.' (length=31)
      protected 'messageParameters' => 
        array (size=0)
          empty
      protected 'messagePluralization' => null
或者当我执行
var\u dump($form->getErrors())
时,我得到:

string 'ERROR: This value should not be blank.
type:
    0:
        No errors
    1:
        No errors
    2:
        No errors
category:
    No errors
company:
    No errors
file:
    No errors
url:
    No errors
position:
    No errors
location:
    No errors
description:
    No errors
how_to_apply:
    No errors
is_public:
    No errors
email:
    No errors
' (length=355)
array (size=1)
  0 => 
    object(Symfony\Component\Form\FormError)[614]
      private 'message' => string 'This value should not be blank.' (length=31)
      protected 'messageTemplate' => string 'This value should not be blank.' (length=31)
      protected 'messageParameters' => 
        array (size=0)
          empty
      protected 'messagePluralization' => null

我不知道是什么产生了这个
错误:这个值不应该是空的。
错误。我很难弄明白。任何帮助都将不胜感激。

我刚刚遇到了同样的问题。我得到一个全局错误
错误:此值不应为空
,但特定字段没有任何错误

如果正确,验证实际上应用于基础对象。问题是在表单将提交的数据应用于对象之后,该对象是否有效


出现此问题的原因是,提交表单后,对象的某些字段无效,并且这些字段未包含在表单中。要解决此问题,您可以在验证之前将有效数据传递给对象的字段,或者使用验证组仅根据类上的某些约束验证对象。

正如@cheesemacfly所提到的,您的问题在“令牌”字段中

它被断言为“非空”,但未包含在表单中,这就是为什么该错误未绑定到任何表单字段,而是表单的全局错误,因为验证发生在实体上,而不是表单上(与symfony 1.4不同)因此验证机制无法将其绑定到表单中的字段,因为此属性(令牌)在表单中没有字段。请删除以下内容:

token:
     - NotBlank: ~

src/Ibw/JobeetBundle/Resources/config/validation.yml

中,当表单应该显示在视图中时,您是否在GET请求中收到这些错误?您的意思是当您将表单发布到控制器以处理表单时?这只是一个想法。。。我认为您应该使用@Assert\NotBlank()或使用回调函数,而不是两者都使用。@k当POST控制器处理已发布的表单时,会发生这种情况。所以在POST请求中是的。
$token
=>
@Assert\NotBlank()
?首先验证与表单无关,与实体本身无关。您应该为表单创建一个,并在设置令牌后创建第二个来验证您的实体。将此标记为正确答案,这有助于我使表单有效。