So i want to display all the courses within my database in a drop down form. a user who is logged in then select one of the drop downs and it would store the users ID and the course ID into the database. How would i go about doing this?
Here's my course entity course.php
<?php
// src/Simple/SimpleBundle/Entity/Course.php
namespace Simple\ProfileBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="course")
*/
class Course
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(name="course", type="string", length=255)
*/
protected $course;
public function __construct()
{
$this->users = new ArrayCollection();
}
public function setCourse($course)
{
$this->course = $course;
}
public function getCourse()
{
return $this->course;
}
public function setId($id)
{
$this->id = $id;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
}
ChooseCourseType.php my form
<?php
// src/Simple/ProfileBundle/Controller/ChooseCourseType.php
namespace Simple\ProfileBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ChooseCourseType extends AbstractType
{
private $course;
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder->add('course', 'choice', array(
'choices' => $this->course,
));
$builder->add('Choose Course', 'submit');
}
public function getName()
{
return 'name';
}
public function getCourse()
{
return 'course';
}
}
Coursecontroller.php
function chooseAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$form = $this->createForm(new ChooseCourseType(), $CourseType);
$form->handleRequest($request);
if ($form->isValid()) {
$course = $form->getData();
$em->persist($course->getCourse());
$em->flush();
}
return $this->render(
'SimpleProfileBundle:Course:choosecourse.html.twig',
array('form' => $form->createView())
);
}
}
User.php
namespace Simple\ProfileBundle\Entity;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="users")
*/
class User implements UserInterface
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(name="user", type="string", length=255)
*/
protected $username;
/**
* #ORM\Column(name="password", type="string", length=255)
*/
protected $password;
/**
* #ORM\Column(name="salt", type="string", length=255)
*/
protected $salt;
/**
* #ORM\ManyToMany(targetEntity="Role")
* #ORM\JoinTable(name="user_role",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="role_id", referencedColumnName="id")}
* )
*/
protected $roles;
/**
* #ORM\ManyToMany(targetEntity="Course")
* #ORM\JoinTable(name="user_course",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="course_id",
referencedColumnName="id")}
* )
*/
protected $courses;
/**
* #inheritDoc
*/
public function getUsername()
{
return $this->username;
}
/**
* #inheritDoc
*/
public function getSalt()
{
return '';
}
/**
* #inheritDoc
*/
public function getPassword()
{
return $this->password;
}
/**
* #inheritDoc
*/
public function getRoles()
{
return $this->roles->toArray();
}
/**
* #inheritDoc
*/
public function eraseCredentials()
{
}
/**
* Constructor
*/
public function __construct()
{
$this->roles = new \Doctrine\Common\Collections\ArrayCollection();
$this->salt = sha1(uniqid(null, true));
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set user
*
* #param string $user
* #return User
*/
public function setUser($user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* #return string
*/
public function getUser()
{
return $this->user;
}
/**
* Set password
*
* #param string $password
* #return User
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Set salt
*
* #param string $salt
* #return User
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Add roles
*
* #param \Simple\ProfileBundle\Entity\Role $roles
* #return User
*/
public function addRole(\Simple\ProfileBundle\Entity\Role $roles)
{
$this->roles[] = $roles;
return $this;
}
/**
* Remove roles
*
* #param \Simple\ProfileBundle\Entity\Role $roles
*/
public function removeRole(\Simple\ProfileBundle\Entity\Role $roles)
{
$this->roles->removeElement($roles);
}
/**
* Add roles
*
* #param \Simple\ProfileBundle\Entity\Course $courses
* #return User
*/
public function addCourse(\Simple\ProfileBundle\Entity\Course $courses)
{
$this->course[] = $courses;
return $this;
}
}
What else am i missing i am new to symfony2 and just need some direction.
Cheers
You need to use the entity form type.
Form type
<?php
// src/Simple/ProfileBundle/Controller/ChooseCourseType.php
namespace Simple\ProfileBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ChooseCourseType extends AbstractType {
$builder->add('courses', 'entity', array(
'label' => 'Courses',
'class' => 'SimpleSimpleBundle:Course',
'expanded' => false,
'multiple' => false
))
// ...
Controller
function chooseAction(Request $request) {
$em = $this->getDoctrine()->getManager();
// Replace this with whatever logic you use to find the user
$user = $em->getRepository('SimpleSimpleBundle:User')->findOneBy(
array('id' => 1)
);
$form = $this->createForm(new ChooseCourseType(), $user);
$form->handleRequest($request);
if ($form->isValid()) {
$user = $form->getData();
// Since you've bound this user object to the form and properly
// created a relationship between the course and user entities
// the relationship between course and user will persist here
$em->persist($user);
$em->flush();
}
Related
So here is my concern. I have a "Child" entity that contains $services and $users linked in ManyToMany.
The goal in my application is to be able to assign a child to a user of my service.
So, depending on the service I'm in, I won't have the same choice of users to assign.
In my ChildType, in my "users" field, I added a key ''query_builder'' that will retrieve only the users concerned.
My ChildType.php
<?php
namespace App\Form;
use App\Entity\Child;
use App\Entity\Service;
use App\Entity\Sexe;
use App\Entity\User;
use App\Repository\ServiceRepository;
use App\Repository\UserRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Security;
class ChildType extends AbstractType
{
/** #var User $user */
private $user;
private $serviceRepository;
private $authorization;
public function __construct(Security $security, AuthorizationCheckerInterface $authorization, ServiceRepository $serviceRepository)
{
$this->user = $security->getUser();
$this->authorization = $authorization;
$this->serviceRepository = $serviceRepository;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
/** #var Service $service */
$service = $this->user->getService();
$builder
->add('nom', TextType::class)
->add('prenom', TextType::class)
->add('sexe', EntityType::class, [
'class' => Sexe::class,
])
->add('dateDeNaissance', DateType::class, [
'widget' => 'single_text'
])
->add('lieuDeNaissance', TextType::class)
->add('nationalite', TextType::class)
->add('dateElaborationPpe', DateType::class, [
'widget' => 'single_text'
]);
if ($this->authorization->isGranted('ROLE_ADMIN')) {
$builder->add('users', EntityType::class, [
'class' => User::class,
'label' => 'Affecter à un utilisateur',
'query_builder' => function (UserRepository $userRepository) use ($service) {
return $userRepository->findByCurrentService($service);
},
'multiple' => true,
'expanded' => true,
]);
$builder->add('services', EntityType::class, [
'class' => Service::class,
'label' => 'Affecter à un service',
'choices' => $this->serviceRepository->findByDepartement($service->getDepartement()),
'choice_attr' => function($key, $val, $index) use ($service) {
return([]);
return $key->getCategorie()->getId() === $service->getCategorie()->getId() ?
['disabled' => 'disabled'] :
[];
},
'multiple' => true,
'expanded' => true,
]);
}
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Child::class,
]);
}
}
The problem:
Let's assume that my Service #1 has several users from Service #1 to my child. When I assign in my Service #2 users from Service #2 to the child, I have my 2 new users from Service #2 in the database, but on the other hand, those from Service #1 have been deleted, which is not the desired behavior.
I've been looking for a topic for almost 2 hours, and I can't find an answer, so if it's a duplicate, really sorry.
edit method in my controller:
/**
* #Route("/{id}/edit", name="child_edit", methods={"GET","POST"})
*/
public function edit(Request $request, Child $child): Response
{
$this->denyAccessUnlessGranted("edit", $child);
$form = $this->createForm(ChildType::class, $child);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('child_show', ['id' => $child->getId()]);
}
return $this->render('child/edit.html.twig', [
'child' => $child,
'form' => $form->createView(),
]);
}
User.php:
<?php
namespace App\Entity;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Validator\Constraints as Assert;
use App\Entity\Service;
use App\Traits\BlameableEntity;
use App\Traits\TimestampableEntity;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity(repositoryClass="App\Repository\UserRepository")
*
*/
class User implements UserInterface, \Serializable
{
use BlameableEntity;
use TimestampableEntity;
/**
* #var int
*
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #var string
*
* #ORM\Column(type="string")
* #Assert\NotBlank()
*/
private $fullName;
/**
* #var string
*
* #ORM\Column(type="string", unique=true)
* #Assert\NotBlank()
* #Assert\Length(min=2, max=50)
*/
private $username;
/**
* #var string
*
* #ORM\Column(type="string", unique=true)
* #Assert\Email()
*/
private $email;
/**
* #var string
*
* #ORM\Column(type="string")
*/
private $password;
/**
* #var array
*
* #ORM\Column(type="json")
*/
private $roles = [];
/**
* #var \DateTime
*
* #ORM\Column(type="datetime", nullable=true)
*/
private $lastLogin;
/**
* #var \DateTime
*
* #ORM\Column(type="datetime", nullable=true)
*/
private $secondToLastLogin;
/**
* #ORM\ManyToOne(targetEntity="Service", inversedBy="users")
*/
private $service;
/**
* #ORM\ManyToMany(targetEntity="Child", mappedBy="users")
*/
private $children;
public function __construct()
{
$this->children = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getFullName(): ?string
{
return $this->fullName;
}
public function setFullName(string $fullName): self
{
$this->fullName = $fullName;
return $this;
}
public function getUsername(): ?string
{
return $this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getPassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* Returns the roles or permissions granted to the user for security.
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantees that a user always has at least one role for security
if (empty($roles)) {
$roles[] = 'ROLE_USER';
}
return array_unique($roles);
}
public function setRoles(array $roles): void
{
$this->roles = $roles;
}
/**
* Get the value of lastLogin
*
* #return \DateTime
*/
public function getLastLogin()
{
return $this->lastLogin;
}
/**
* Set the value of lastLogin
*
* #param \DateTime $lastLogin
*
* #return self
*/
public function setLastLogin(\DateTime $lastLogin)
{
$this->lastLogin = $lastLogin;
return $this;
}
/**
* Get the value of secondToLastLogin
*
* #return \DateTime
*/
public function getSecondToLastLogin()
{
return $this->secondToLastLogin;
}
/**
* Set the value of secondToLastLogin
*
* #param \DateTime $secondToLastLogin
*
* #return self
*/
public function setSecondToLastLogin(\DateTime $secondToLastLogin)
{
$this->secondToLastLogin = $secondToLastLogin;
return $this;
}
/**
*
* {#inheritdoc}
*/
public function getSalt(): ?string
{
return null;
}
/**
* Removes sensitive data from the user.
*
* {#inheritdoc}
*/
public function eraseCredentials(): void
{
// if you had a plainPassword property, you'd nullify it here
// $this->plainPassword = null;
}
/**
* {#inheritdoc}
*/
public function serialize(): string
{
// add $this->salt too if you don't use Bcrypt or Argon2i
return serialize([$this->id, $this->username, $this->password]);
}
/**
* {#inheritdoc}
*/
public function unserialize($serialized): void
{
// add $this->salt too if you don't use Bcrypt or Argon2i
[$this->id, $this->username, $this->password] = unserialize($serialized, ['allowed_classes' => false]);
}
/**
* Get the value of service
*/
public function getService()
{
return $this->service;
}
/**
* Set the value of service
*
* #return self
*/
public function setService($service)
{
$this->service = $service;
return $this;
}
public function hasService(): bool
{
return !empty($this->getService());
}
/**
* #return Collection|Child[]
*/
public function getChildren(): Collection
{
return $this->children;
}
public function addChild(Child $child): self
{
if (!$this->children->contains($child)) {
$this->children[] = $child;
$child->addUser($this);
}
return $this;
}
public function removeChild(Child $child): self
{
if ($this->children->removeElement($child)) {
$child->removeUser($this);
}
return $this;
}
public function __toString()
{
return $this->getFullName();
}
}
Service.php :
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use App\Repository\ServiceRepository;
use App\Entity\Categorie;
use App\Entity\Departement;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
/**
* #ORM\Entity(repositoryClass=ServiceRepository::class)
*/
class Service
{
public const ASE = 'ASE';
public const MDPH = 'MDPH';
public const E_N = 'Éducation Nationale';
/**
* #var int
*
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #var string
*
* #ORM\Column(type="string")
*/
private $nom;
/**
* #var Departement
*
* #ORM\ManyToOne(targetEntity="Departement")
* #ORM\JoinColumn(nullable=false)
*/
private $departement;
/**
* #var Categorie
*
* #ORM\ManyToOne(targetEntity="Categorie")
* #ORM\JoinColumn(nullable=false)
*/
private $categorie;
/**
* #ORM\OneToMany(targetEntity="User", mappedBy="service")
*/
private $users;
/**
* #ORM\ManyToMany(targetEntity="Child", mappedBy="services")
*/
private $children;
/**
* #ORM\ManyToMany(targetEntity="Element", mappedBy="services")
*/
private $elements;
public function __construct()
{
$this->users = new ArrayCollection();
$this->children = new ArrayCollection();
$this->elements = new ArrayCollection();
}
/**
* Get the value of id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set the value of id
*
* #param int $id
*
* #return self
*/
public function setId(int $id)
{
$this->id = $id;
return $this;
}
/**
* Get the value of nom
*
* #return string
*/
public function getNom()
{
return $this->nom;
}
/**
* Set the value of nom
*
* #param string $nom
*
* #return self
*/
public function setNom(string $nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get the value of departement
*
* #return Departement
*/
public function getDepartement()
{
return $this->departement;
}
/**
* Set the value of departement
*
* #param Departement $departement
*
* #return self
*/
public function setDepartement(Departement $departement)
{
$this->departement = $departement;
return $this;
}
/**
* Get the value of categorie
*
* #return Categorie
*/
public function getCategorie()
{
return $this->categorie;
}
/**
* Set the value of categorie
*
* #param Categorie $categorie
*
* #return self
*/
public function setCategorie(Categorie $categorie)
{
$this->categorie = $categorie;
return $this;
}
/**
* #return Collection|Users[]
*/
public function getUsers(): Collection
{
return $this->users;
}
public function addUser(User $user): self
{
if (!$this->users->contains($user)) {
$this->users[] = $user;
$user->setService($this);
}
return $this;
}
public function removeUser(User $user): self
{
if ($this->users->removeElement($user)) {
// set the owning side to null (unless already changed)
if ($user->getService() === $this) {
$user->setService(null);
}
}
return $this;
}
/**
* #return Collection|Children[]
*/
public function getChildren(): Collection
{
return $this->children;
}
public function addChild(Child $child): self
{
if (!$this->children->contains($child)) {
$this->children[] = $child;
$child->addService($this);
}
return $this;
}
public function removeChild(Child $child): self
{
if ($this->children->removeElement($child)) {
$child->removeService($this);
}
return $this;
}
/**
* #return Collection|Elements[]
*/
public function getElements(): Collection
{
return $this->elements;
}
public function addElements(Element $element): self
{
if (!$this->children->contains($element)) {
$this->elements[] = $element;
$element->addService($this);
}
return $this;
}
public function removeElement(Element $element): self
{
if ($this->elements->removeElement($element)) {
$element->removeService($this);
}
return $this;
}
public function __toString()
{
return $this->getNom();
}
}
Child.php :
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
use App\Entity\Service;
use App\Entity\Sexe;
use App\Entity\User;
use DateTime;
use App\Repository\ChildRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use App\Traits\TimestampableEntity;
use App\Traits\BlameableEntity;
/**
* #ORM\Entity(repositoryClass=ChildRepository::class)
*/
class Child
{
use BlameableEntity;
use TimestampableEntity;
/**
* #var int
*
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
*/
private $id;
/**
* #var string
*
* #ORM\Column(type="string")
*/
private $nom;
/**
* #var string
*
* #ORM\Column(type="string")
*/
private $prenom;
/**
* #var Sexe
*
* #ORM\ManyToOne(targetEntity="Sexe")
*/
private $sexe;
/**
* #var date
*
* #ORM\Column(type="date")
*/
private $dateDeNaissance;
/**
* #var string
*
* #ORM\Column(type="string")
*/
private $lieuDeNaissance;
/**
* #var string
*
* #ORM\Column(type="string")
*/
private $nationalite;
/**
* #var date
*
* #ORM\Column(type="datetime", nullable=true)
*/
private $dateElaborationPpe;
/**
* #var Service[]|Collection
*
* #ORM\ManyToMany(targetEntity="Service", inversedBy="children")
*/
private $services;
/**
* #var User[]|Collection
*
* #ORM\ManyToMany(targetEntity="User", inversedBy="children")
*/
private $users;
/**
* #var Element[]|Collection
*
* #ORM\OneToMany(targetEntity="Element", mappedBy="child")
*/
private $elements;
public function __construct()
{
$this->services = new ArrayCollection();
$this->users = new ArrayCollection();
$this->elements = new ArrayCollection();
}
/**
* Get the value of id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set the value of id
*
* #param int $id
*
* #return self
*/
public function setId(int $id)
{
$this->id = $id;
return $this;
}
/**
* Get id
*
* #return string
*/
public function getNumDossier()
{
return str_pad($this->id, 6, "0", STR_PAD_LEFT);
}
/**
* Get the value of nom
*/
public function getNom()
{
return $this->nom;
}
/**
* Set the value of nom
*
* #return self
*/
public function setNom(string $nom)
{
$this->nom = $nom;
return $this;
}
/**
* Get the value of prenom
*/
public function getPrenom()
{
return $this->prenom;
}
/**
* Set the value of prenom
*
* #return self
*/
public function setPrenom(string $prenom)
{
$this->prenom = $prenom;
return $this;
}
/**
* Get the value of sexe
*
* #return Sexe
*/
public function getSexe()
{
return $this->sexe;
}
/**
* Set the value of sexe
*
* #param Sexe $sexe
*
* #return self
*/
public function setSexe(Sexe $sexe)
{
$this->sexe = $sexe;
return $this;
}
/**
* Get the value of dateDeNaissance
*/
public function getDateDeNaissance()
{
return $this->dateDeNaissance;
}
/**
* Set the value of dateDeNaissance
*
* #return self
*/
public function setDateDeNaissance(datetime $dateDeNaissance)
{
$this->dateDeNaissance = $dateDeNaissance;
return $this;
}
/**
* Get the value of lieuDeNaissance
*/
public function getLieuDeNaissance()
{
return $this->lieuDeNaissance;
}
/**
* Set the value of lieuDeNaissance
*
* #return self
*/
public function setLieuDeNaissance(string $lieuDeNaissance)
{
$this->lieuDeNaissance = $lieuDeNaissance;
return $this;
}
/**
* Get the value of nationalite
*/
public function getNationalite()
{
return $this->nationalite;
}
/**
* Set the value of nationalite
*
* #return self
*/
public function setNationalite(string $nationalite)
{
$this->nationalite = $nationalite;
return $this;
}
/**
* Get the value of dateElaborationPpe
*/
public function getDateElaborationPpe()
{
return $this->dateElaborationPpe;
}
/**
* Set the value of dateElaborationPpe
*
* #return self
*/
public function setDateElaborationPpe(datetime $dateElaborationPpe)
{
$this->dateElaborationPpe = $dateElaborationPpe;
return $this;
}
/**
* #return Collection|Service[]
*/
public function getServices(): Collection
{
return $this->services;
}
public function addService(Service $service): self
{
if (!$this->services->contains($service)) {
$this->services[] = $service;
}
return $this;
}
public function removeService(Service $service): self
{
$this->services->removeElement($service);
return $this;
}
/**
* #return Collection|User[]
*/
public function getUsers(): Collection
{
return $this->users;
}
public function addUser(User $user): self
{
$test = 'test';
if (!$this->users->contains($user)) {
$this->users[] = $user;
}
return $this;
}
public function removeUser(User $user): self
{
$this->users->removeElement($user);
return $this;
}
public function getNbUsers()
{
return count($this->getUsers());
}
/**
* #return Collection|Element[]
*/
public function getElements(): Collection
{
return $this->elements;
}
public function addElement(Element $element): self
{
if (!$this->elements->contains($element)) {
$this->elements[] = $element;
}
return $this;
}
public function removeElement(Element $element): self
{
$this->elements->removeElement($element);
return $this;
}
public function isNotAssigned(): bool
{
return (!$this->getNbUsers());
}
public function __toString(): string
{
return $this->getNom() . ' ' . $this->getPrenom();
}
}
Thanks in advance for your help.
A User has many Games.
A Game can Belong to many Users.
I have a form with a list of games, I want the list of Games to be added to the current logged User.
When I submit the form nothing happens, I want at least 1 record to be added to users_games:
Update:
Added User entity
FormType addGameToUserType:
namespace AppBundle\Form;
use AppBundle\Entity\Game;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
class addGameToUserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('game', EntityType::class, [
'class' => 'AppBundle:Game',
'choice_label' => function ($game) {
return $game->getName();
},
'multiple' => true,
'expanded' => false,
]);
}
public function configureOptions(OptionsResolver $resolver)
{
}
public function getBlockPrefix()
{
return 'app_bundleadd_game_to_user';
}
}
UserController addGameAction:
/**
* Adds game(s) to current user.
*
* #Route("user/game/add", name="game_add")
* #Method({"GET", "POST"})
*/
public function addGameAction(Request $request)
{
/** #var $form */
$form = $this->createForm('AppBundle\Form\addGameToUserType');
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
echo $form->get('game')->getData();
$em = $this->getDoctrine()->getManager();
/** #var $game */
$game = new Game();
$game->getId();
/** #var User $userObject */
$userObject = $this->getUser();
$user = $em->getRepository('AppBundle:User')
->find(['id' => $userObject->getId()]);
$game->addGameUser($user);
$em->persist($user);
$em->flush();
}
return $this->render('user/addGame.html.twig', array(
'form' => $form->createView()
));
}
Game entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Game
*
* #ORM\Table(name="game")
* #ORM\Entity(repositoryClass="AppBundle\Repository\GameRepository")
*/
class Game
{
/**
* #ORM\OneToMany(targetEntity="PlayLog", mappedBy="game")
* #ORM\OrderBy({"date" = "DESC"})
*
*/
private $playlogs;
private $users;
/**
* #return ArrayCollection
*/
public function getUsers()
{
return $this->users;
}
/**
* #param ArrayCollection $users
*/
public function setUsers($users)
{
$this->users = $users;
}
// private $categories;
public function __construct()
{
$this->playlogs = new ArrayCollection();
$this->users = new ArrayCollection();
}
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
* #Assert\NotBlank()
* #Assert\Length(
* min = "3",
* max = "100"
* )
* #ORM\Column(name="name", type="string", length=255, unique=true)
*/
private $name;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Game
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* #return mixed
*/
public function getPlaylogs()
{
return $this->playlogs;
}
/**
* #param mixed $playlogs
*/
public function setPlaylogs($playlogs)
{
$this->playlogs = $playlogs;
}
public function addPlayLog(PlayLog $playlog)
{
$this->playlog->add($playlog);
$playlog->setPlayLogs($this);
}
public function addGameUser(User $user){
$this->users[] = $user;
}
}
User entity:
namespace AppBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\ManyToMany(targetEntity="Game")
*
* #ORM\JoinTable(name="users_games",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="game_id", referencedColumnName="id")}
* )
*/
private $games;
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\PlayLog", mappedBy="user")
*
*/
private $playlogs;
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
/**
* #param mixed $id
*/
public function setId($id)
{
$this->id = $id;
}
public function __construct()
{
$this->games = new ArrayCollection();
}
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #return mixed
*/
public function getGames()
{
return $this->games;
}
/**
* #param mixed $games
*/
public function setGames($games)
{
$this->games = $games;
}
public function addGame(Game $game)
{
// $this->games->add($game);
$this->games[] = $game;
return $this;
}
public function removeGame(Game $game)
{
$this->games->removeElement($game);
}
/**
* #return mixed
*/
public function getPlaylogs()
{
return $this->playlogs;
}
/**
* #param mixed $playlogs
*/
public function setPlaylogs($playlogs)
{
$this->playlogs = $playlogs;
}
public function addPlayLog(PlayLog $playlog)
{
$this->playlog->add($playlog);
$playlog->setPlayLogs($this);
}
}
i have a big problem implementing JWT Tokens on symfony.
I already make work the JWT token, but i need to add to the token info the User roles too. i am doing this using a Listener (JWTCreatedListener):
public function onJWTCreated(JWTCreatedEvent $event)
{
$request = $this->requestStack->getCurrentRequest();
$payload = $event->getData();
$payload['ip'] = $request->getClientIp();
$payload['roles'] = $event->getUser()->getRoles();
$event->setData($payload);
}
I implemented the Role.php (AppBundle/Entity/Role.php) on this way:
<?php
namespace AppBundle\Entity;
use Symfony\Component\Security\Core\Role\RoleInterface;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table(name="acme_role")
* #ORM\Entity()
*/
class Role implements RoleInterface
{
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id()
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\Column(name="name", type="string", length=30)
*/
private $name;
/**
* #ORM\Column(name="role", type="string", length=20, unique=true)
*/
private $role;
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="roles")
*/
private $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
/**
* #see RoleInterface
*/
public function getRole()
{
return $this->role;
}
// ... getters and setters for each property
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Role
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set role
*
* #param string $role
*
* #return Role
*/
public function setRole($role)
{
$this->role = $role;
return $this;
}
/**
* 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;
}
}
And my User class:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Table(name="users")
* #ORM\Entity
*/
class User implements AdvancedUserInterface, \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=500)
*/
private $password;
/**
* #ORM\Column(name="is_active", type="boolean")
*/
private $isActive;
/**
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
*
*/
private $roles;
public function __construct($username)
{
$this->isActive = true;
$this->username = $username;
$this->roles = new ArrayCollection();
}
public function getUsername()
{
return $this->username;
}
public function getSalt()
{
return null;
}
public function getPassword()
{
return $this->password;
}
public function setPassword($password)
{
$this->password = $password;
}
public function getRoles()
{
return $this->roles->toArray();
}
public function eraseCredentials()
{
}
/**
* 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 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;
}
/**
* Add role
*
* #param \AppBundle\Entity\Role $role
*
* #return User
*/
public function addRole(\AppBundle\Entity\Role $role)
{
$this->roles[] = $role;
return $this;
}
/**
* Remove role
*
* #param \AppBundle\Entity\Role $role
*/
public function removeRole(\AppBundle\Entity\Role $role)
{
$this->roles->removeElement($role);
}
public function isAccountNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isEnabled()
{
return $this->isActive;
}
// serialize and unserialize must be updated - see below
public function serialize()
{
return serialize(array(
// ...
$this->isActive
));
}
public function unserialize($serialized)
{
list (
// ...
$this->isActive
) = unserialize($serialized);
}
}
The problem is that this method getRole() always returns empty.
This is my db data:
[users]
id username password is_active
1 abriceno $2y$13$NW6uNOKJGUQTSXirej4HKOwIa6mWzYqFxzz1ppWQjyp... 1
[acme_role]
id name role
1 admin ROLE_ADMIN
[user_role]
user_id user_role
1 1
Also, i try to call the data from a controller test using doctrine:
public function indexAction(Request $request)
{
$repository = $this->getDoctrine()->getRepository('AppBundle:User');
$user = $repository->findOneByusername('abriceno');
$username = $user->getUsername();
$roles = $user->getRoles();
$arr = array(
'username' => $user->getUsername(),
'password' => $user->getPassword(),
'roles' => $user->getRoles()
);
return new JsonResponse($arr);
this returns:
{"username":"abriceno","password":"$2y$13$NW6uNOKJGUQTSXirej4HKOwIa6mWzYqFxzz1ppWQjypQJLIgUGJ.m","roles":[{}]}
I am so desperate... thanks for all the help that you can provide to me.
UPDATE 1
If i do print_r($role) this prints a huuuuuge list of values:
array(1) { [0]=> object(AppBundle\Entity\Role)#624 (4) { ["id":"AppBundle\Entity\Role":private]=> int(1) ["name":"AppBundle\Entity\Role":private]=> string(5) "admin" ["role":"AppBundle\Entity\Role":private]=> string(10) "ROLE_ADMIN" ["users":"AppBundle\Entity\Role":private]=> object(Doctrine\ORM\PersistentCollection)#626 (9) { ["snapshot":"Doctrine\ORM\PersistentCollection":private]=> array(0) { } ["owner":"Doctrine\ORM\PersistentCollection":private]=> *RECURSION*
... and keeps going... very strange!!
Seems that the join table is not handled directly by doctrine, so you need do specify to doctrine howto map the referenced fied with the JoinTable annotation (See the default mapping section.)
In your case, try to modify the roles relation definition in the User entity as follow:
/**
* #ORM\ManyToMany(targetEntity="Role", inversedBy="users")
* #ORM\JoinTable(name="user_role",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="user_role", referencedColumnName="id")})
*
*/
private $roles;
Hope this help
Finally i fix this with this code:
// Work of roles
$roles = $event->getUser()->getRoles();
$role_length = count($roles);
$role_list = array();
for ($i=0; $i <$role_length ; $i++) {
array_push($role_list,$roles[$i]->getRole());
}
$payload = $event->getData();
$payload['ip'] = $request->getClientIp();
$payload['roles'] = $role_list;
The problem (i guess) is on the ->getRoles(); code. This returns a array of Entity\Role class, not an array of roles.
Now the dump is:
{
"token": "eyJhbGciOiJSUzI1NiJ9.....",
"data": {
"roles": [
"ROLE_ADMIN"
]
}
}
I have three database tables. user, meeting, group. The meetings and group table are manytomany associations from the user table. So I can do user->getmeetings(), or user->getgroups().
I want to get just the next meeting comping up for the user, and I don't know how to achieve this. Whether by SQL Query or simply in the controller. Here is what I have done so far.
$loggedInUser = $em->getRepository('AppBundle\Entity\User')
->find($id);
foreach ($loggedInUser->getMeetings() as $userMeetings) {
$nextMeeting[$userMeetings->getId()]['id'] = $userMeetings->getId();
$nextMeeting[$userMeetings->getId()]['group'] = $userMeetings->getGroup();
$nextMeeting[$userMeetings->getId()]['name'] = $userMeetings->getName();
$nextMeeting[$userMeetings->getId()]['info'] = $userMeetings->getInfo();
$nextMeeting[$userMeetings->getId()]['bring'] = $userMeetings->getBring();
$nextMeeting[$userMeetings->getId()]['summary'] = $userMeetings->getSummary();
$nextMeeting[$userMeetings->getId()]['files'] = $userMeetings->getFiles();
$nextMeeting[$userMeetings->getId()]['meetingDate'] = $userMeetings->getMeetingDate();
$nextMeeting[$userMeetings->getId()]['meetingAddress'] = $userMeetings->getMeetingAddress();
$nextMeeting[$userMeetings->getId()]['time_diff'] = date_diff($userMeetings->getMeetingDate(), new \DateTime());
}
I have added a time_diff field in the new array to calculate the time from now to the meeting time. All I need to do now is select the smallest one.How can I do this? Thank you.
UPDATE - Below is my User Repository
namespace AppBundle\Repository;
use AppBundle\Entity\User;
use AppBundle\Entity\Meeting;
use Doctrine\ORM\EntityRepository;
use Doctrine\Common\Collections\Criteria;
class UserRepository extends EntityRepository
{
public function getComingMeeting()
{
$criteria = Criteria::create()
->where(Criteria::expr()->gte("meetingDate", new \DateTime('now')))
->orderBy(array("meetingDate" => Criteria::ASC))
->setMaxResults(1);
$this->getMeetings()->matching($criteria);
}
}
Below is my User Entity
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;
/**
* #ORM\Entity(repositoryClass="AppBundle\Repository\UserRepository")
* #ORM\Table(name="user")
*/
class User
{
/**
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", nullable=false)
*/
private $first_name;
/**
* #ORM\Column(type="string", nullable=false)
*/
private $last_name;
/**
* #ORM\Column(type="string", nullable=false, unique=true)
*/
private $email_address;
/**
* #ORM\Column(type="string", nullable=true)
*/
private $phone_number;
/**
* #ORM\Column(type="string", nullable=false)
*/
private $password;
/**
* #ORM\Column(type="datetime", nullable=true)
*/
private $last_login;
/**
* #ORM\Column(type="string", nullable=true)
*/
private $reset_password;
/**
* #ORM\ManyToMany(targetEntity="Meeting", inversedBy="users")
*/
private $meetings;
/**
* #ORM\ManyToMany(targetEntity="Group", inversedBy="users")
*/
private $groups;
public function __construct()
{
$this->groups = new arrayCollection();
$this->meetings = new arrayCollection();
}
/**
* #return mixed
*/
public function getFirstName()
{
return $this->first_name;
}
/**
* #param mixed $first_name
*/
public function setFirstName($first_name)
{
$this->first_name = $first_name;
}
/**
* #return mixed
*/
public function getLastName()
{
return $this->last_name;
}
/**
* #param mixed $last_name
*/
public function setLastName($last_name)
{
$this->last_name = $last_name;
}
/**
* #return mixed
*/
public function getEmailAddress()
{
return $this->email_address;
}
/**
* #param mixed $email_address
*/
public function setEmailAddress($email_address)
{
$this->email_address = $email_address;
}
/**
* #return mixed
*/
public function getPhoneNumber()
{
return $this->phone_number;
}
/**
* #param mixed $phone_number
*/
public function setPhoneNumber($phone_number)
{
$this->phone_number = $phone_number;
}
/**
* #return mixed
*/
public function getPassword()
{
return $this->password;
}
/**
* #param mixed $password
*/
public function setPassword($password)
{
$this->password = $password;
}
/**
* #return mixed
*/
public function getLastLogin()
{
return $this->last_login;
}
/**
* #param mixed $last_login
*/
public function setLastLogin($last_login)
{
$this->last_login = $last_login;
}
/**
* #return mixed
*/
public function getResetPassword()
{
return $this->reset_password;
}
/**
* #param mixed $reset_password
*/
public function setResetPassword($reset_password)
{
$this->reset_password = $reset_password;
}
/**
* #return arrayCollection|Meeting[]
*/
public function getMeetings()
{
return $this->meetings;
}
/**
* #return ArrayCollection|Group[]
*/
public function getGroups()
{
return $this->groups;
}
/**
* #return mixed
*/
public function getId()
{
return $this->id;
}
}
below is my HomeControlller.php
class HomeController extends Controller
{
/**
* #Route("/home", name="home_show")
*/
public function showAction()
{
$em = $this->getDoctrine()->getManager();
//logged in user
$id = 1;
$loggedInUser = $em->getRepository('AppBundle\Entity\User')
->find($id);
foreach ($loggedInUser->getMeetings() as $userMeetings) {
$nextMeeting[$userMeetings->getId()]['id'] = $userMeetings->getId();
$nextMeeting[$userMeetings->getId()]['group'] = $userMeetings->getGroup();
$nextMeeting[$userMeetings->getId()]['name'] = $userMeetings->getName();
$nextMeeting[$userMeetings->getId()]['info'] = $userMeetings->getInfo();
$nextMeeting[$userMeetings->getId()]['bring'] = $userMeetings->getBring();
$nextMeeting[$userMeetings->getId()]['summary'] = $userMeetings->getSummary();
$nextMeeting[$userMeetings->getId()]['files'] = $userMeetings->getFiles();
$nextMeeting[$userMeetings->getId()]['meetingDate'] = $userMeetings->getMeetingDate();
$nextMeeting[$userMeetings->getId()]['meetingAddress'] = $userMeetings->getMeetingAddress();
$nextMeeting[$userMeetings->getId()]['time_diff'] = date_diff($userMeetings->getMeetingDate(), new \DateTime());
}
$groups = $em->getRepository('AppBundle\Entity\Group')
->findAll();
return $this->render('home/show.html.twig', [
'loggedInUser' => $loggedInUser,
'groups' => $groups,
]);
}
}
You can add a method in your UserEntity with a matching criteria on meeting collection
namespace AppBundle\Entity;
use Doctrine\Common\Collections\Criteria;
....
public function getComingMeeting()
{
$criteria = Criteria::create()
->where(Criteria::expr()->gte("meetingDate", new \DateTime('now')))
->orderBy(array("meetingDate" => Criteria::ASC))
->setMaxResults(1);
return $this->getMeetings()->matching($criteria);
}
see http://doctrine-orm.readthedocs.io/projects/doctrine-orm/en/latest/reference/working-with-associations.html
I'm trying to do file upload for my Task entity. I working with two sources:
http://symfony.com/doc/3.4/controller/upload_file.html and Symfony2 file upload step by step but I can't figure out how to keep uploaded file during editing.
I'm not sure if I implemented right the part:
My form was complaining when I tried to edit any Task:
The form's view data is expected to be an instance of class
Symfony\Component\HttpFoundation\File\File, but is a(n) string. You
can avoid this error by setting the "data_class" option to null or by
adding a view transformer that transforms a(n) string to an instance
of Symfony\Component\HttpFoundation\File\File.
So I modified getter getBrochure() in my Task entity which I want to expand of PDF file. Please, see below my getBrochure method This is code of my entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\File;
/**
* Task
*
* #ORM\Table(name="task")
* #ORM\Entity(repositoryClass="AppBundle\Repository\TaskRepository")
*/
class Task
{
/**
* #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=255)
*/
private $name;
/**
* #var \DateTime
*
* #ORM\Column(name="datetime", type="datetime")
*/
private $datetime;
/**
* #ORM\ManyToMany(targetEntity="Category", inversedBy="tasks")
* #ORM\JoinTable(name="categories_tasks")
*/
private $categories;
/**
* #ORM\Column(type="text")
*/
private $description;
/**
* #ORM\Column(type="string")
*
* #Assert\File(mimeTypes={ "application/pdf" })
*/
private $brochure;
public function __construct() {
$this->categories = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Task
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set datetime
*
* #param \DateTime $datetime
*
* #return Task
*/
public function setDatetime($datetime)
{
$this->datetime = $datetime;
return $this;
}
/**
* Get datetime
*
* #return \DateTime
*/
public function getDatetime()
{
return $this->datetime;
}
public function getCategories()
{
return $this->categories;
}
public function setCategories(Category $categories)
{
$this->categories = $categories;
}
public function getDescription()
{
return $this->description;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getBrochure()
{
//return $this->brochure;
return new File($this->brochure);
}
public function setBrochure($brochure)
{
$this->brochure = $brochure;
return $this;
}
public function __toString() {
return $this->name;
}
}
?>
The result is that I can load edit page, but the field of file upload is empty, there is no information that I uploaded any file. I'm not sure if there should be any information but I see in database that the filename is there and also in web folder there is uploaded file. When I change anything in Task and save of file is cleared and when I try to launch edit page I see:
The file "" does not exis
What is clear for me, because file column for this Task was cleared. So, how to keep file during editing when I don't want to upload new file?
This is my TaskType
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Ivory\CKEditorBundle\Form\Type\CKEditorType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
class TaskType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('name')->add('datetime')->add('categories')
->add('description', 'Ivory\CKEditorBundle\Form\Type\CKEditorType', array())
->add('brochure', FileType::class, array('label' => 'Broszurka (PDF)', 'required' => false));
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Task'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_task';
}
}
and this is my TaskController (only edit action)
/**
* Displays a form to edit an existing task entity.
*
* #Route("/{id}/edit", name="task_edit")
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, Task $task)
{
$deleteForm = $this->createDeleteForm($task);
$editForm = $this->createForm('AppBundle\Form\TaskType', $task);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('task_edit', array('id' => $task->getId()));
}
return $this->render('task/edit.html.twig', array(
'task' => $task,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
Task Entity:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\File;
/**
* Task
*
* #ORM\Table(name="task")
* #ORM\Entity(repositoryClass="AppBundle\Repository\TaskRepository")
*/
class Task
{
/**
* #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=255)
*/
private $name;
/**
* #var \DateTime
*
* #ORM\Column(name="datetime", type="datetime")
*/
private $datetime;
/**
* #ORM\ManyToMany(targetEntity="Category", inversedBy="tasks")
* #ORM\JoinTable(name="categories_tasks")
*/
private $categories;
/**
* #ORM\Column(type="text")
*/
private $description;
/**
* #ORM\Column(type="string")
*
* #Assert\File(mimeTypes={ "application/pdf" })
*/
private $brochure;
public function __construct() {
$this->categories = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Task
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set datetime
*
* #param \DateTime $datetime
*
* #return Task
*/
public function setDatetime($datetime)
{
$this->datetime = $datetime;
return $this;
}
/**
* Get datetime
*
* #return \DateTime
*/
public function getDatetime()
{
return $this->datetime;
}
public function getCategories()
{
return $this->categories;
}
public function setCategories(Category $categories)
{
$this->categories = $categories;
}
public function getDescription()
{
return $this->description;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getBrochure()
{
//return $this->brochure;
return new File($this->brochure);
}
public function setBrochure($brochure)
{
$this->brochure = $brochure;
return $this;
}
public function __toString() {
return $this->name;
}
}
?>
You should check the file and then,If the user did not select the file,Select the file name from the database
if ($editForm->isSubmitted() && $editForm->isValid()) {
$em = $this->getDoctrine()->getManager();
$form->handleRequest($request);
$TaskRepo=$em->getRepository('AppBundle:Task');
$Taskdata = $TaskRepo->find($id);///id task
$Taskdata->setName($form->get('name')->getData());
$Taskdata->setDescription($form->get('description(')->getData());
$Taskdata->setDatetime(new \DateTime('now'));
if($form->get('brochure')->getData() != ""){////Check the file selection status
$file2 = $form->get('brochure')->getData();
$fileName2 = md5(uniqid()).'.'.$file2->guessExtension();
$file2->move(
$this->getParameter('brochures_directory'), $fileName2);
$Taskdata->setBrochure($fileName2);
}
$em->flush();
}
OK I found the problem few seconds after I wrote comment and added Task entity code. In getBrochure method I tried to create File object for every Task instance even it hasn't any brochure so the solution is to use:
public function getBrochure()
{
return $this->brochure;
//return new File($this->brochure);
}