Search code examples
symfonyentityfosuserbundle

FosUserBundle Registration, which saves data into 2 different tables


I am using FOSUserbundle in symfony 3 and want to use a second table, where I save the address data.

Therefore I use the extended User Entity and the addresses Entity.

Workflow:

f.e. first_name,last_name,company and all other Formdata should go to md_user table.

copy of first_name,last_name,company etc should go to md_addresses table, which has got the "customer_id" field of md_user.id

To get it working I use the Eventlistener in RegistrationType:

->addEventListener(FormEvents::POST_SUBMIT, array($this, 'onPreSetData'));

and the method:

 public function onPreSetData(FormEvent $event)
{
    $user = $event->getData();
    $user->addAddress(new Addresses());
    $event->setData($user);

}

Before I use $event->setData($user) in RegistrationType, the $user looks like:

enter image description here

My Questions are:

1) How to get the back the field id of md_user from doctrine

2) How to save the other data with this id to md_addresses

Thats what I have done right now.

User Entity:

namespace AppBundle\Entity;


 class User extends BaseUser
{

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

    /**
     * Different Logins for One Customer
     * @ORM\Column(name="customer_id",type="integer",nullable=true,options={"default":null})
     * @ORM\OneToMany(targetEntity="Addresses", mappedBy="user", cascade={"persist","remove"})
     **/
    protected $customer_id;

    /**
      * @var \DateTime
      * @ORM\Column(name="created", type="datetime")
      */
     protected $created;

     /**
      * @ORM\Column(name="mandant",type="integer")
      */
    protected $mandant;

     /**
      * @var string
      * @ORM\Column(name="salutation", type="string", length=1)
      */
     protected $salutation;

     /**
      * @var string
      * @ORM\Column(name="first_name", type="string", length=120)
      * @Assert\Length(
      *     min=2,
      *     max=120,
      *     minMessage="The name is too short.",
      *     maxMessage="The name is too long.",
      *     groups={"Registration", "Profile"}
      * )
      */
     protected $first_name;

     /**
      * @var string
      * @ORM\Column(name="last_name", type="string", length=255)
      * @Assert\Length(
      *     min=2,
      *     max=255,
      *     minMessage="The name is too short.",
      *     maxMessage="The name is too long.",
      *     groups={"Registration", "Profile"}
      * )
      */
     protected $last_name;

     /**
      * @var string
      * @ORM\Column(name="company", type="string", length=255)
      */
     protected $company;

     /**
      * @var string
      * @ORM\Column(type="string", type="string", length=150)
      */
     protected $street;

     /**
      * @var string
      * @ORM\Column(type="string", type="string", length=30)
      */
     protected $street_number;

     /**
      * @var string
      * @ORM\Column(type="string", type="string", length=150)
      */
     protected $city;

     /**
      * @var string
      * @ORM\Column(type="string", type="string", length=150)
      */
     protected $plz;

     /**
      * @var string
      * @ORM\Column(name="ustid", type="string", length=30)
      */
     protected $ustid;

     /**
      * @var string
      * @ORM\Column(name="country", type="string", length=6)
      */
     protected $country;

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

     /**
      * @ORM\Column(name="email_info", type="string",length=255,nullable=true)
      */
     protected $email_info;
     /**
      * @ORM\Column(name="email_invoice", type="string",length=255,nullable=true)
      */
     protected $email_invoice;

     /**
      * @ORM\Column(name="send_info", type="boolean",nullable=true)
      */
     protected $send_info = true;

     /**
      * @ORM\Column(name="invoice_pdf", type="boolean",nullable=true)
      */
     protected $invoice_pdf = true;

     /**
      * @ORM\OneToMany(targetEntity="AppBundle\Entity\Addresses", mappedBy="customer_id", cascade={"persist","remove"})
      */
     protected $addresses;
     /**
      * @var bool
      * @ORM\Column(name="newsletter", type="boolean")
      */
     protected $newsletter=true;


     public function __construct()
     {
         parent::__construct();
         $this->created         = new \DateTime();
//         $this->addresses              = new ArrayCollection();
     }


     /**
      * @return mixed
      */
     public function getEmailInfo()
     {
         return $this->email_info;
     }

     public function setEmailInfo($email_info)
     {
         $this->email_info = is_null($email_info) ? $this->email : $email_info;
         return $this;
     }

     public function getEmailInvoice()
     {
         return $this->email_invoice;
     }

     /**
      * @param mixed $email_invoice
      * @return User
      */
     public function setEmailInvoice($email_invoice)
     {
         $this->email_invoice = is_null($email_invoice) ? $this->email : $email_invoice;
         return $this;
     }

     /**
      * @return mixed
      */
     public function getInvoicePdf()
     {
         return $this->invoice_pdf;
     }

     /**
      * @param mixed $invoice_pdf
      * @return User
      */
     public function setInvoicePdf($invoice_pdf)
     {
         $this->invoice_pdf = $invoice_pdf;
         return $this;
     }

     /**
      * @return mixed
      */
     public function getSendInfo()
     {
         return $this->send_info;
     }

     /**
      * @param mixed $send_info
      * @return User
      */
     public function setSendInfo($send_info)
     {
         $this->send_info = $send_info;
         return $this;
     }





     public function getTelephone()
     {
         return $this->telephone;
     }

     /**
      * @param mixed $telephone
      * @return User
      */
     public function setTelephone($telephone)
     {
         $this->telephone = $telephone;
         return $this;
     }


     public function setEmail($email)
     {
         $email = is_null($email) ? '' : $email;
         parent::setEmail($email);
         $this->setUsername($email);
         return $this;
     }

     /**
      * @return string
      */
     public function getSalutation()
     {
         return $this->salutation;
     }

     /**
      * @param string $saluation
      * @return User
      */
     public function setSalutation($salutation)
     {
         $this->salutation = $salutation;
         return $this;
     }

     /**
      * @return string
      */
     public function getFirstName()
     {
         return $this->first_name;
     }

     /**
      * @param string $first_name
      * @return User
      */
     public function setFirstName($first_name)
     {

         $this->first_name = $first_name;
         return $this;
     }

     /**
      * @return string
      */
     public function getLastName()
     {
         return $this->last_name;
     }

     /**
      * @param string $last_name
      * @return User
      */
     public function setLastName($last_name)
     {
         $this->last_name = $last_name;
         return $this;
     }

     /**
      * @return string
      */
     public function getCompany()
     {
         return $this->company;
     }

     /**
      * @param string $company
      * @return User
      */
     public function setCompany($company)
     {
         $this->company = $company;
         return $this;
     }

     /**
      * @return string
      */
     public function getUstid()
     {
         return $this->ustid;
     }

     /**
      * @param string $ustid
      * @return User
      */
     public function setUstid($ustid)
     {
         $this->ustid = $ustid;
         return $this;
     }


     public function getName()
     {
         return 'user';
     }

     /**
      * @return mixed
      */
     public function getMandant()
     {
         return $this->mandant;
     }

     /**
      * @param mixed $mandant
      * @return User
      */
     public function setMandant($mandant)
     {
         $this->mandant = $mandant;
         return $this;
     }

     /**
      * @return string
      */
     public function getCity()
     {
         return $this->city;
     }

     /**
      * @param string $city
      * @return User
      */
     public function setCity($city)
     {
         $this->city = $city;
         return $this;
     }

     /**
      * @return string
      */
     public function getCountry()
     {
         return $this->country;
     }

     /**
      * @param string $country
      * @return User
      */
     public function setCountry($country)
     {
         $this->country = $country;
         return $this;
     }

     /**
      * @return string
      */
     public function getStreet()
     {
         return $this->street;
     }

     /**
      * @param string $street
      * @return User
      */
     public function setStreet($street)
     {
         $this->street = $street;
         return $this;
     }

     /**
      * @return string
      */
     public function getStreetNumber()
     {
         return $this->street_number;
     }

     /**
      * @param string $street_number
      * @return User
      */
     public function setStreetNumber($street_number)
     {
         $this->street_number = $street_number;
         return $this;
     }

