0

Hoping that my explanation is clear(!), i will do my best:

I am working with the Symfony framework and untill now i got it all worked out. So whats my problem?

I use a form collection (ProjectType and DocumentType): One project can have many documents.

To get the forms i used the generate:crud command and then adjusted the entities, types, etc. like on this page: http://symfony.com/doc/current/cookbook/form/form_collections.html

This all went succesfull: I can create new projects and in the same form i can add many documents. When the submit button is pressed the data gets persisted in the MySQL database.

In my doctrines i created a foreign key in the document entity, called: project_id. The association of these are correct because when i add the id to the form the dropdown appears with existing projects.

BUT I would like that the form also persist the foreign key in my documents table (which is off course the new created project PK). So that when i creat a new project with documents, the foreign key of the documents is the PK from the new project.

Edit: When i add the foreign key manually in the database and then delete the project the documents with the foreign key alse gets deleted (just to point out that the association is correct..!)

Please help me out, thank you!

-----------------ProjectController.php:

 /**
 * Displays a form to create a new Project entity.
 *
 * @Route("/new", name="project_new")
 * @Method("GET")
 * @Template()
 */
public function newAction() {
    $entity = new Project();
    $form = $this->createCreateForm($entity);

    return array(
        'entity' => $entity,
        'form' => $form->createView(),
    );
}

/**
 * Creates a form to create a Project entity.
 *
 * @param Project $entity The entity
 *
 * @return \Symfony\Component\Form\Form The form
 */
private function createCreateForm(Project $entity) {
    $form = $this->createForm(new ProjectType(), $entity, array(
        'action' => $this->generateUrl('project_create'),
        'method' => 'POST',
    ));

    $form->add('submit', 'submit', array('label' => 'Create project'));

    return $form;
}

/**
 * Creates a new Project entity.
 *
 * @Route("/", name="project_create")
 * @Method("POST")
 * @Template("AcmeDemoBundle:Project:new.html.twig")
 */
public function createAction(Request $request) {
    $entity = new Project();
    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);
    $entity->setDateCreated(new \DateTime());

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('project_show', array('id' => $entity->getId())));
    }

    return array(
        'entity' => $entity,
        'form' => $form->createView(),
    );
}

-----------------ProjectType.php:

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options) {
    $builder
            ->add('name')
            ->add('date_executed')
            ->add('imageprojects', 'collection', array(
                'type'          => new DocumentType(),
                'allow_add'     => true,
                'allow_delete'  => true,
                'by_reference'  => false
                ))
    ;
}

/**
 * @param OptionsResolverInterface $resolver
 */
public function setDefaultOptions(OptionsResolverInterface $resolver) {
    $resolver->setDefaults(array(
        'data_class' => 'Acme\DemoBundle\Entity\Project',
        'cascade_validation' => false,
    ));
}

/**
 * @return string
 */
public function getName() {
    return 'project';
}

---------------Project.php (Entity):

 /**
 * @ORM\Column(type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 *
 * @ORM\Column(type="string")
 */
protected $name;

/**
 *
 * @ORM\Column(type="date")
 */
protected $date_executed;

/**
 *
 * @ORM\Column(type="date")
 */
protected $date_created;

/**
 * @ORM\OneToMany(targetEntity="Document", mappedBy="project_id", cascade={"persist", "remove"})
 */
protected $imageprojects;

public function __construct() {
    $this->imageprojects = new ArrayCollection();
}

function __toString() {
    return $this->getName();
}

/**
 * Get id
 *
 * @return integer 
 */
public function getId()
{
    return $this->id;
}

/**
 * Set name
 *
 * @param string $name
 * @return Project
 */
public function setName($name)
{
    $this->name = $name;

    return $this;
}

/**
 * Get name
 *
 * @return string 
 */
public function getName()
{
    return $this->name;
}

/**
 * Set date_executed
 *
 * @param \DateTime $dateExecuted
 * @return Project
 */
public function setDateExecuted($dateExecuted)
{
    $this->date_executed = $dateExecuted;

    return $this;
}

/**
 * Get date_executed
 *
 * @return \DateTime 
 */
public function getDateExecuted()
{
    return $this->date_executed;
}

/**
 * Set date_created
 *
 * @param \DateTime $dateCreated
 * @return Project
 */
public function setDateCreated($dateCreated)
{
    $this->date_created = $dateCreated;

    return $this;
}

/**
 * Get date_created
 *
 * @return \DateTime 
 */
public function getDateCreated()
{
    return $this->date_created;
}

/**
 * Add projectimages
 *
 * @param \Acme\DemoBundle\Entity\Document $projectimages
 * @return Project
 */
public function addImageproject(Document $projectimages)
{
    //$this->imageprojects[] = $imageprojects;
    $projectimages->addProjectimage($this);

    $this->imageprojects->add($projectimages);

    return $this;
}

/**
 * Remove projectimages
 *
 * @param \Acme\DemoBundle\Entity\Document $projectimages
 */
public function removeImageproject(Document $projectimages)
{
    $this->imageprojects->removeElement($projectimages);
}

