【问题标题】:Symfony API Entity ValidationSymfony API 实体验证
【发布时间】:2016-03-22 16:48:09
【问题描述】:

我有一个带有注释的类用于验证。

namespace AppBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as Serialize;
use Symfony\Component\Validator\Constraints as Assert;
use AppBundle\Annotation\Link;

/**
 * @Serialize\ExclusionPolicy("all")
 * @Serialize\AccessType(type="public_method")
 * @Serialize\AccessorOrder("custom", custom = {"id", "name", "awardType", "nominations"})
 * @ORM\Entity(repositoryClass="AppBundle\Repository\AwardRepository")
 * @ORM\Table(name="awards")
 * @Link("self", route = "api_awards_show", params = { "id": "object.getId()" })
 */
class Award extends Entity
{
    /**
     * @Serialize\Expose()
     * @Serialize\Type(name="string")
     * @Assert\Type(type="string")
     * @Assert\NotBlank(message="Please enter a name for the Award")
     * @Assert\Length(min="3", max="255")
     * @ORM\Column(type="string")
     */
    private $name;

    /**
     * @Serialize\Expose()
     * @Serialize\Type(name="AppBundle\Entity\AwardType")
     * @Serialize\MaxDepth(depth=2)
     * @Assert\Valid()
     * @ORM\ManyToOne(
     *     targetEntity="AppBundle\Entity\AwardType",
     *     inversedBy="awards"
     * )
     */
    private $awardType;

    /**
     * @Serialize\Expose()
     * @Serialize\Type(name="ArrayCollection<AppBundle\Entity\Nomination>")
     * @Serialize\MaxDepth(depth=2)
     * @ORM\OneToMany(
     *     targetEntity="AppBundle\Entity\Nomination",
     *     mappedBy="award"
     * )
     */
    private $nominations;
}

然后我使用以下内容验证该实体:

    $validator = $this->get('validator');
    $errors = $validator->validate($entity);

    if (count($errors) > 0) {
        $apiProblem = new ApiProblem(
            400,
            ApiProblem::TYPE_VALIDATION_ERROR
        );

        $apiProblem->set('errors', ['testing', 'array']);

        throw new ApiProblemException($apiProblem);
    }

    $this->save($entity);

这很好用,问题是我无法获取有关哪些字段有错误及其错误消息的信息。在这种情况下,$errors 似乎属于未知类型,我似乎无法获取任何字段的错误消息。

我如何获得该对象的错误信息?

【问题讨论】:

    标签: validation symfony


    【解决方案1】:

    您可以像这样获得错误的确切消息:

    $errors = $validator->validate($entity);
    
    if (count($errors) > 0) {
        $formattedErrors = [];
        foreach ($errors as $error) {
            $formattedErrors[$error->getPropertyPath()] = [
                'message' => sprintf('The property "%s" with value "%s" violated a requirement (%s)', $error->getPropertyPath(), $error->getInvalidValue(), $error->getMessage());
            ];
        }
    
        return new \Symfony\Component\HttpFoundation\JsonResponse($formattedErrors, 400);
    }
    

    例如,可以输出:

    [
        'field1' => 'The property "field1" with value "" violated a requirement (Cannot be null)',
        // ...
    ]
    

    【讨论】:

    • 这会让我得到所有的错误还是会在第一个错误时停止?
    • 感谢您提供非常感谢的信息。
    • 不客气。如果它不打扰你,你能告诉我你为什么不投票给我的答案的原因吗?如果我能改进它,它可能会对遇到同样问题的人有所帮助。
    • 哦,对不起,我真的不理解投票,我认为只是接受它就可以完成它应该做的事情。我很抱歉。我想我现在刚刚投了赞成票。我希望我没有弄乱其他答案。
    • 没问题 :) 它实际上不是自动的,您也不是第一个。对于可以阅读答案的其他人以及答案的所有者编写其他答案来说,这是令人鼓舞的。感谢您的投票!不要犹豫,继续您以前的问题,为对您有帮助的问题投票,我们将不胜感激。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多