     /**
      * @return string
      */
     public function getPlz()
     {
         return $this->plz;
     }

     /**
      * @param string $plz
      * @return User
      */
     public function setPlz($plz)
     {
         $this->plz = $plz;
         return $this;
     }

     /**
      * Set created
      *
      * @param \DateTime $created
      *
      * @return User
      */
     public function setCreated($created)
     {
         $this->created = $created;

         return $this;
     }

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



     /**
      * @return mixed
      */
     public function getCustomerId()
     {
         return $this->customer_id;
     }

     /**
      * @param mixed $customer_id
      * @return User
      */
     public function setCustomerId($customer_id)
     {
         $this->customer_id = $customer_id;
         return $this;
     }

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

     /**
      * Set newsletter
      * @param boolean $newsletter
      * @return User
      */
     public function setNewsletter($newsletter)
     {
         $this->newsletter = $newsletter;

         return $this;
     }

     /**
      * Get newsletter
      * @return bool
      */
     public function getNewsletter()
     {
         return $this->newsletter;
     }

     /**
      * Add professional
      *
      * @param \AppBundle\Entity\Addresses $addresses
      *
      * @return User
      */
     public function addAddress(\AppBundle\Entity\Addresses $addresses)
     {
         $addresses->setSalutation($this->salutation);
         $addresses->setFirstName($this->first_name);
         $addresses->setLastName($this->last_name);
         $addresses->setEmail($this->email);
         $addresses->setTelephone($this->telephone);
         $addresses->setStreet($this->street);
         $addresses->setStreetNumber($this->street_number);
         $addresses->setPlz($this->plz);
         $addresses->setCity($this->city);
         $addresses->setCountry($this->country);
         $addresses->setCompany($this->company);
         $addresses->setInvoice(true);
         $addresses->setDelivery(true);
         $addresses->setCustomerId($this->id);
         return $this->addresses = $addresses;
     }
     /**
      * Get addresses
      *
      * @return \Doctrine\Common\Collections\Collection
      */
     public function getAddresses()
     {
         return $this->addresses;
     }

     public function getFullName()
     {
         return $this->first_name.' '.$this->last_name;
     }
 }

Addresses Entity:

namespace AppBundle\Entity;


use Doctrine\ORM\Mapping as ORM;



/**
 * @ORM\Table(name="md_addresses")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\AddressesRepository")
 */


class Addresses
{
    /**
     * @var id

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

    /**
     * @ORM\Column(name="customer_id", type="integer")
     * @ORM\ManyToOne(targetEntity="User", inversedBy="addresses", cascade={"persist"})
     * @ORM\JoinColumn(name="customer_id", referencedColumnName="id")
     */
    protected $customer_id;


    /**
     * @ORM\Column(name="salutation", type="string",length=1)
     */
    protected $salutation;
    /**
     * @var string
     * @ORM\Column(name="first_name", type="string", length=120)
     */

    protected $first_name;

    /**
     * @var string
     * @ORM\Column(name="last_name", type="string", length=255)
     */

    protected $last_name;

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

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

    /**
     * @var string
     * @ORM\Column(name="company", type="string", length=255)
     */
    protected $company;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $street;

    /**
     * @ORM\Column(type="string", length=30)
     */
    protected $street_number;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $additional_1;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $additional_2;

    /**
     * @ORM\Column(type="string", length=255)
     */
    protected $additional_3;

    /**
     * @ORM\Column(type="string", length=30)
     */
    protected $plz;
    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $city;

    /**
     * @ORM\Column(type="string", length=10)
     */

    protected $country;
    /**
     * @ORM\Column(type="boolean", options={"default":true})
     */

    protected $invoice;
    /**
     * @ORM\Column(type="boolean", options={"default":true})
     */

    protected $sender;
    /**
     * @ORM\Column(type="boolean", options={"default":true})
     */
    protected $delivery;




      /**
     * @return mixed
     */
    public function getSalutation()
    {
        return $this->salutation;
    }

    /**
     * @param mixed $salutation
     * @return Addresses
     */
    public function setSalutation($salutation)
    {
        $this->salutation = $salutation;
        return $this;
    }