/**
 * Get imageprojects
 *
 * @return \Doctrine\Common\Collections\Collection 
 */
public function getImageprojects()
{
    return $this->imageprojects;
}

------------------Document.php (Entity)

/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
public $id;

/**
 * @ORM\ManyToOne(targetEntity="Project", inversedBy="imageprojects")
 * @ORM\JoinColumn(name="project_id", referencedColumnName="id", onDelete="CASCADE")
 */
protected $project_id;

/**
 * @ORM\Column(type="string", length=255)
 * @Assert\NotBlank
 */
public $name;

/**
 * @ORM\Column(type="string", length=255, nullable=true)
 */
public $path;

public function getAbsolutePath() {
    return null === $this->path ? null : $this->getUploadRootDir() . '/' . $this->id . '.' . $this->path;
}

public function getWebPath() {
    return null === $this->path ? null : $this->getUploadDir() . '/' . $this->path;
}

protected function getUploadRootDir() {
    // the absolute directory path where uploaded
    // documents should be saved
    return __DIR__ . '/../../../../web/' . $this->getUploadDir();
}

protected function getUploadDir() {
    // get rid of the __DIR__ so it doesn't screw up
    // when displaying uploaded doc/image in the view.
    return 'imgupload';
}

/**
 * @Assert\File(maxSize="6000000")
 */
private $file;

/**
 * Sets file.
 *
 * @param UploadedFile $file
 */
public function setFile(UploadedFile $file = null) {
    $this->file = $file;
    // check if we have an old image path
    if (is_file($this->getAbsolutePath())) {
        // store the old name to delete after the update
        $this->temp = $this->getAbsolutePath();
    } else {
        $this->path = 'initial';
    }
}

/**
 * Get file.
 *
 * @return UploadedFile
 */
public function getFile() {
    return $this->file;
}

/**
 * @ORM\PrePersist()
 * @ORM\PreUpdate()
 */
public function preUpload() {
    if (null !== $this->getFile()) {
        $this->path = $this->getFile()->guessExtension();
    }
}

/**
 * @ORM\PostPersist()
 * @ORM\PostUpdate()
 */
public function upload() {
    if (null === $this->getFile()) {
        return;
    }

    // check if we have an old image
    if (isset($this->temp)) {
        // delete the old image
        unlink($this->temp);
        // clear the temp image path
        $this->temp = null;
    }

    // you must throw an exception here if the file cannot be moved
    // so that the entity is not persisted to the database
    // which the UploadedFile move() method does
    $this->getFile()->move(
            $this->getUploadRootDir(), $this->id . '.' . $this->getFile()->guessExtension()
    );

    $this->setFile(null);
}

/**
 * @ORM\PreRemove()
 */
public function storeFilenameForRemove() {
    $this->temp = $this->getAbsolutePath();
}

/**
 * @ORM\PostRemove()
 */
public function removeUpload() {
    if (isset($this->temp)) {
        unlink($this->temp);
    }
}

/**
 * Get id
 *
 * @return integer 
 */
public function getId() {
    return $this->id;
}

/**
 * Set name
 *
 * @param string $name
 * @return Document
 */
public function setName($name) {
    $this->name = $name;

    return $this;
}

/**
 * Get name
 *
 * @return string 
 */
public function getName() {
    return $this->name;
}

/**
 * Set path
 *
 * @param string $path
 * @return Document
 */
public function setPath($path) {
    $this->path = $path;

    return $this;
}

/**
 * Get path
 *
 * @return string 
 */
public function getPath() {
    return $this->path;
}

/**
 * Add projectimages
 *
 * @param \Acme\DemoBundle\Entity\Project $projectimages
 * @return Document
 */
public function addProjectimage(Project $projectimages) {
    $this->projectimages[] = $projectimages;
    /*
    if (!$this->projectimages->contains($projectimages)) {
        $this->projectimages->add($projectimages);
    }
     */
    return $this;
}

/**
 * Remove projectimages
 *
 * @param \Acme\DemoBundle\Entity\Project $projectimages
 */
public function removeProjectimage(Project $projectimages) {
    $this->projectimages->removeElement($projectimages);
}

/**
 * Get projectimages
 *
 * @return \Doctrine\Common\Collections\Collection 
 */
public function getProjectimages() {
    return $this->projectimages;
}

/**
 * Set project_id
 *
 * @param \Acme\DemoBundle\Entity\Project $projectId
 * @return Document
 */
public function setProjectId(\Acme\DemoBundle\Entity\Project $projectId = null) {
    $this->project_id = $projectId;

    return $this;
}

/**
 * Get project_id
 *
 * @return \Acme\DemoBundle\Entity\Project 
 */
public function getProjectId() {
    return $this->project_id;
}
Lex Hartman
  • 148
  • 6
  • 16

1 Answers1

0

OK, it was a matter of 'bad reading'...! The solution was already posted for this question: [Persistence with embedded forms

Community
  • 1
  • 1
Lex Hartman
  • 148
  • 6
  • 16