简体   繁体   中英

Inserting a child entity with parent in Symfony

I have a parent entity which is referring to a child entity and the classes are written as follows:

class MyEntity {
  /**
  * ORM Annotations
  */
  private $id;

  /**
  * ORM Annotations
  */
  private $name;

  /**
  * @var string
  * @ORM\OneToOne(targetEntity="Picture")
  */
  private $image;

  /** Getters & Setters **/
}

private Image {
  private $id;
  private $image_url;
}

Here, Image is a weak entity and I don't want to insert image before inserting MyEntity object. Basically, my question is, how can I render the form for MyEntity so that, Image form appears as a part of it, and image get saved when I save MyEntity .

How come your code has targetEntity="Picture" and you have defined Image as child Entity. I guess there is a typo, you need to correct.

You need to add cascade={"persist", "update"} to your image association in MyEntity .

This will make sure, Image entity being created / updated along with MyEntity .

Now the form Part

Create a new FormType for Image , lets call it as ImageType . In your MyEntity FormType, add the new FormType as a new field :

$builder
    ->add('image', ImageType::class, array(
        'label' => 'Image'
));

Now on form Submission, The child entity (Image) will be created / updated accordingly.

Note : You need to take care of image upload explicitly.

Hope this helps!

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