UXerUIer
UXerUIer

Reputation: 2338

Inserting into DB the association established in Doctrine/Symfony 4

My user class in Symfony 4:

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;

    /**
     * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
     * @UniqueEntity(fields={"email"}, message="There is already an account with this email")
     */
    class User implements UserInterface
    {
        /**
         * @ORM\Id()
         * @ORM\GeneratedValue()
         * @ORM\Column(type="integer")
         */
        private $id;

    // ... rest of the User Entity
    }

I created another entity called "Creator" like so:

// src/Entity/Creator.php
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\ProductRepository")
 */
class Creator
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\OneToOne(targetEntity="App\Entity\User", inversedBy="creator")
     */
    private $user;


    public function getId(): ?int
    {
        return $this->id;
    }

    public function createCreator($userid)
    {
        $this->user->id = $userid;

        return $this;
    }

    public function getUser(): ?User
    {
        return $this->user;
    }

    // ... getter and setter methods
}

The association between the two is when the user registers as a "creator" (outside of the context of just registering as a "regular user"), the insert associates the creator with the user.

Inserting into the DB is like so:

$user    = new User();
$creator = new Creator();
$form    = $this->createForm(CreatorRegistrationForm::class, [$user, $creator]);
$form->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
    $user
        ->setEmail($form->get('email')->getData())
        ->setPassword(
                $passwordEncoder->encodePassword(
                    $user,
                    $form->get('password')->getData()
                )
            )
            ->setFirstName($form->get('firstname')->getData())
            ->setLastName($form->get('lastname')->getData())
            ->setBirthday($form->get('birthday')->getData());

            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            $entityManager->flush(); //This insert is successful :)

            $userID = $user->getId();

            $creator->createCreator($userID);

            $entityManager->persist($creator);
            $entityManager->flush();
            // This does nothing.
            // Can you only persist/flush once? If so, what is the right syntax?

            return $guardHandler->authenticateUserAndHandleSuccess(
                $user,
                $request,
                $authenticator,
                'main' // firewall name in security.yaml
            );
        }

Is this the correct way to create an association in the DB via doctrine? Still trying to understand how associations work. Do you have to explicitly state the associations similarly to what is above? This returns an error of Warning: Creating default object from empty value and it points this:

public function createCreator($userid)
{        
    $this->user->id = $userid; //this here is what the error points to.

    return $this;    
}

What's the right approach to doing this?

Upvotes: 1

Views: 68

Answers (1)

yivi
yivi

Reputation: 47300

Doctrine expects Creator->user to be an object of the User class.

So you'd probably need a Creator::setUser(User) method, and do something like this:

//...
$entityManager->persist($user);
$creator->setUser($user);
$entityManager->persist($creator);

$entityManaer->flush();

Upvotes: 1

Related Questions