问题描述
我已经为 JMSSerializerBundle 编写了一个自定义表单处理程序,我正在将它与 FOSRestBundle 一起使用.根据文档,它应该像正确标记服务一样简单.但我的自定义处理程序从未被使用过.
I have written a custom Form Handler for JMSSerializerBundle that I'm using with FOSRestBundle. According to the documentation it should be as easy as tagging a service correctly. But my custom handler never gets used.
这是处理程序:
<?php
namespace AppBundle\Handler;
use JMS\Serializer\Handler\FormErrorHandler as JMSFormErrorHandler;
class FormErrorHandler extends JMSFormErrorHandler
{
public function serializeFormToJson(\JMS\Serializer\JsonSerializationVisitor $visitor, \Symfony\Component\Form\Form $form, array $type)
{
$this->convertFormToArray($visitor, $form);
}
private function getErrorMessage(FormError $error)
{
if (null !== $error->getMessagePluralization()) {
return $this->translator->transChoice($error->getMessageTemplate(), $error->getMessagePluralization(), $error->getMessageParameters(), 'validators');
}
return $this->translator->trans($error->getMessageTemplate(), $error->getMessageParameters(), 'validators');
}
private function convertFormToArray(GenericSerializationVisitor $visitor, Form $data)
{
$isRoot = null === $visitor->getRoot();
$form = $errors = array();
foreach ($data->getErrors() as $error) {
$errors[] = $this->getErrorMessage($error);
}
if ($errors) {
$form['errors'] = $errors;
}
$children = array();
foreach ($data->all() as $child) {
if ($child instanceof Form) {
$children[$child->getName()] = $this->convertFormToArray($visitor, $child);
}
}
if ($children) {
$form = array_merge($form , $children);
}
if ($isRoot) {
$visitor->setRoot($form);
}
return $form;
}
}
这里是服务注册
services:
my_form_error_handler:
class: AppBundle\Handler\FormErrorHandler
arguments: ["@translator"]
tags:
- {name: jms_serializer.subscribing_handler}
我不需要做太多改动,所以在大多数情况下,我只是扩展了原始版本并更改了我需要更改的功能.
I don't need to change much so for the most part I just extend the original and changed the functions I needed to change.
没有错误.一切都像不存在覆盖类一样执行,它只使用在 JMSSerializer 中找到的默认 FormErrorHandler.这与使用 FOSRestBundle 有什么关系吗?对于笑声,在随机控制器中,我尝试了 $this->get('my_form_error_handler')
并且有效,所以我知道该服务已注册.任何帮助表示赞赏.
There are no errors. Everything executes as if no overriding class existed and it just uses the default FormErrorHandler found in the JMSSerializer. Does this have anything to do with also using the FOSRestBundle? For giggles, in a random controller I tried $this->get('my_form_error_handler')
and that worked, so I know the service is registered. Any help appreciated.
谢谢.
推荐答案
您不是通过标记启用表单错误处理程序,而是通过设置 jms_serializer.form_error_handler.class
参数指向您的类:
you do not enable the form error handler by tagging, but by setting the jms_serializer.form_error_handler.class
parameter to point to your class:
参数:jms_serializer.form_error_handler.class: AppBundle\Handler\FormErrorHandler
这篇关于FOSRestBundle 和 JMSSerializer 自定义表单错误处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!