简体   繁体   中英

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. 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. 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.

How I am supposed to persist related entities with an API?

Entity Serie.php

/**
 * @ORM\ManyToMany(targetEntity="Category", inversedBy="series")
 * @ORM\JoinTable(name="categories_series")
 */
private $categories;

a form 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

/**
 * @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:

{ 
"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.

And you should use a DataTransformer in order to be able to identify the category when trying to submit a POST request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM