Answer the question
In order to leave comments, you need to log in
What is the correct way to make a many-to-many relationship in Symfony?
There are two entities News and User .
When updating the first, in the author field you need to specify the ID of the current user.
I do this one like this:
->add('author', 'hidden', array('data' => $this->securityContext->getToken()->getUser()->getId()))
/**
* @var $newsCategory
*
* @ORM\ManyToOne(targetEntity="\Sector\UserBundle\Entity\User", inversedBy="id")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="author", referencedColumnName="id")
* })
* })
* @Assert\NotBlank
*/
private $author;
/**
* Set author
*
* @param \Sector\UserBundle\Entity\User $author
*/
public function setAuthor(\Sector\UserBundle\Entity\User $author)
{
$this->author = $author;
}
/**
* Get author
*
* @return \Sector\UserBundle\Entity\User
*/
public function getAuthor()
{
return $this->author;
}
ContextErrorException: Catchable Fatal Error: Argument 1 passed to Sector\ArticlesBundle\Entity\News::setAuthor() must be an instance of Sector\UserBundle\Entity\User, string given, called in /Users/roman/Development/Sites/Sector.dev/vendor/symfony/symfony/src/Symfony/Component/PropertyAccess/PropertyAccessor.php on line 377 and defined in /Users/roman/Development/Sites/Sector.dev/src/Sector/ArticlesBundle/Entity/News.php line 341
Answer the question
In order to leave comments, you need to log in
How do you create a form? In a controller, you would normally create something like this:
$news = new News();
$news->setUser($this->getUser());
$form = $this->createForm(new NewsType(), $news);
If you do not need to display a field for selecting a user, I would remove the user from the form altogether. And hung up on the creation of news, user installation. For example on prePersist
Here is the list of events.
doctrine-orm.readthedocs.org/en/latest/reference/e...
In the Many to Many question, in the Many to One code...
Firstly, incorrect annotations, Read the documentation
Secondly, the methods... In theory, for Many to One, the default value is null (setAuthor( $author = null)). The validator will not give you an empty value when submitting the form...
And you don't need to insert it into the form as a hidden field, it's more logical to add the Author before writing directly to the database.
if ($form->isValid()) {
$entity->setAuthor( $this->getUser() );
$entity->flush();
}
In the sonata this is also easy .
If Many To Many, then there must be methods for working with the collection. add, remove, get... As well as joining tables, not columns.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question