首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Symfony API实体验证

Symfony API实体验证
EN

Stack Overflow用户
提问于 2016-03-21 10:10:53
回答 1查看 1.2K关注 0票数 1

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

代码语言:javascript
复制
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;
}

然后,我使用以下方法验证该实体:

代码语言:javascript
复制
    $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似乎是一个未知类型,我似乎无法获得任何字段的错误消息。

如何获取该对象的错误消息?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-03-21 16:35:58

您可以获得以下错误的确切消息:

代码语言:javascript
复制
$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);
}

例如,可以输出:

代码语言:javascript
复制
[
    'field1' => 'The property "field1" with value "" violated a requirement (Cannot be null)',
    // ...
]
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36128133

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档