    /**
     * @return string
     */
    public function getCompany()
    {
        return $this->company;
    }

    /**
     * @param string $company
     * @return Addresses
     */
    public function setCompany($company)
    {
        $this->company = $company;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getStreet()
    {
        return $this->street;
    }

    /**
     * @param mixed $street
     * @return Addresses
     */
    public function setStreet($street)
    {
        $this->street = $street;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getStreetNumber()
    {
        return $this->street_number;
    }

    /**
     * @param mixed $street_number
     * @return Addresses
     */
    public function setStreetNumber($street_number)
    {
        $this->street_number = $street_number;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getAdditional1()
    {
        return $this->additional_1;
    }

    /**
     * @param mixed $additional_1
     * @return Addresses
     */
    public function setAdditional1($additional_1)
    {
        $this->additional_1 = $additional_1;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getAdditional2()
    {
        return $this->additional_2;
    }

    /**
     * @param mixed $additional_2
     * @return Addresses
     */
    public function setAdditional2($additional_2)
    {
        $this->additional_2 = $additional_2;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getAdditional3()
    {
        return $this->additional_3;
    }

    /**
     * @param mixed $additional_3
     * @return Addresses
     */
    public function setAdditional3($additional_3)
    {
        $this->additional_3 = $additional_3;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getPlz()
    {
        return $this->plz;
    }

    /**
     * @param mixed $plz
     * @return Addresses
     */
    public function setPlz($plz)
    {
        $this->plz = $plz;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getCity()
    {
        return $this->city;
    }

    /**
     * @param mixed $city
     * @return Addresses
     */
    public function setCity($city)
    {
        $this->city = $city;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getCountry()
    {
        return $this->country;
    }

    /**
     * @param mixed $country
     * @return Addresses
     */
    public function setCountry($country)
    {
        $this->country = $country;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getInvoice()
    {
        return $this->invoice;
    }

    /**
     * @param mixed $invoice
     * @return Addresses
     */
    public function setInvoice($invoice)
    {
        $this->invoice = $invoice;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getSender()
    {
        return $this->sender;
    }

    /**
     * @param mixed $sender
     * @return Addresses
     */
    public function setSender($sender)
    {
        $this->sender = $sender;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getDelivery()
    {
        return $this->delivery;
    }

    /**
     * @param mixed $delivery
     * @return Addresses
     */
    public function setDelivery($delivery)
    {
        $this->delivery = $delivery;
        return $this;
    }


    /**
     * Set user
     * @param \AppBundle\Entity\User $user
     * @return Addresses
     */
    public function setCustomerId(\AppBundle\Entity\User $customer_id = null)
    {
        $this->customer_id = $customer_id;

        return $this;
    }

    /**
     * Get user
     * @return \AppBundle\Entity\User
     */
    public function getCustomerId()
    {
        return $this->customer_id;
    }

    /**
     * @return string
     */
    public function getFirstName()
    {
        return $this->first_name;
    }

    /**
     * @param string $first_name
     * @return Addresses
     */
    public function setFirstName($first_name)
    {
        $this->first_name = $first_name;
        return $this;
    }

    /**
     * @return string
     */
    public function getLastName()
    {
        return $this->last_name;
    }

    /**
     * @param string $last_name
     * @return Addresses
     */
    public function setLastName($last_name)
    {
        $this->last_name = $last_name;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getTelephone()
    {
        return $this->telephone;
    }

    /**
     * @param mixed $telephone
     * @return Addresses
     */
    public function setTelephone($telephone)
    {
        $this->telephone = $telephone;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getEmail()
    {
        return $this->email;
    }

    /**
     * @param mixed $email
     * @return Addresses
     */
    public function setEmail($email)
    {
        $this->email = $email;
        return $this;
    }



}

RegistrationType:

class RegistrationType extends AbstractType
{

    private $session;
    public function __construct(Session $session)
    {
        $this->session = $session;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        parent::buildForm($builder, $options);


        $builder ->add('salutation', SalutationType::class,
                        array('placeholder'   => 'form.choice'))
                 ->add('telephone',     TextType::class,array('required' => false))
                 ->remove('username')
                 ->add('first_name',    TextType::class)
                 ->add('mandant',    HiddenType::class,array('data'=>$this->session->get('mandantId')))
                 ->add('last_name',     TextType::class)
                 ->add('company',       TextType::class,array('required' => false))
                 ->add('street',         TextType::class)
                 ->add('street_number',  TextType::class)
                 ->add('ustid',         TextType::class,array('required' => false))
                 ->add('plz', TextType::class)
                 ->add('city', TextType::class)
                 ->add('newsletter',CheckboxType::class,array('label' => false,'required' => false))
                 ->add('country', CountryType::class, [
                    'required' => true,
                    'placeholder' => 'form.choice',
                    'preferred_choices' => [
                        'DE', 'NL', 'BE', 'CH', 'AUT',
                    ]])
                  ->addEventListener(FormEvents::POST_SUBMIT, array($this, 'onPreSetData'));



    }

    public function onPreSetData(FormEvent $event)
    {
        $user = $event->getData();
        $user->addAddress(new Addresses());

        $event->setData($user);

    }

    public function getParent()

    {
        return 'FOS\UserBundle\Form\Type\RegistrationFormType';
    }

    public function getBlockPrefix()

    {
        return 'app_user_registration';
    }

    public function getName()

    {
        return $this->getBlockPrefix();
    }

}

UPDATE:

class RegistrationSubscriber implements EventSubscriberInterface
{

    private $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public static function getSubscribedEvents()
    {
        return [
            FOSUserEvents::REGISTRATION_COMPLETED => [
                ['onRegistrationSuccess']
                ],
            ];
    }

    public function onRegistrationSuccess(FilterUserResponseEvent $event)
    {
        $user = $event->getUser();
        $address = new Address();
        $address->setSalutation($user->getSalutation());
        $address->setFirstName($user->getFirstName());
        $address->setLastName($user->getLastName());
        $address->setEmail($user->getEmail());
        $address->setTelephone($user->getTelephone());
        $address->setStreet($user->getStreet());
        $address->setStreetNumber($user->getStreetNumber());
        $address->setPlz($user->getPlz());
        $address->setCity($user->getCity());
        $address->setCountry($user->getCountry());
        $address->setCompany($user->getCompany());
        $address->setCustomerId($user->getId());
        $user->addAddress($address);
        $this->em->persist($user);
        $this->em->flush();
    }


}

Solution

  • As Greg said it's easy to get the id from doctrine through the FOSUserBundle

    Now, for the second part I would suggest you use a Collection In your User entity add an ArrayCollection property for your addresses. And declare the methods to add a new collection to the user object.

    <?php
    
    namespace AppBundle\Entity;
    
    /**
     * User
     */
    class User
    {
    
        /**
         * @var \Doctrine\Common\Collections\Collection
         */
        private $addresses;
    
    
        /**
         * Constructor
         */
        public function __construct()
        {
    
            $this->addresses = new \Doctrine\Common\Collections\ArrayCollection();
        }
    
        /**
         * Add address
         *
         * @param \AppBundle\Entity\Address $address
         *
         * @return User
         */
        public function addAddress(\AppBundle\Entity\Address $address)
        {
            $this->addresses[] = $address;
    
            return $this;
        }
    
        /**
         * Remove address
         *
         * @param \AppBundle\Entity\Address $address
         */
        public function removeAddress(\AppBundle\Entity\Address $address)
        {
            $this->addresses->removeElement($address);
        }
    
        /**
         * Get addresses
         *
         * @return \Doctrine\Common\Collections\Collection
         */
        public function getAddresses()
        {
            return $this->addresses;
        }
    
    
    }
    

    Now when you create a new User you can call the addAddresses method to add a new address.

    Example:

    $user = new User;
    $address = new Address;
    ... // copy of first_name,last_name,company to the address object
    
    $address->setLastName($user->getLastName()); // or whatever field you want
    $user->addAddress($address); 
    
    $em->persist($user);
    $em->flush();
    

    Now you call the $user->getAddresses() method, and get all the addresses.