Many-to-many relationship inside a symfony 3 form - many-to-many

I have a problem implementing a symfony 3 form with two objects having a many-to-many relationship.
I have two datatables, "Users" and "Roles". I want to have a form, where I can edit a user and assign a user some roles. In detail I want a form where each Role is a checkbox and I can choose which role a user has.
I know, that I have to implement a new UserType,, but how can I implement the dynamic checkboxes?
This is my User-Class:
<?php
// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* #ORM\Table(name="app_users")
* #ORM\Entity(repositoryClass="AppBundle\Entity\UserRepository")
*/
class User implements UserInterface, \Serializable
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(type="string", length=25, unique=true)
*/
private $username;
/**
* #ORM\Column(type="string", length=64)
*/
private $password;
/**
* #ORM\Column(type="string", length=60, unique=true)
*/
private $email;
/**
* #ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
/**
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
* #ORM\JoinTable(name="user_roles")
*/
private $roles;
public function __construct()
{
$this->isActive = true;
// may not be needed, see section on salt below
// $this->salt = md5(uniqid(null, true));
}
public function getUsername()
{
return $this->username;
}
public function getSalt()
{
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
public function getPassword()
{
return $this->password;
}
public function getRoles()
{
$permissionsArray = array();
foreach ($this->roles as $role)
{
$rolesPermissions = $role->getPermissions();
for($i=0;$i<count($rolesPermissions);$i++)
if(!in_array($rolesPermissions[$i],$permissionsArray))
$permissionsArray[] = $rolesPermissions[$i];
}
return $permissionsArray;
}
public function eraseCredentials()
{
}
/** #see \Serializable::serialize() */
public function serialize()
{
return serialize(array(
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt,
));
}
/** #see \Serializable::unserialize() */
public function unserialize($serialized)
{
list (
$this->id,
$this->username,
$this->password,
// see section on salt below
// $this->salt
) = unserialize($serialized);
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* #param string $username
*
* #return User
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Set password
*
* #param string $password
*
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Set email
*
* #param string $email
*
* #return User
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* #return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set isActive
*
* #param boolean $isActive
*
* #return User
*/
public function setIsActive($isActive)
{
$this->isActive = $isActive;
return $this;
}
/**
* Get isActive
*
* #return boolean
*/
public function getIsActive()
{
return $this->isActive;
}
}
And this is my Role-Class:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Role
*
* #ORM\Table(name="role")
* #ORM\Entity(repositoryClass="AppBundle\Repository\RoleRepository")
*/
class Role
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="bezeichnung", type="string", length=255, unique=true)
*/
private $bezeichnung;
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
/**
* #ORM\ManyToMany(targetEntity="Permission", inversedBy="roles")
* #ORM\JoinTable(name="roles_permissions")
*/
private $permissions;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set bezeichnung
*
* #param string $description
*
* #return Role
*/
public function setBezeichnung($bezeichnung)
{
$this->bezeichnung = $bezeichnung;
return $this;
}
/**
* Get bezeichnung
*
* #return string
*/
public function getBezeichnung()
{
return $this->bezeichnung;
}
/**
* Constructor
*/
public function __construct()
{
$this->users = new \Doctrine\Common\Collections\ArrayCollection();
$this->roles = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add user
*
* #param \AppBundle\Entity\User $user
*
* #return Role
*/
public function addUser(\AppBundle\Entity\User $user)
{
$this->users[] = $user;
return $this;
}
/**
* Remove user
*
* #param \AppBundle\Entity\User $user
*/
public function removeUser(\AppBundle\Entity\User $user)
{
$this->users->removeElement($user);
}
/**
* Get users
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getUsers()
{
return $this->users;
}
/**
* Add permission
*
* #param \AppBundle\Entity\Permission $permission
*
* #return Role
*/
public function addPermission(\AppBundle\Entity\Permission $permission)
{
$this->permissions[] = $permission;
return $this;
}
/**
* Remove permission
*
* #param \AppBundle\Entity\Permission $permission
*/
public function removePermission(\AppBundle\Entity\Permission $permission)
{
$this->permissions->removeElement($permission);
}
/**
* Get permissions
*
* #return Array
*/
public function getPermissions()
{
$permissionsArray = array();
foreach ($this->permissions as $permission)
$permissionsArray[] = "ROLE_".$permission->getTechBezeichnung();
return $permissionsArray;
}
}

a) Give your entities a __toString() method.
b) Make a UserType. You can also Use the CLI command bin/console doctrine:generate:crud and choose at "write actions" [yes].
The script wil generate a controller, a formType and some templates.
c) add this use statement at the top of UserType:
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
d) add this formfield into your UserType:
->add('roles', EntityType::class, array(
'expanded => true,
'multiple' => true
))

Related

form builder, variable as default

