map*_*phe 12 forms validation transformation symfony
我想做一些看起来像在如何使用数据变换器教程中所做的事情.但我想添加一个过程,我找不到任何例子.
在symfony教程中,数据转换是关于将问题编号更改为Issue对象.这是在reverseTransform()功能中完成的IssueToNumberTransformer
public function reverseTransform($number)
{
if (!$number) {
return null;
}
$issue = $this->om
->getRepository('AcmeTaskBundle:Issue')
->findOneBy(array('number' => $number))
;
if (null === $issue) {
throw new TransformationFailedException(sprintf(
'An issue with number "%s" does not exist!',
$number
));
}
return $issue;
}
Run Code Online (Sandbox Code Playgroud)
我们可以看到,如果提供了无效的问题编号,转换将失败并且函数抛出一个TransformationFailedException.因此,表单作为错误消息"此值无效".个性化这个消息会很棒.
数据转换过程在任何验证之前执行(使用约束应用于字段),因此在尝试转换之前,我找不到验证问题编号的方法.
作为我必须在转换之前验证的另一个例子,我使用MongoDB文档管理器将"问题mongo id"转换为问题(表单由REST API服务器使用,这就是我收到id的原因).所以:
public function reverseTransform($id)
{
if (!$number) {
return null;
}
$issue = $this->dm
->getRepository('AcmeTaskBundle:Issue')
->find(new \MongoId($id))
;
if (null === $issue) {
throw new TransformationFailedException(sprintf(
'An issue with number "%s" does not exist!',
$number
));
}
return $issue;
}
Run Code Online (Sandbox Code Playgroud)
在这里,如果我在API表单中收到的id没有形成正确的MongoID,客户端将收到500.所以我想检查,在转换之前如果收到的id是正确的,因为如果不是,转换将引发致命的错误.如果我在转换中管理所有情况,比如检查$ id是否正确,就像我在变换器中进行验证并且它不正确.
我的问题是:有没有办法在数据转换之前应用约束?或者有没有办法在转换失败时在表单上添加摘要约束?
den*_*den 10
这就像一个解决方法,但我建议编写代表"无效问题"的类来个性化错误.
class InvalidIssue extends Issue
{
public $message = 'This issue is invalid';
public function __construct($message = null)
{
if (null !== $message) {
$this->message = $message;
}
}
}
Run Code Online (Sandbox Code Playgroud)
并且在变换器中,如果给定的值无效,则返回InvalidIssue对象而不是抛出异常.
public function reverseTransform($id)
{
if (!$number) {
return null;
}
$issue = $this->dm
->getRepository('AcmeTaskBundle:Issue')
->find(new \MongoId($id))
;
if (null === $issue) {
return new InvalidIssue(sprintf(
'An issue with number "%s" does not exist!',
$number
));
}
return $issue;
}
Run Code Online (Sandbox Code Playgroud)
然后,在您的模型上添加验证器.
/** Assert\Callback("callback"="validateIssueIsValid") */
class YourModel
{
protected $issue;
public function setIssue(Issue $issue)
{
$this->issue = $issue;
}
public function validateIssueIsValid(ExecutionContextInterface $context)
{
if ($this->issue instanceof InvalidIssue) {
$context->addViolationAt('issue', $this->issue->message, array());
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2563 次 |
| 最近记录: |