craphunter
craphunter

Reputation: 981

Save Object in table related to another

How can I create a new object when a cell is related to another table? In my case there exist a table with states, like id=1,state=active;id=2,state=inactive.

My Entity/States.php

class States
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer", nullable=false)
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $id;
....

Entity/User.php

 ....
 /**
 * Set state
 *
 * @param \Frontend\AccountBundle\Entity\States $state
 * @return User
 */
public function setState(\Frontend\AccountBundle\Entity\States $state = null)
{
    $this->state = $state;

    return $this;
}

My AccountController:

....
$user = new User();
$em = $this->get('doctrine')->getEntityManager();
$state = $this->getDoctrine()->getRepository('FrontendAccountBundle:States')->find(1);

$user->setEmail($formData->getEmail());
$user->setStateId(1);
$em->persist($user);
$em->flush();

This is not working and way to complicated: http://symfony.com/doc/current/book/doctrine.html#relationship-mapping-metadata. It was so freaking easy in symfony1.4.

Upvotes: 1

Views: 984

Answers (2)

juanitourquiza
juanitourquiza

Reputation: 2194

This solution works for me: https://stackoverflow.com/a/14131067/2400373

But in Symfony 4 change the line of getRepository:

$role = $this->getDoctrine()
                ->getRepository(Role::class)
                ->find(1);
$usuario->setRole($role);

Upvotes: 0

Thomas Kelley
Thomas Kelley

Reputation: 10292

Your User entity has a method setState(), which takes a single parameter of $state. That parameter must be of type \Frontend\AccountBundle\Entity\States.

In your controller, you obtain that object through this call:

$state = $this->getDoctrine()->getRepository('FrontendAccountBundle:States')->find(1);

So when you go to set the State of the User, you don't need to bother with IDs. Rather, just set the State directly, and Doctrine will take care of the rest:

$user->setState($state);

Upvotes: 2

Related Questions