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;
Related
Symfony 6
No identifier/primary key specified for Entity "App\Entity\ContactVw".
Every Entity must have an identifier/primary key.
I know how to fix that error when using a simple table.
But how can I fix that error when I am using a view. Views don't have primary keys. Where in the class definition do I have to tell doctrine what column to use as primary?
This is my class
<?php
namespace App\Entity;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
/**
* ContactVw
*
* #ORM\Table(name="contact_vw", indexes={#ORM\Index(name="city", columns={"city"}), #ORM\Index(name="customer", columns={"customer"}), #ORM\Index(name="name", columns={"name"}), #ORM\Index(name="country_sold_to", columns={"country_sold_to"})})
* #ORM\Entity
*/
class ContactVw
{
public function __construct(
#[Id, Column]
private string $contactId,
) {
}
/**
* #var string|null
*
* #ORM\Column(name="first", type="string", length=255, nullable=true, options={"default"="NULL"})
*/
private $first = 'NULL';
/**
* #var string|null
*
* #ORM\Column(name="middle", type="string", length=255, nullable=true, options={"default"="NULL"})
*/
private $middle = 'NULL';
/**
* #var string
*
* #ORM\Column(name="last", type="string", length=255, nullable=false)
*/
private $last;
/**
* #var string
*
* #ORM\Column(name="customer", type="decimal", precision=38, scale=0, nullable=false)
*/
private $customer;
/**
* #var string|null
*
* #ORM\Column(name="email", type="string", length=255, nullable=true, options={"default"="NULL"})
*/
private $email = 'NULL';
/**
* #var string|null
*
* #ORM\Column(name="phone", type="string", length=255, nullable=true, options={"default"="NULL"})
*/
private $phone = 'NULL';
/**
* #var string|null
*
* #ORM\Column(name="mobile", type="string", length=255, nullable=true, options={"default"="NULL"})
*/
private $mobile = 'NULL';
/**
* #var bool
*
* #ORM\Column(name="skill_id", type="boolean", nullable=false)
*/
private $skillId;
/**
* #var string
*
* #ORM\Column(name="skill", type="string", length=255, nullable=false)
*/
private $skill;
/**
* #var string
*
* #ORM\Column(name="country", type="string", length=2, nullable=false)
*/
private $country;
/**
* #var string|null
*
* #ORM\Column(name="country_sold_to", type="string", length=41, nullable=true, options={"default"="NULL"})
*/
private $countrySoldTo = 'NULL';
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=35, nullable=false)
*/
private $name;
/**
* #var string|null
*
* #ORM\Column(name="name_2", type="string", length=35, nullable=true, options={"default"="NULL"})
*/
private $name2 = 'NULL';
/**
* #var string|null
*
* #ORM\Column(name="postal_code", type="decimal", precision=38, scale=0, nullable=true, options={"default"="NULL"})
*/
private $postalCode = 'NULL';
/**
* #var string
*
* #ORM\Column(name="city", type="string", length=35, nullable=false)
*/
private $city;
public function setContactId(int $contactId): self
{
$this->contactId = $contactId;
return $this;
}
public function getFirst(): ?string
{
return $this->first;
}
public function setFirst(?string $first): self
{
$this->first = $first;
return $this;
}
public function getMiddle(): ?string
{
return $this->middle;
}
public function setMiddle(?string $middle): self
{
$this->middle = $middle;
return $this;
}
public function getLast(): ?string
{
return $this->last;
}
public function setLast(string $last): self
{
$this->last = $last;
return $this;
}
public function getCustomer(): ?string
{
return $this->customer;
}
public function setCustomer(string $customer): self
{
$this->customer = $customer;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(?string $email): self
{
$this->email = $email;
return $this;
}
public function getPhone(): ?string
{
return $this->phone;
}
public function setPhone(?string $phone): self
{
$this->phone = $phone;
return $this;
}
public function getMobile(): ?string
{
return $this->mobile;
}
public function setMobile(?string $mobile): self
{
$this->mobile = $mobile;
return $this;
}
public function isSkillId(): ?bool
{
return $this->skillId;
}
public function setSkillId(bool $skillId): self
{
$this->skillId = $skillId;
return $this;
}
public function getSkill(): ?string
{
return $this->skill;
}
public function setSkill(string $skill): self
{
$this->skill = $skill;
return $this;
}
public function getCountry(): ?string
{
return $this->country;
}
public function setCountry(string $country): self
{
$this->country = $country;
return $this;
}
public function getCountrySoldTo(): ?string
{
return $this->countrySoldTo;
}
public function setCountrySoldTo(?string $countrySoldTo): self
{
$this->countrySoldTo = $countrySoldTo;
return $this;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getName2(): ?string
{
return $this->name2;
}
public function setName2(?string $name2): self
{
$this->name2 = $name2;
return $this;
}
public function getPostalCode(): ?string
{
return $this->postalCode;
}
public function setPostalCode(?string $postalCode): self
{
$this->postalCode = $postalCode;
return $this;
}
public function getCity(): ?string
{
return $this->city;
}
public function setCity(string $city): self
{
$this->city = $city;
return $this;
}
}
You did not set an identifier on any attribute, which you can do using :
#[ORM\Id] // Php Attribute
/**
* #ORM\Id // Annotation
**/
enter code here
In your code :
#[Id, Column] // seems wrong
You are mixing annotation and Php Attribute to define how your entity work: dont do that.
Personnally, i recommend php attribute over annotation if you can use it.
https://symfony.com/blog/new-in-symfony-5-2-php-8-attributes
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!
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);
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.
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
))