[英]symfony fosrestbundle - How to post a record with associated entities (many-to-many)
I am trying to build a RESTful API with Symfony2, FosRestBundle, and JMSSerializer and everything works perfect until I try to persist an entity with any kind of association. 我正在尝试使用Symfony2,FosRestBundle和JMSSerializer构建RESTful API,并且在我尝试通过任何类型的关联来持久化实体之前,一切都可以正常运行。 This works out-of-the-box with the standard symfony edition, it's enough to set the form field as "entity" type and the framework updated the cross table.
这与标准symfony版本即用即用,将表单字段设置为“实体”类型就足够了,并且框架更新了交叉表。 However when I try to do the same on a REST setup, I get this error "Notice: Array to string conversion" related to the "categories" form field and a 500 error.
但是,当我尝试在REST设置上执行相同操作时,出现与“类别”表单字段相关的错误“注意:数组到字符串转换”和500错误。
How I am supposed to persist related entities with an API? 我应该如何使用API保留相关实体?
Entity Serie.php 实体Serie.php
/**
* @ORM\ManyToMany(targetEntity="Category", inversedBy="series")
* @ORM\JoinTable(name="categories_series")
*/
private $categories;
a form SerieType.php 表格SerieType.php
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('categories', 'entity', array(
'multiple' => true,
'expanded' => false,
'property' => 'name',
'class' => 'My\Bundle\CoreBundle\Entity\Category'
))
->add('name')
->add('description')
->add('status', 'checkbox', array('required' => false))
->add('save', 'submit')
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'My\Bundle\CoreBundle\Entity\Serie',
'csrf_protection' => false
));
}
public function getName()
{
return 'serie';
}
and a SerieController.php 和一个SerieController.php
/**
* @POST("", name="serie_new")
*/
public function newAction(Request $request){
$serie = new Serie();
$form = $this->createForm(new SerieType(), $serie);
$form->submit($request->request->get($form->getName()));
if($form->isValid()){
$em = $this->getDoctrine()->getManager();
$em->persist($serie);
$em->flush();
$view = $this->routeRedirectView('serie_index');
return $this->handleView($view);
}
and a json POST request: 和一个JSON POST请求:
{
"serie": {
"categories":[
{"id":1,"name":"Category 1"},
{"id":2,"name":"Category 2"}
],
"name":"asasdasd",
"description":"sadsads",
"status":true
}
You error is probably generated when trying to display the entity. 尝试显示实体时可能会生成您的错误。 Try adding __toString() method to your Category Entity.
尝试将__toString()方法添加到类别实体。
And you should use a DataTransformer in order to be able to identify the category when trying to submit a POST request. 并且您应该使用DataTransformer以便在尝试提交POST请求时能够识别类别。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.