我有一个带有验证注释的类。
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似乎是一个未知类型,我似乎无法获得任何字段的错误消息。
如何获取该对象的错误消息?
发布于 2016-03-21 16:35:58
您可以获得以下错误的确切消息:
$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)',
// ...
]https://stackoverflow.com/questions/36128133
复制相似问题