Unable to include Collection of Entities inside API POST-call

The error in question:

Entity of type AppEntityNutt is missing an assigned ID for field  'squirrel'.
The identifier generation strategy for this entity requires the ID field to be populated before EntityManager#persist() is called.
If you want automatically generated identifiers instead you need to adjust the metadata mapping accordingly.

I’m perfectly able to call the api POST to add a Squirrel entity into the database.
And using the id of this Squirrel, I can preform the POST call for the Nutt entity with the result being a correctly related record in the Nutt tabel.

What I can’t seem to get working, is allowing the Squirrel api call to include the related collection of Nutts I want to insert in the same api call.

What am I doing wrong?

The JSON call:

{
    "name": "Jake",
    "nutts": [
        {
            "size": 10,
            "color": "blue"
        }
    ]
}

Entity Squirrel

/**
 * @ORMEntity
 * @ORMTable(name="squirrel")
 */
class Squirrel {
  /**
   * @ORMColumn(type="integer")
   * @ORMId
   * @ORMGeneratedValue(strategy="AUTO")
   */
  private $id;
  /**
   * @ORMColumn(type="string", length=100)
   * @AssertNotBlank()
   *
   */
  private $name;
  /**
   * @ORMOneToMany(targetEntity="AppEntityNutt", mappedBy="squirrel", cascade={"persist", "remove"})
   */
  private $nutts;
  public function __construct()
  {
    $this->nutts = new DoctrineCommonCollectionsArrayCollection();
  }
  public function getId()
  {
    return $this->id;
  }
  public function setId($id)
  {
    $this->id = $id;
  }
  public function getName()
  {
    return $this->name;
  }
  public function setName($name)
  {
    $this->name = $name;
  }
  public function getNutts(): ?Collection
  {
    return $this->nutts;
  }
  public function setNutts(Collection $nutts)
  {
    foreach ($nutts as $nutt)
    {
      $this->nutts->add($nutt);
    }
  }
  public function addNutt(Nutt $nutt): Squirrel
  {
    $this->nutts->add($nutt);
    return $this;
  }
}

Entity Nutt

/**
 * @ORMEntity
 * @ORMTable(name="nutt")
 */
class Nutt {
  /**
   * @ORMManyToOne(targetEntity="AppEntitySquirrel", inversedBy="nutts")
   * @ORMId
   */
  private $squirrel;
  /**
   * @ORMColumn(type="integer")
   * @ORMId
   */
  private $size;
  /**
   * @ORMColumn(type="text")
   * @AssertNotBlank()
   */
  private $color;
  /**
   * @return Squirrel|null
   */
  public function getSquirrel(): ?Squirrel
  {
    return $this->squirrel;
  }
  /**
   * @param Squirrel|null $squirrel
   * @return $this
   */
  public function setSquirrel(?Squirrel $squirrel): self
  {
    $this->squirrel = $squirrel;
    return $this;
  }
  //getters and setters for the rest
}

SquirrelController

/**
 * Squirrel controller.
 * @Route("/api", name="api_")
 */
class SquirrelController extends AbstractFOSRestController
{
  /**
   * Lists all Squirrels.
   * @RestGet("/squirrels")
   * @return Response
   */
  public function getSquirrelAction()
  {
    $repository = $this->getDoctrine()->getRepository(Squirrel::class);
    $squirrels = $repository->findall();
    return $this->handleView($this->view($squirrels));
  }
  /**
   * Create Squirrel.
   * @RestPost("/squirrel")
   *
   * @return Response
   */
  public function postSquirrelAction(Request $request)
  {
    $squirrel = new Squirrel();
    $form = $this->createForm(SquirrelType::class, $squirrel);
    $data = json_decode($request->getContent(), true);
    $form->submit($data);
    if ($form->isSubmitted() && $form->isValid()) {
      $em = $this->getDoctrine()->getManager();
      $em->persist($squirrel);
      $em->flush();
      return $this->handleView($this->view(['status' => 'ok'], Response::HTTP_CREATED));
    }
    return $this->handleView($this->view($form->getErrors()));
  }
}

And my current focus
The Squirrel Form

class SquirrelType extends AbstractType
{
  public function buildForm(FormBuilderInterface $builder, array $options)
  {
    $builder
      ->add('name')
      ->add(
        'nutts',
        CollectionType::class, [
          'entry_type' => NuttType::class,
          'allow_add' => true,
          'by_reference' => false
        ])
      ->add('save', SubmitType::class);
  }
  public function configureOptions(OptionsResolver $resolver)
  {
    $resolver->setDefaults(array(
      'data_class' => Squirrel::class,
      'csrf_protection' => false
    ));
  }
}

There is a nutt form but it works fine.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *