我而新人到SF2的社區,所以,請把它簡單;)JMSSerializer +形式/陣列
我所面臨的問題與JMSSerializerBundle和形式/陣列。我花了兩天的時間試圖找出自己,沒有取得任何成功,我決定將此發佈到集團。
我正在構建一個簡單的測試應用程序,可以讓我瞭解這些東西的工作原理。現在是API的時候了。我使用FOSRestBundle,完美地工作。我的整個「應用程序」工作得很好(開發速度非常快且有效),我學會了如何使用安全組件,防火牆,路由,Doctrine(但是我過去使用它)編寫自定義身份驗證提供程序 - 我實際上,它是API的一部分。
形式問題: 我創建簡單ArticleController我APIBundle(請忽略文本的反應,我只是刪除我的代碼在調試時,以使其更具可讀性):
namespace Veron\ApiBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\View\View;
use Veron\ApiBundle\Form\Type\ArticleType;
use Veron\CoreBundle\Entity\Article;
class ArticleController extends Controller
{
public function createAction()
{
return $this->processForm(new Article());
}
private function processForm(Article $article)
{
$em = $this->getDoctrine()->getManager();
$form = $this->createForm(new ArticleType(), $article, array(
'csrf_protection' => false
));
$form->bind($this->getRequest());
if ($form->isValid()) {
return new Response('Everything ok');
}
$view = View::create($form, 400);
return $this->get('fos_rest.view_handler')->handle($view);
}
}
,你可以看,我也有一個ArticleType表單類:
namespace Veron\ApiBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ArticleType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title')
->add('description')
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Veron\CoreBundle\Entity\Article',
'csrf_protection' => false,
));
}
public function getName()
{
return 'article';
}
}
問題是什麼?在發送請求時,在XML或JSON - 形式數據沒有被驗證時 - 我發現了錯誤(由JMSSerializer以及格式化):
JSON例如:
{"errors":["This value should not be blank."],"children":{"title":{"errors":["This value is too short. It should have 5 character or more."]},"description":{"errors":["This value should not be blank."]}}}
XML示例:
<?xml version="1.0" encoding="UTF-8"?>
<form name="article">
<errors>
<entry><![CDATA[This value should not be blank.]]></entry>
</errors>
<form name="title">
<errors>
<entry><![CDATA[This value should not be blank.]]></entry>
</errors>
</form>
<form name="description">
<errors>
<entry><![CDATA[This value should not be blank.]]></entry>
</errors>
</form>
</form>
我的第一個問題是:是否有任何自動方式來更改序列化的表單錯誤的輸出?
我也有一個問題,與第一個有關,我想。當返回單個對象,我已下面的XML結構返回:
<article>
<id>10</id>
<title>Test article</title>
</article>
而返回一個數組(多篇文章)的輸出爲:
<result>
<entry>
<id>1</id>
...
</entry>
<entry>
<id>10</id>
...
</entry>
</result>
第二個問題:如何改變響應XML/JSON結構?
感謝您的回覆。我想實現什麼?在出現表單錯誤的情況下,我想要一個簡單的結構:'該值不應爲空 '。對於序列化數組也是如此,我希望將''作爲XML根元素,將''作爲子元素。 Hos這類問題在Symfony 2風格中解決? –
user1854344
2013-03-17 12:33:21