Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8742545
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T11:31:21+00:00 2026-06-13T11:31:21+00:00

I’m trying to handle a form which is quite complex for me… We have

  • 0

I’m trying to handle a form which is quite complex for me…

We have Collections, which contain books (OneToMany), with articles(OneToMany) and their authors (ManyToMany).

The user can edit a book: he can add or remove an article, and add or remove some authors for each article. There are nested forms : book>article>author.
If the author is new in the Collection, it is created for that Collection.

Entities descriptions look fine, database is generated by the console and seems consistent.

This is working fine if I don’t have to deal with authors using the book edition form. If the author exists, I have a duplicate entry bug. If the author is new, I have a “Explicitly persist the new entity or configure cascading persist operations on the relationship” bug.

Here is the code:

public function onSuccess(Book $book)
{   
    $this->em->persist($book);

    foreach($book->getArticles() as $article)  
    {
        $article->setUrlname($this->mu->generateUrlname($article->getName()));
        $article->setBook($book);

        // Saving (and creating) the authors of the book
        foreach ($this->collectionWithAuthors->getAuthors() as $existAuthor){      
            foreach($article->getAuthors() as $author) {                        
                $authorUrlname=$this->mu->generateUrlname($author->getFirstname().' '.$author->getLastname());
                if ( $existAuthor->getUrlname() ==  $authorUrlname) { // The author is existing
                    $article->addAuthor($existAuthor);
                    $this->em->persist($existAuthor);
                }else{                                                // New Author
                    $newAuthor = new Author();                                
                    $newAuthor->setCollection($this->collectionWithBaseArticles);
                    $newAuthor->setLastname($author->getLastname());
                    $newAuthor->setFirstname($author->getFirstname());
                    $newAuthor->setUrlname($authorUrlname);
                    $this->em->persist($newAuthor);
                    $article->addAuthor($newAuthor);                          
                }
            }
        }
        $this->em->persist($article);

    }
    $this->em->flush();

}

I don’t know how to use cascades. But the $article->addAuthor() is supposed to call $authors->addArticle():

Article Entity extract

/**
* @ORM\ManyToMany(targetEntity="bnd\myBundle\Entity\Author", mappedBy="articles")
*/
private $authors;

/**
 * Add authors
 *
 * @param bnd\myBundle\Entity\Author $authors
 * @return Article
 */

public function addAuthor(\bnd\myBundle\Entity\Author $authors)
{
    $this->authors[] = $authors;
    $authors->addArticle($this);
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T11:31:22+00:00Added an answer on June 13, 2026 at 11:31 am

    The logic in foreach statement is wrong. Suppose we have next authors:

    1. Persisted authors (collectionWithAuthors):
      • John
      • Eric
    2. Submitted authors
      • Ada
      • Eric

    So for every existing author (John and Eric) the script loop thru new authors:

    foreach ([John, Eric] as $author) {
        foreach([Ada, Eric] as $newAuthor) {
            // John author: the script persist Ada(right) and Eric(wrong) as new authors
            // Eric author: the script persist Ada(wrong), but not Eric(right)
        }
    }
    

    The solution is to replace article authors with existing authors (if there is similar)

    foreach ($article->getAuthors() as $key => $articleAuthor) {
        $authorUrlname=$this->mu->generateUrlname($articleAuthor->getFirstname().' '.$articleAuthor->getLastname());
        $foundAuthor = false;
        // Compare article author with each existing author
        foreach ($this->collectionWithAuthors->getAuthors() as $existAuthor) { 
            if ($existAuthor->getUrlname() ==  $authorUrlname) {
                $foundAuthor = true;
                break; // It has found similar author no need to look further
            }
        }
    
        // Use $existAuthor as found one, otherwise use $articleAuthor
        if ($foundAuthor) {
            $article->removeAuthor($articleAuthor); // Remove submitted author, so he wont be persisted to database
            $article->addAuthor($existAuthor);
        } else {
            // Here you dont need to create new author                          
            $articleAuthor->setCollection($this->collectionWithBaseArticles);
            $articleAuthor->setUrlname($authorUrlname);
        }
    
        ...
    }
    
    $this->_em->persist($article);
    

    You have noticed i removed any author persistent from the loop, to persist these authors its better to set cascade={‘persist’} in $authors annotation of Article Entity Class

    /**
     * @ORM\ManyToMany(targetEntity="Author", cascade={"persist"})
     * @ORM\JoinTable(...)
     */
    protected $authors;
    

    UPD:

    I forgot to mention one thing about cascade persistent. To persist relation betweed article and author you also have to add relation to author entity. Edit the addAuthor() method in the Article entity as below:

    public function addAuthor(Author $author)
    {
        // Only add author relation if the article does not have it already
        if (!$this->authors->contains($author)) {
            $this->authors[] = $author;
            $author->addArticle($this);
        }
    }
    

    Also, it’s a good practice to define default values for a collection of entities in the constructor:

    use Doctrine\Common\Collections\ArrayCollection;
    
    // ...
    
    public function __construct()
    {
        $this->authors = new ArrayCollection();
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a text area in my form which accepts all possible characters from
I am trying to understand how to use SyndicationItem to display feed which is
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I have an autohotkey script which looks up a word in a bilingual dictionary
I'm trying to select an H1 element which is the second-child in its group
I have an array which has BIG numbers and small numbers in it. I
I am trying to loop through a bunch of documents I have to put
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.