I have problems with setting up default variable using form builder and FOS UserBundle in Symfony2.8
/**
* #Route("/add/{id}", name="add")
* #Template("add.html.twig")
*/
public function createFormAction ($id, Request $request)
{
$user = $this->container->get('security.context')->getToken()->getUser();
$username = $user->getUsername();
$userid = $user->getId();
$repo = $this->getDoctrine()->getRepository('AppBundle:Place');
$pl = $repo->find($id);
//var_dump($us);
$form = $this -> createFormBuilder ($pl)
-> add( "id" , "integer" )
-> add( "placeuser", NULL)
-> add( "priceperhour", "hidden", array( "mapped" => false))
-> add( "rentdate" , "date" )
-> add( "rentlength" , "integer" )
->add( 'save', 'submit', array('label' => 'Add'))
-> getForm ();
$form->handleRequest($request);
if ($form->isSubmitted())
{
$pl = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->flush();
return $this->redirectToRoute('reservation');
}
Return $this -> render ( 'add.html.twig' , [ 'form' => $form -> createView ()]);
}
Please take look at -> add( "placeuser", NULL) in result I received drop-down menu with all usernames from table.
I tried to change to -> add( "placeuser", "integer or text", array( "data" => $username, or $userid from security.context)) but I have got error "Unable to transform value for property path "placeuser": Expected a numeric/string." Form is working only when user from drop-down menu is selected.
Entity Place:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Places
*
* #ORM\Entity
* #ORM\Table(name="places")
*/
class Place
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="NONE")
*
*/
private $id;
/**
* #ORM\Column(name="priceperhour", type="decimal", precision=4, scale=2, nullable=true)
*/
private $priceperhour;
/**
* #ORM\Column(name="rentdate", type="date", nullable=true)
*/
private $rentdate;
/**
* #ORM\Column(name="rentlength", type="decimal", nullable=true)
*/
private $rentlength;
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="places")
* #ORM\JoinColumn(name="placeuser", referencedColumnName="id")
*/
private $placeuser;
/**
* Set id
*
* #param integer $id
*
* #return Place
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set priceperhour
*
* #param string $priceperhour
*
* #return Place
*/
public function setPriceperhour($priceperhour)
{
$this->priceperhour = $priceperhour;
return $this;
}
/**
* Get priceperhour
*
* #return string
*/
public function getPriceperhour()
{
return $this->priceperhour;
}
/**
* Set rentdate
*
* #param string $rentdate
*
* #return Place
*/
public function setRentdate($rentdate)
{
$this->rentdate = $rentdate;
return $this;
}
/**
* Get rentdate
*
* #return string
*/
public function getRentdate()
{
return $this->rentdate;
}
/**
* Set rentlength
*
* #param integer $rentlength
*
* #return Place
*/
public function setRentlength($rentlength)
{
$this->rentlength = $rentlength;
return $this;
}
/**
* Get rentlength
*
* #return integer
*/
public function getRentlength()
{
return $this->rentlength;
}
/**
* Set placeuser
*
* #param \AppBundle\Entity\User $placeuser
*
* #return Place
*/
public function setPlaceuser(\AppBundle\Entity\User $placeuser = null)
{
$this->placeuser = $placeuser;
return $this;
}
/**
* Get placeuser
*
* #return \AppBundle\Entity\User
*/
public function getPlaceuser()
{
return $this->placeuser;
}
}
Entity User:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use FOS\UserBundle\Model\User as BaseUser;
/**
* User
*
* #ORM\Entity
* #ORM\Table(name="users")
* #UniqueEntity(fields="email", message="Email already taken")
* #UniqueEntity(fields="username", message="Username already taken")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(name="id", type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #Assert\Length(min=5)
*/
protected $username;
/**
* #Assert\Length(min=5)
* #Assert\Length(max=4096)
*/
protected $password;
/**
* #ORM\Column(name="name", type="string", length=20, nullable=true)
*/
private $name;
/**
* #ORM\Column(name="surname", type="string", length=20, nullable=true)
*/
private $surname;
/**
* #Assert\NotBlank()
*/
protected $email;
/**
* #ORM\Column(name="accountvalue", type="decimal", precision=6, scale=2, nullable=true)
*/
private $accountvalue;
/**
* #ORM\OneToMany (targetEntity="Place", mappedBy="placeuser")
*/
private $places;
public function __construct()
{
parent::__construct();
$this->places = new ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return User
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set surname
*
* #param string $surname
*
* #return User
*/
public function setSurname($surname)
{
$this->surname = $surname;
return $this;
}
/**
* Get surname
*
* #return string
*/
public function getSurname()
{
return $this->surname;
}
/**
* Set accountvalue
*
* #param string $accountvalue
*
* #return User
*/
public function setAccountvalue($accountvalue)
{
$this->accountvalue = $accountvalue;
return $this;
}
/**
* Get accountvalue
*
* #return string
*/
public function getAccountvalue()
{
return $this->accountvalue;
}
/**
* Add place
*
* #param \AppBundle\Entity\Place $place
*
* #return User
*/
public function addPlace(\AppBundle\Entity\Place $place)
{
$this->places[] = $place;
return $this;
}
/**
* Remove place
*
* #param \AppBundle\Entity\Place $place
*/
public function removePlace(\AppBundle\Entity\Place $place)
{
$this->places->removeElement($place);
}
/**
* Get places
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getPlaces()
{
return $this->places;
}
}
My goal is to have field with currently logged user, and add place in this context.
Thanks a million for any help!

Doctrine Make Join

Users Entity :
<?php
namespace App\Entity;
use App\Entity;
use Doctrine\ORM\Mapping;
/**
* #Entity
* #Table(name="users", options={"collate":"utf8_general_ci", "charset":"utf8", "engine":"MyISAM"})
*/
class Users extends Entity {
/**
* #Column(type="string", length=50)
* #var string
*/
protected $email;
/**
* #Column(type="string", length=50)
* #var string
*/
protected $encrypted_password;
/**
* #Column(type="string", length=10)
* #var string
*/
protected $salt;
/**
* #Column(type="smallint", options={"default":"0","comment":"0 : Doctor, 1 : Assistant, 2 : Student"}))
* #var smallint
*/
protected $type;
/**
* #Column(type="string", length=150)
* #var string
*/
protected $sef_link;
/**
* #return string
*/
public function getEmail() {
return $this->email;
}
/**
* #param string $email
*/
public function setEmail($email) {
$this->email = $email;
}
/**
* #return string
*/
public function getEncryptedPassword() {
return $this->encrypted_password;
}
/**
* #param string $encrypted_password
*/
public function setEncryptedPassword($encrypted_password) {
$this->encrypted_password = $encrypted_password;
}
/**
* #return string
*/
public function getSalt() {
return $this->salt;
}
/**
* #param string $salt
*/
public function setSalt($salt) {
$this->salt = $salt;
}
/**
* #return integer
*/
public function getType() {
return $this->type;
}
/**
* #param integer $type
*/
public function setType($type) {
$this->type = $type;
}
/**
* #return string
*/
public function getSefLink() {
return $this->sef_link;
}
/**
* #param string $sef_link
*/
public function setSefLink($sef_link) {
$this->sef_link = $sef_link;
}
}
UserInformation Entity :
<?php
namespace App\Entity;
use App\Entity;
use Doctrine\ORM\Mapping;
/**
* #Entity
* #Table(name="user_information", options={"collate":"utf8_general_ci", "charset":"utf8", "engine":"MyISAM"})
*/
class UserInformation extends Entity {
/**
* #Column(type="integer", unique=true)
* #var integer
*/
protected $uid;
/**
* #Column(type="string", length=50)
* #var string
*/
protected $title;
/**
* #Column(type="string", length=50)
* #var string
*/
protected $name;
/**
* #Column(type="string", length=50)
* #var string
*/
protected $surname;
/**
* #Column(type="date", nullable=true)
* #var date
*/
protected $born;
/**
* #Column(type="text", length=65532)
* #var text
*/
protected $address;
/**
* #Column(type="string", length=100)
* #var string
*/
protected $cv_path;
/**
* #Column(type="string", length=50)
* #var string
*/
protected $facebook_link;
/**
* #Column(type="string", length=50)
* #var string
*/
protected $twitter_link;
/**
* #Column(type="string", length=50)
* #var string
*/
protected $instagram_link;
/**
* #Column(type="string", length=50)
* #var string
*/
protected $linkedin_link;
/**
* #Column(type="string", length=100)
* #var string
*/
protected $img_path;
/**
* #Column(type="date", nullable=true)
* #var date
*/
protected $university_graduated_at;
/**
* #Column(type="date", nullable=true)
* #var date
*/
protected $md_graduated_at;
/**
* #Column(type="date", nullable=true)
* #var date
*/
protected $associate_professor_graduated_at;
/**
* #return int
*/
public function getUid() {
return $this->uid;
}
/**
* #param int $uid
*/
public function setUid($uid) {
$this->uid = $uid;
}
/**
* #return string
*/
public function getTitle() {
return $this->title;
}
/**
* #param string $title
*/
public function setTitle($title) {
$this->title = $title;
}
/**
* #return string
*/
public function getName() {
return $this->name;
}
/**
* #param string $name
*/
public function setName($name) {
$this->name = $name;
}
/**
* #return string
*/
public function getSurname() {
return $this->surname;
}
/**
* #param string $surname
*/
public function setSurname($surname) {
$this->surname = $surname;
}
/**
* #return date
*/
public function getBorn() {
return $this->born;
}
/**
* #param date $born
*/
public function setBorn($born) {
$this->born = $born;
}
/**
* #return text
*/
public function getAddress() {
return $this->address;
}
/**
* #param text $address
*/
public function setAddress($address) {
$this->address = $address;
}
/**
* #return string
*/
public function getCvPath() {
return $this->cv_path;
}
/**
* #param string $cv_path
*/
public function setCvPath($cv_path) {
$this->cv_path = $cv_path;
}
/**
* #return string
*/
public function getFacebookLink() {
return $this->facebook_link;
}
/**
* #param string $facebook_link
*/
public function setFacebookLink($facebook_link) {
$this->facebook_link = $facebook_link;
}
/**
* #return string
*/
public function getTwitterLink() {
return $this->twitter_link;
}
/**
* #param string $twitter_link
*/
public function setTwitterLink($twitter_link) {
$this->twitter_link = $twitter_link;
}
/**
* #return string
*/
public function getInstagramLink() {
return $this->instagram_link;
}
/**
* #param string $instagram_link
*/
public function setInstagramLink($instagram_link) {
$this->instagram_link = $instagram_link;
}
/**
* #return string
*/
public function getLinkedinLink() {
return $this->linkedin_link;
}
/**
* #param string $linkedin_link
*/
public function setLinkedinLink($linkedin_link) {
$this->linkedin_link = $linkedin_link;
}
/**
* #return string
*/
public function getImgPath() {
return $this->img_path;
}
/**
* #param string $img_path
*/
public function setImgPath($img_path) {
$this->img_path = $img_path;
}
/**
* #return date
*/
public function getUniversityGraduatedAt() {
return $this->university_graduated_at;
}
/**
* #param date $university_graduated_at
*/
public function setUniversityGraduatedAt($university_graduated_at) {
$this->university_graduated_at = $university_graduated_at;
}
/**
* #return date
*/
public function getMdGraduatedAt() {
return $this->md_graduated_at;
}
/**
* #param date $md_graduated_at
*/
public function setMdGraduatedAt($md_graduated_at) {
$this->md_graduated_at = $md_graduated_at;
}
/**
* #return date
*/
public function getAssociateProfessorGraduatedAt() {
return $this->associate_professor_graduated_at;
}
/**
* #param date $associate_professor_graduated_at
*/
public function setAssociateProfessorGraduatedAt($associate_professor_graduated_at) {
$this->associate_professor_graduated_at = $associate_professor_graduated_at;
}
}
Users Service :
public function getUserByEmailAndPassword($email, $password, $ip, $user_agent) {
$repository = $this->getEntityManager()->getRepository('App\Entity\Users');
$user = $repository->createQueryBuilder('u')->innerJoin('u.user_information', 'ui')->where('u.email = :email')->setParameter('email', $email);
I want to left join one to one users with user_information.
User Information has uid as a unique_key and refer to users id.
How can i left join and get data from user_information where uid = users id?
You have to create relation between your entities.
If you want a oneToOne relation:
class User
{
/**
* #ORM\Id
*/
protected $id;
/**
* #ORM\OneToOne(targetEntity="UserInformation")
*/
protected $userInformation;
}
class UserInformation
{
/**
* #ORM\Id
*/
protected $id;
/**
* #ORM\OneToOne(targetEntity="User", inversedBy="userInformation")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $uid;
}
Inner join:
$user = $repository
->createQueryBuilder('u')
->addSelect('ui') // to limit queries when doing $user->getUserInformation()
->innerJoin('u.userInformation', 'ui')
->where('u.email = :email')->setParameter('email', $email);

Expected argument of type "biblioBundle\Entity\Profil", "integer" given

PersonneController.php
<?php
namespace biblioBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use biblioBundle\Entity\Personne;
use biblioBundle\Form\PersonneType;
/**
* Personne controller.
*
*/
class PersonneController extends Controller
{
/**
* Lists all Personne entities.
*
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$personnes = $em->getRepository('biblioBundle:Personne')->findAll();
return $this->render('personne/index.html.twig', array(
'personnes' => $personnes,
));
}
/**
* Creates a new Personne entity.
*
*/
public function newAction(Request $request)
{
//$em = $this->getDoctrine()->getManager();
//$prf = $em->getRepository('biblioBundle:Profil')->findAll();
$personne = new Personne();
$form = $this->createForm(PersonneType::class, $personne);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($personne);
$em->flush();
return $this->redirectToRoute('personne_show', array('id' => $personne->getIdpersonne()));
}
return $this->render('personne/new.html.twig', array(
'personne' => $personne,
'form' => $form->createView(),
));
}
PersonneType.php
<?php
namespace biblioBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use biblioBundle\Entity\Profil;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
class PersonneType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('nom')
->add('prenom')
->add('datenaiss', 'date')
->add('adresse')
->add('photo1')
->add('sexe',ChoiceType::class,array(
'choices' => array(
'H' => 'Homme',
'F' => 'Femme')))
->add('idProfil',IntegerType::class);
}
/* public function getName()
{
return 'name';
}*/
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'biblioBundle\Entity\Personne'
));
}
}
Personne.php
<?php
namespace biblioBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Personne
*
* #ORM\Table(name="personne", indexes= {#ORM\Index(name="FK_Appartenir2", columns={"idProfil"})})
* #ORM\Entity
*/
class Personne
{
/**
* #var string
*
* #ORM\Column(name="Nom", type="string", length=20, nullable=false)
*/
private $nom;
/**
* #var string
*
* #ORM\Column(name="Prenom", type="string", length=20, nullable=false)
*/
private $prenom;
/**
* #var \DateTime
*
* #ORM\Column(name="DateNaiss", type="date", nullable=false)
*/
private $datenaiss;
/**
* #var string
*
* #ORM\Column(name="Adresse", type="string", length=100, nullable=true)
*/
private $adresse;
/**
* #var string
*
* #ORM\Column(name="Photo1", type="string", length=255, nullable=true)
*/
private $photo1;
/**
* #var string
*
* #ORM\Column(name="Sexe", type="string", length=1, nullable=false)
*/
private $sexe;
/**
* #var integer
*
* #ORM\Column(name="idPersonne", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idpersonne;
/**
* #var \biblioBundle\Entity\Profil
*
* #ORM\ManyToOne(targetEntity="biblioBundle\Entity\Profil")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="idProfil", referencedColumnName="idProfil")
* })
*/
private $idprofil;
/**
* Set nom
*
* #param string $nom
* #return Personne
*/
public function setNom($nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set prenom
*
* #param string $prenom
* #return Personne
*/
public function setPrenom($prenom)
{
$this->prenom = $prenom;
return $this;
}
/**
* Get prenom
*
* #return string
*/
public function getPrenom()
{
return $this->prenom;
}
/**
* Set datenaiss
*
* #param \DateTime $datenaiss
* #return Personne
*/
public function setDatenaiss($datenaiss)
{
$this->datenaiss = $datenaiss;
return $this;
}
/**
* Get datenaiss
*
* #return \DateTime
*/
public function getDatenaiss()
{
return $this->datenaiss;
}
/**
* Set adresse
*
* #param string $adresse
* #return Personne
*/
public function setAdresse($adresse)
{
$this->adresse = $adresse;
return $this;
}
/**
* Get adresse
*
* #return string
*/
public function getAdresse()
{
return $this->adresse;
}
/**
* Set photo1
*
* #param string $photo1
* #return Personne
*/
public function setPhoto1($photo1)
{
$this->photo1 = $photo1;
return $this;
}
/**
* Get photo1
*
* #return string
*/
public function getPhoto1()
{
return $this->photo1;
}
/**
* Set sexe
*
* #param string $sexe
* #return Personne
*/
public function setSexe($sexe)
{
$this->sexe = $sexe;
return $this;
}
/**
* Get sexe
*
* #return string
*/
public function getSexe()
{
return $this->sexe;
}
/**
* Get idpersonne
*
* #return integer
*/
public function getIdpersonne()
{
return $this->idpersonne;
}
/**
* Set idprofil
*
* #param \biblioBundle\Entity\Profil $idprofil
* #return Personne
*/
public function setIdprofil(\biblioBundle\Entity\Profil $idprofil = null)
{
$this->idprofil = $idprofil;
return $this;
}
/**
* Get idprofil
*
* #return \biblioBundle\Entity\Profil
*/
public function getIdprofil()
{
return $this->idprofil;
}
}
Every time I try to run the code I get:
{Expected argument of type "biblioBundle\Entity\Profil", "integer" given }
Please I need help.
In your PersonneType class you have line:
->add('idProfil',IntegerType::class);
when in Personne class you have:
public function setIdprofil(\biblioBundle\Entity\Profil $idprofil = null)
{
$this->idprofil = $idprofil;
return $this;
}
You need to have Profil instance instead of integer (defined in form). How to solve this?
Replace IntegerType class to EntityType.
Add data transformer to form and transform integer to Profil and vice versa.
Replace argument $idprofil with integer type instead of Profil.

500: Internal Server Error undefined index Symfony3

I'm trying to send from api rest controller (Symfony3) a object collection but get an error. "{"error":{"code":500,"message":"Internal Server Error","exception":[{"message":"Notice: Undefined index: Bar"
/**
*
*
* #Get("/api/bars.{_format}", defaults={"_format"="json"}, options={"expose"=true}, name="api_bars")
* #View()
*/
public function getBarsAction (Request $request)
{
$em = $this->getDoctrine()->getManager();
$session = $this->get('Session');
$repository = $em->getRepository('AppBundle:Bar');
$bars = $repository->findAll();
foreach ($bars as $bar)
{
$id = $bar->getId();
$name = $bar->getName();
$bars[] = array('id'=>$id,'name'=>$name);
}
$view = $this->View($bars,200);
return $this->handleView($view);
}
And the Bar Entity is:
<?php
namespace AppBundle\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* Bar
*
* #ORM\Table(name="Bar")
* #ORM\Entity(repositoryClass="AppBundle\Repository\BarRepository")
*/
class Bar
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=45, nullable=true)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="location", type="string", length=45, nullable=true)
*/
private $location;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=45, nullable=true)
*/
private $description;
/**
* #ORM\OneToMany(targetEntity="Waiter", mappedBy="Bar")
*/
protected $waiters;
/**
* #ORM\OneToMany(targetEntity="Table_", mappedBy="Bar")
*/
protected $tables;
/** #ORM\OneToMany(targetEntity="Stock_food", mappedBy="Bar") */
private $stockfoods;
/** #ORM\OneToMany(targetEntity="Stock_drink", mappedBy="Bar") */
private $stockdrinks;
public function __construct()
{
$this->waiters = new ArrayCollection();
$this->tables = new ArrayCollection();
$this->stockfoods = new ArrayCollection();
$this->stockdrinks = new ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Bar
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set location
*
* #param string $location
*
* #return Bar
*/
public function setLocation($location)
{
$this->location = $location;
return $this;
}
/**
* Get location
*
* #return string
*/
public function getLocation()
{
return $this->location;
}
/**
* Set description
*
* #param string $description
*
* #return Bar
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
public function addWaiter($value){
$this->waiters[] = $value;
}
public function getWaiters(){
return $this->waiters;
}
public function removeWaiters($id)
{
//optionally add a check here to see that $group exists before removing it.
return $this->waiters->removeElement($id);
}
public function addTable($value){
$this->tables[] = $value;
}
public function getTables(){
return $this->tables;
}
public function removeTables($id)
{
//optionally add a check here to see that $group exists before removing it.
return $this->tables->removeElement($id);
}
public function addFood($value){
$this->stockfoods[] = $value;
}
public function getFoods(){
return $this->stockfoods;
}
public function removeFoods($id)
{
//optionally add a check here to see that $group exists before removing it.
return $this->stockfoods->removeElement($id);
}
public function addDrink($value){
$this->stockdrinks[] = $value;
}
public function getDrinks(){
return $this->stockdrinks;
}
public function removeDrinks($id)
{
//optionally add a check here to see that $group exists before removing it.
return $this->stockdrinks->removeElement($id);
}
}
Thanks a lot!!!!
I solved my problem!!! I was related to association mapping. I've changed this:
/**
* #ORM\OneToMany(targetEntity="Waiter", mappedBy="Bar")
*/
protected $waiters;
/**
* #ORM\OneToMany(targetEntity="Table_", mappedBy="Bar")
*/
protected $tables;
/** #ORM\OneToMany(targetEntity="Stock_food", mappedBy="Bar") */
private $stockfoods;
/** #ORM\OneToMany(targetEntity="Stock_drink", mappedBy="Bar") */
private $stockdrinks;
For this:
/**
* #ORM\OneToMany(targetEntity="Waiter", mappedBy="bar")
*/
protected $waiters;
/**
* #ORM\OneToMany(targetEntity="Table_", mappedBy="bar")
*/
protected $tables;
/** #ORM\OneToMany(targetEntity="Stock_food", mappedBy="bar") */
private $stockfoods;
/** #ORM\OneToMany(targetEntity="Stock_drink", mappedBy="bar") */
private $stockdrinks;

Array Collection not saving to database in manytomany relationship

I have a many to many relationship using zend framework 2 and doctrine 2.
The relationship is between categories and products.
My products entity is
<?php
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Zend\ServiceManager\ServiceManager;
use Doctrine\ORM\PersistentCollection;
use Application\Entity\Categories;
/**
* Products
*
* #ORM\Table(name="products", indexes={
* #ORM\Index(name="PRIMARY", columns={"product_id"}),
* #ORM\Index(name="created_by_user_id", columns={"created_by_user_id"}),
* #ORM\Index(name="retail_status_id", columns={"retail_status_id"}),
* })
* #ORM\Entity(repositoryClass="Application\Entity\Repository\ProductsRepository")
* #ORM\HasLifecycleCallbacks
*/
class Products extends AbstractEntity
{
/**
* #var integer
*
* #ORM\Column(name="product_id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $productId;
/**
* #var \Application\Entity\AttributeSets
*
* #ORM\ManyToOne(targetEntity="Application\Entity\AttributeSets", inversedBy="products")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="attribute_set_id", referencedColumnName="attribute_set_id")
* })
*/
private $attributeSet;
/**
* #var \Application\Entity\RetailStatus
*
* #ORM\ManyToOne(targetEntity="Application\Entity\RetailStatus", inversedBy="products")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="retail_status_id", referencedColumnName="retail_status_id")
* })
*/
private $retailStatus;
/**
* #var string
*
* #ORM\Column(name="price", type="decimal", precision=9, scale=2, nullable=false)
*/
private $price;
/**
* #var integer
*
* #ORM\Column(name="active", type="integer", nullable=false)
*/
private $active;
/**
* #var \DateTime
*
* #ORM\Column(name="date_created", type="datetime")
*/
private $dateCreated;
/**
* #var \DateTime
*
* #ORM\Column(name="date_modified", type="datetime")
*/
private $dateModified;
/**
* #var \Application\Entity\Users
*
* #ORM\ManyToOne(targetEntity="Application\Entity\Users")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="created_by_user_id", referencedColumnName="user_id")
* })
*/
private $authUser;
/**
* #var \Application\Entity\ProductTitles
*
* #ORM\OneToOne(targetEntity="Application\Entity\ProductTitles", cascade={"persist", "persist"}, mappedBy="product")
*/
private $title;
/**
* #var \Application\Entity\ProductDescriptions
*
* #ORM\OneToOne(targetEntity="Application\Entity\ProductDescriptions", cascade={"persist", "persist"}, mappedBy="product")
*/
private $description;
/**
* #var \Application\Entity\ProductDimentions
*
* #ORM\OneToOne(targetEntity="Application\Entity\ProductDimentions", cascade={"persist", "persist"}, mappedBy="product")
*/
private $productDimentions;
/**
* #var \Doctrine\ORM\PersistentCollection
*
* #ORM\ManyToMany(targetEntity="Application\Entity\Categories", cascade={"persist"}, inversedBy="products")
* #ORM\JoinTable(name="product_to_catagory",
* joinColumns={#ORM\joinColumn(name="product_id", referencedColumnName="product_id")},
* inverseJoinColumns={#ORM\joinColumn(name="catagory_id", referencedColumnName="catagory_id")}
* )
*/
private $categories;
/**
* #var \Doctrine\ORM\PersistentCollection
*
* #ORM\OneToMany(targetEntity="Application\Entity\ProductAttributeValues", cascade={"persist", "persist"}, mappedBy="product")
*/
private $values;
public function __construct(ServiceManager $serviceManager = NULL)
{
parent::__construct($serviceManager);
$this->categories = new ArrayCollection();
}
/**
*
* #return integer
*/
public function getProductId()
{
return $this->productId;
}
/**
*
* #return \Application\Entity\AttributeSets
*/
public function getAttributeSet()
{
return $this->attributeSet;
}
/**
*
* #return \Application\Entity\RetailStatus
*/
public function getRetailStatus()
{
return $this->retailStatus;
}
/**
*
* #return string
*/
public function getPrice()
{
return $this->price;
}
/**
*
* #return boolean
*/
public function isActive()
{
return (bool) $this->active;
}
/**
*
* #return \DateTime
*/
public function getDateCreated()
{
return $this->dateCreated;
}
/**
*
* #return \DateTime
*/
public function getDateModified()
{
return $this->dateModified;
}
/**
*
* #return \Application\Entity\Users
*/
public function getAuthUser()
{
return $this->authUser;
}
/**
*
* #return \Application\Entity\ProductTitles
*/
public function getTitle()
{
return $this->title;
}
/**
*
* #return \Application\Entity\ProductDescriptions
*/
public function getDescription()
{
return $this->description;
}
/**
*
* #return \Application\Entity\ProductDimentions
*/
public function getProductDimentions()
{
return $this->productDimentions;
}
/**
*
* #return \Doctrine\ORM\PersistentCollection
*/
public function getCategories()
{
return $this->categories;
}
/**
*
* #return \Doctrine\ORM\PersistentCollection
*/
public function getValues()
{
return $this->values;
}
/**
*
* #param \Application\Entity\AttributeSets $attributeSet
* #return \Application\Entity\Products
*/
public function setAttributeSet(\Application\Entity\AttributeSets $attributeSet)
{
$this->attributeSet = $attributeSet;
return $this;
}
/**
*
* #param \Application\Entity\RetailStatus $retailStatus
* #return \Application\Entity\Products
*/
public function setRetailStatus(\Application\Entity\RetailStatus $retailStatus)
{
$this->retailStatus = $retailStatus;
return $this;
}
/**
*
* #param string $price
* #return \Application\Entity\Products
*/
public function setPrice($price)
{
$this->price = $price;
return $this;
}
/**
*
* #param integer $active
* #return \Application\Entity\Products
*/
public function setActive($active)
{
$this->active = $active;
return $this;
}
/**
*
* #param \DateTime $dateCreated
* #return \Application\Entity\Products
*/
public function setDateCreated(\DateTime $dateCreated)
{
$this->dateCreated = $dateCreated;
return $this;
}
/**
*
* #param \DateTime $dateModified
* #return \Application\Entity\Products
*/
public function setDateModified(\DateTime $dateModified)
{
$this->dateModified = $dateModified;
return $this;
}
/**
*
* #param \Application\Entity\Users $authUser
* #return \Application\Entity\Products
*/
public function setAuthUser(\Application\Entity\Users $authUser)
{
$this->authUser = $authUser;
return $this;
}
/**
*
* #param \Application\Entity\ProductTitles $title
* #return \Application\Entity\Products
*/
public function setTitle(\Application\Entity\ProductTitles $title)
{
$this->title = $title;
return $this;
}
/**
*
* #param \Application\Entity\ProductDescriptions $description
* #return \Application\Entity\Products
*/
public function setDescription(\Application\Entity\ProductDescriptions $description)
{
$this->description = $description;
return $this;
}
/**
*
* #param \Application\Entity\ProductDimentions $productDimentions
* #return \Application\Entity\Products
*/
public function setProductDimentions(\Application\Entity\ProductDimentions $productDimentions)
{
$this->productDimentions = $productDimentions;
return $this;
}
public function addCategory(Categories $category)
{
$this->categories->add($category);
}
/**
*
* #param \Doctrine\Common\Collections\ArrayCollection $categories
* #return \Application\Entity\Products
*/
public function addCategories(\Doctrine\Common\Collections\ArrayCollection $categories)
{
foreach ($categories as $category) {
$this->addCategory($category);
}
// \Freedom\Logger\InfoLogger::vardump($this->categories);
return $this;
}
public function removeCategories(\Doctrine\Common\Collections\ArrayCollection $categories)
{
foreach ($categories as $category) {
$this->categories->removeElement($category);
}
return $this;
}
/**
* #ORM\PrePersist
* #return \Application\Entity\Users
*/
public function prePersist()
{
$this->dateCreated = $this->getCurrentDateTime();
$this->dateModified = $this->getCurrentDateTime();
$this->authUser = $this->getAutherizedUser();
// $this->categories = new PersistentCollection($this->getEntityManager(), NULL, $this->categories);
// \Freedom\Logger\InfoLogger::vardump($this->categories->count());
// \Freedom\Logger\InfoLogger::vardump($this->categories);
return $this;
}
/**
* #ORM\PreUpdate
* #return \Application\Entity\Users
*/
public function preUpdate()
{
// $this->dateModified = $this->getCurrentDateTime();
return $this;
}
public function toArray()
{
$array = array();
foreach (get_object_vars($this) as $var => $value) {
switch ($var) {
case 'authUser':
if (!is_null($value)) {
$array[$var] = $value->toArray();
}
break;
default:
$array[$var] = $value;
}
}
return $array;
}
}
and my category entity
<?php
namespace Application\Entity;
use Doctrine\ORM\Mapping as ORM;
use Zend\ServiceManager\ServiceManager;
use Application\Entity\StaticPages;
/**
* Categories
*
* #ORM\Table(name="catagories", indexes={
* #ORM\Index(name="PRIMARY", columns={"catagory_id"}),
* #ORM\Index(name="created_by_user_id", columns={"created_by_user_id"}),
* })
* #ORM\Entity(repositoryClass="Application\Entity\Repository\CategoriesRepository")
* #ORM\HasLifecycleCallbacks
*/
class Categories extends AbstractEntity
{
/**
* #var integer
*
* #ORM\Column(name="catagory_id", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $catagoryId;
/**
* #var string
*
* #ORM\Column(name="category", type="string", length=30, nullable=false)
*/
private $category;
/**
* #var \DateTime
*
* #ORM\Column(name="date_created", type="datetime")
*/
private $dateCreated;
/**
* #var \DateTime
*
* #ORM\Column(name="date_modified", type="datetime")
*/
private $dateModified;
/**
* #var \Application\Entity\Users
*
* #ORM\ManyToOne(targetEntity="Application\Entity\Users")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="created_by_user_id", referencedColumnName="user_id")
* })
*/
private $authUser;
/**
* #var \Application\Entity\Categories
*
* #ORM\ManyToOne(targetEntity="Application\Entity\Categories", inversedBy="childCategories")
* #ORM\JoinColumn(name="parent_catagory_id", referencedColumnName="catagory_id")
*/
protected $parentCategory;
/**
* #var \Doctrine\ORM\PersistentCollection
*
* #ORM\OneToMany(targetEntity="Application\Entity\Categories", mappedBy="parentCategory")
*/
protected $childCategories;
/**
* #var Doctrine\ORM\PersistentCollection
*
* #ORM\ManyToMany(targetEntity="Application\Entity\Products", cascade={"persist"}, orphanRemoval=true, mappedBy="categories")
*/
private $products;
/**
* #var \Application\Entity\Sites
*
* #ORM\ManyToOne(targetEntity="Application\Entity\Sites", inversedBy="categories")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="site_id", referencedColumnName="site_id")
* })
*/
private $site;
/**
* #var \Application\Entity\StaticPages
*
* #ORM\OneToOne(targetEntity="Application\Entity\StaticPages", mappedBy="category", cascade="persist")
*/
private $staticPage;
/**
* #var integer
*
* #ORM\Column(name="active", type="integer", nullable=false)
*/
private $active;
/**
* #var string
*
* #ORM\Column(name="url_key", type="string", length=30, nullable=false)
*/
private $urlKey;
/**
* #var string
*
* #ORM\Column(name="description", type="text", length=200, nullable=false)
*/
private $description;
/**
* #var integer
*
* #ORM\Column(name="sort_order", type="integer", nullable=false)
*/
private $sortOrder;
public function __construct(ServiceManager $serviceManager = NULL)
{
parent::__construct($serviceManager);
$this->parentCategory = NULL;
$this->urlKey = NULL;
}
/**
*
* #return integer
*/
public function getCatagoryId()
{
return $this->catagoryId;
}
/**
*
* #return string
*/
public function getCategory()
{
return $this->category;
}
/**
*
* #return \DateTime
*/
public function getDateCreated()
{
return $this->dateCreated;
}
/**
*
* #return \DateTime
*/
public function getDateModified()
{
return $this->dateModified;
}
/**
*
* #return \Application\Entity\Users
*/
public function getAuthUser()
{
return $this->authUser;
}
/**
*
* #return boolean
*/
public function hasChildCategories()
{
return (bool) $this->getChildCategories()->count();
}
/**
*
* #return \Doctrine\ORM\PersistentCollection
*/
public function getChildCategories()
{
return $this->childCategories;
}
/**
*
* #return boolean
*/
public function hasParentCategory()
{
return (bool) $this->getParentCategory();
}
/**
*
* #return \Application\Entity\Categories
*/
public function getParentCategory()
{
return $this->parentCategory;
}
public function hasProducts()
{
return (bool) $this->getProducts()->count();
}
/**
*
* #return \Doctrine\ORM\PersistentCollection
*/
public function getProducts()
{
return $this->products;
}
/**
*
* #return \Application\Entity\Sites
*/
public function getSite()
{
return $this->site;
}
/**
*
* #return \Application\Entity\StaticPages
*/
public function getStaticPage()
{
return $this->staticPage;
}
/**
*
* #return boolean
*/
public function isActive()
{
return (bool) $this->active;
}
/**
*
* #return strng
*/
public function getUrlKey()
{
return $this->urlKey;
}
/**
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
/**
*
* #return integer
*/
public function getSortOrder()
{
return $this->sortOrder;
}
/**
*
* #param string $category
* #return \Application\Entity\Categories
*/
public function setCategory($category)
{
$this->category = $category;
return $this;
}
/**
*
* #param \DateTime $dateCreated
* #return \Application\Entity\Categories
*/
public function setDateCreated(\DateTime $dateCreated)
{
$this->dateCreated = $dateCreated;
return $this;
}
/**
*
* #param \DateTime $dateModified
* #return \Application\Entity\Categories
*/
public function setDateModified(\DateTime $dateModified)
{
$this->dateModified = $dateModified;
return $this;
}
/**
*
* #param \Application\Entity\Sites $site
* #return \Application\Entity\Categories
*/
public function setSite(\Application\Entity\Sites $site)
{
$this->site = $site;
return $this;
}
public function hasStaticPage()
{
return (bool) $this->getStaticPage();
}
/**
*
* #param \Application\Entity\StaticPages $staticPage
* #return \Application\Entity\Categories
*/
public function setStaticPage(\Application\Entity\StaticPages $staticPage)
{
$this->staticPage = $staticPage;
return $this;
}
public function removeStaticPage()
{
if ($this->getStaticPage() instanceof StaticPages) {
$entityManager = $this->getEntityManager();
$entityManager->remove($this->staticPage);
$entityManager->flush();
}
$this->staticPage = NULL;
}
/**
*
* #param \Application\Entity\Users $authUser
* #return \Application\Entity\Categories
*/
public function setAuthUser(\Application\Entity\Users $authUser)
{
$this->authUser = $authUser;
return $this;
}
/**
*
* #param \Application\Entity\Categories $parentCategory
* #return \Application\Entity\Categories
*/
public function setParentCategory(\Application\Entity\Categories $parentCategory)
{
$this->parentCategory = $parentCategory;
return $this;
}
/**
*
* #param integer $active
* #return \Application\Entity\Categories
*/
public function setActive($active)
{
$this->active = $active;
return $this;
}
/**
*
* #param string $urlKey
* #return \Application\Entity\Categories
*/
public function setUrlKey($urlKey)
{
$escapeUri = $this->getServiceManager()->get('ViewHelperManager')->get('escapeUrl');
$this->urlKey = $escapeUri($urlKey);
return $this;
}
/**
*
* #param string $description
* #return \Application\Entity\Categories
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
*
* #param integer $sortOrder
* #return \Application\Entity\Categories
*/
public function setSortOrder($sortOrder)
{
$this->sortOrder = $sortOrder;
return $this;
}
/**
* #ORM\PrePersist
* #return \Application\Entity\Users
*/
public function prePersist()
{
$this->dateCreated = $this->getCurrentDateTime();
$this->dateModified = $this->getCurrentDateTime();
$this->authUser = $this->getAutherizedUser();
return $this;
}
/**
* #ORM\PreUpdate
* #return \Application\Entity\Users
*/
public function preUpdate()
{
$this->dateModified = $this->getCurrentDateTime();
return $this;
}
public function toArray()
{
$array = array();
foreach (get_object_vars($this) as $var => $value) {
switch ($var) {
case 'products':
foreach ($value as $product) {
$array[$var][] = $product->toArray();
}
break;
case 'authUser':
if (!is_null($value)) {
$array[$var] = $value->toArray();
}
break;
default:
$array[$var] = $value;
}
}
return $array;
}
}
As can be seen the products and categories are linked through the table product_to_catagory.
I am using doctrines object multi checkbox to get the categories for the product using
$this->add(array(
'name' => 'categories',
'type' => 'Admin\DoctrineModule\Form\Element\ObjectMultiCheckbox',
'options' => array(
'label' => _('Categories:'),
'label_attributes' => array('class' => 'required'),
'object_manager' => $this->getEntityManager(),
'target_class' => 'Application\Entity\Categories',
'property' => 'category',
'is_method' => true,
'find_method' => array(
'name' => 'FindAll',
),
'disable_inarray_validator' => true,
),
));
The form is bound to the products entity
After the form is submitted the categories in the product entity returns Doctrine\Common\Collections\ArrayCollection
The problem I am having is that the categories are not being saved on the database in the product_to_catagory table when I flush the products entity.
Does anyone know what I am doing wrong?
Many thanks in advance.
EDIT
Changed owning side to products, code above updated.