I am trying to learn Symfony2 and currently : Entity Relationships/Associations (Joining to Related Records) . I have a problem I can not get correct
Notice: Undefined index: roles 500 Internal Server Error -
ContextErrorException
This is the my code:
*Class Role:
class Roles
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nom_roles", type="string", length=225, nullable=false)
*#Assert\NotBlank(message="le champ nom du role est obligatoire")
*
*/
Private $name_role;
/**
* #var ArrayCollection $groups
*
* #ORM\OneToMany(targetEntity="Groups", mappedBy="roles", cascade={"persist","merge"})
*#Assert\Valid()
*/
protected $groups;
/**
* #var ArrayCollection Permissions $permision
*
* #ORM\ManyToMany(targetEntity="Permissions", inversedBy="roleGroup", cascade={"persist", "merge"})
* #ORM\JoinTable(name="roles_permissions",
* joinColumns={#ORM\JoinColumn(name="id_rolesGR", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="id_permGR", referencedColumnName="id_per")}
* )
* #Assert\Valid()
*/
protected $permissions_role;
/**
* Roles constructor.
*/
public function __construct()
{
$this->groups = new ArrayCollection();
$this->permissions_role = new ArrayCollection();
}
-class permissions:
class Permissions {
/**
* #var integer
*
* #ORM\Column(name="id_per", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
* #ORM\Column(name="nom_permisions", length=255, nullable=true)
* #Assert\NotBlank(message="le choix des permissions sont obligatoire")
*/
private $name_permissions;
/**
* #var ArrayCollection Roles $roleGroup
*
* Inverse Side
*
* #ORM\ManyToMany(targetEntity="Roles", mappedBy="permissions", cascade={"persist", "merge"})
*#Assert\Valid()
*/
protected $roleGroup;
-Class Groups:
class Groups
{
/**
* #var integer
*
* #ORM\Column(name="id_groupes", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*
*/
private $id;
/**
* #var string
*
*-- contrainte sur le chmap
*
* #Assert\NotBlank(message="le champ nom du groupe est obligatoire")
*
* #Assert\Type(
* type="string",
* message="la valeur {{ value }} n'est pas valide {{ type }}.
* Elle est de type chaine des cractéres"
* )
*
* #Assert\Length(
* min=5,
* max= 50,
* minMessage="votre nom du groupe doit comprendre au moins {{ limit }} caractéres",
* maxMessage="votre nom du groupe doit comprendre au maximun {{ limit }} caractéres"
* )
*
* #ORM\Column(name="nom_groupe", type="string", length=225, nullable=false)
*#Assert\NotBlank(message="le champ nom du groupe est obligatoire")
*
*
*/
Private $name_groups;
/**
* #var DateTime()
*
* #ORM\Column(name="date_creation", type="datetime",nullable=false)
*
*#Assert\DateTime()
*/
private $date_create;
/**
* #ORM\OneToOne(targetEntity="Images", cascade={"persist", "merge", "remove"})
* #ORM\JoinColumn(name="image_id", referencedColumnName="id_images")
* #Assert\Valid()
*/
protected $image;
/**
* #var Roles $role
*
* #ORM\ManyToOne(targetEntity="Roles", inversedBy="groups", cascade={"persist", "merge"})
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="role_id", referencedColumnName="id", nullable=false)
* })
* #Assert\Valid()
*/
protected $role;
-here is my controller
class GroupsController extends Controller
{ public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('GroupsBundle:Groups')->findAll();
return $this->render('GroupsBundle:Groups:index.html.twig', array(
'entities' => $entities,
));
}
/**
* Creates a new Groups entity.
*
*/
public function createAction(Request $request)
{
$entity = new Groups();
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('groups_show', array('id' => $entity->getId())));
}
return $this->render('GroupsBundle:Groups:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
/**
* Creates a form to create a Groups entity.
*
* #param Groups $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(Groups $entity)
{
$form = $this->createForm(new GroupsType(), $entity, array(
'action' => $this->generateUrl('groups_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new Groups entity.
*
*/
public function newAction()
{
$entity = new Groups();
$form = $this->createCreateForm($entity);
return $this->render('GroupsBundle:Groups:new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
/**
* Finds and displays a Groups entity.
*
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('GroupsBundle:Groups')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Groups entity.');
}
$deleteForm = $this->createDeleteForm($id);
return $this->render('GroupsBundle:Groups:show.html.twig', array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing Groups entity.
*
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('GroupsBundle:Groups')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Groups entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('GroupsBundle:Groups:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Creates a form to edit a Groups entity.
*
* #param Groups $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createEditForm(Groups $entity)
{
$form = $this->createForm(new GroupsType(), $entity, array(
'action' => $this->generateUrl('groups_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing Groups entity.
*
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('GroupsBundle:Groups')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Groups entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('groups_edit', array('id' => $id)));
}
return $this->render('GroupsBundle:Groups:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Deletes a Groups entity.
*
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('GroupsBundle:Groups')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Groups entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('groups'));
}
/**
* Creates a form to delete a Groups entity by id.
*
* #param mixed $id The entity id
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('groups_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
}
the problem:
Catchable Fatal Error: Argument 1 passed to
Doctrine\Common\Collections\ArrayCollection::__construct() must be of
the type array, object given, called in
/home/cros/Desktop/Project_Console/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php
on line 555 and defined 500 Internal Server Error -
ContextErrorException
*Stack Trace:
in vendor/doctrine/collections/lib/Doctrine/Common/Collections/ArrayCollection.php at line 48 -
/*
* #param array $elements
*/
public function __construct(array $elements = array())
{
$this->elements = $elements;
}
at ErrorHandler ->handleError ('4096', 'Argument 1 passed to
Doctrine\Common\Collections\ArrayCollection::__construct() must be of
the type array, object given, called in
/home/cros/Desktop/Project_Console/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php
on line 555 and defined',
'/home/Cros/Desktop/Project_Console/vendor/doctrine/collections/lib/Doctrine/Common/Collections/ArrayCollection.php',
My GroupsType and RolesType:
class GroupsType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('image',new ImagesType())
->add('name_groups', 'text',array('required' => true, 'attr' => array('placeholder' => 'Nom du groupe')))
->add('role', new RolesType())
;
}
}
//My RolesType:
class RolesType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('groups', 'entity',array(
'class' => 'GroupsBundle:Roles',
'choice_label' => 'name_role',
/*'query_builder' => function(EntityRepository $er)
{
return $er->createQueryBuilder('r')
->orderBy('r.id', 'ASC');
},*/
'required' => true,
'placeholder' => 'Choisir le role du votre groupe'
)
)
->add('permissions_role','entity',array(
'class' => 'GroupsBundle:Permissions',
'multiple' => true,
'expanded' => true,
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.id', 'ASC');
},
'required' => true
)
)
// ->add('permissions_role','number')
;
Thank you
It's quite hard to dig through all the code you've supplied here, but I'll try to help.
As I see, the $groups property in your Roles class is annotated with OneToMany having mappedBy set to "roles".
/**
* #var ArrayCollection $groups
*
* #ORM\OneToMany(targetEntity="Groups", mappedBy="roles", cascade={"persist","merge"})
* #Assert\Valid()
*/
protected $groups;
The target entity of the relation is Groups, and as far as I see from your listings, this entity does not have a roles property, it has role instead:
/**
* #var Roles $role
*
* #ORM\ManyToOne(targetEntity="Roles", inversedBy="groups", cascade={"persist", "merge"})
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="role_id", referencedColumnName="id", nullable=false)
* })
* #Assert\Valid()
*/
protected $role;
You should try renaming this property to roles instead.
Related
I am using symfony 3.4.
I have entity user which is linked to entity campagne(campaign) (one to many), when I want to add a new campagnethis error is displayed:
An exception occurred while executing 'INSERT INTO compagne (desc, user_id) VALUES (?, ?)' with params ["ycamp2", null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null
class Campagne:
class Campagne
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* #var string|null
*
* #ORM\Column(name="desc", type="string", length=255, nullable=true, unique=true)
*
*/
private $desc;
/**
* #ORM\ManyToOne(targetEntity="XxBundle\Entity\User", inversedBy="campagnes")
* #ORM\JoinColumn(nullable=false)
*/
private $user;
//...
/**
* Set user.
*
* #param \XxBundle\Entity\User $user
*
* #return Campagne
*/
public function setUser(\XxBundle\Entity\User $user)
{
$this->user = $user;
return $this;
}
/**
* Get user.
*
* #return \XxBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
}
class user:
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
//...
/**
* #ORM\OneToMany(targetEntity="XxBundle\Entity\Campagne", mappedBy="user", cascade={"persist", "remove"})
*/
private $campagnes;
// .................CAMPAGNE..............
/**
* Add campagne.
*
* #param \XxBundle\Entity\Capagne $campagne
*
* #return User
*/
public function addCampagne(\XxBundle\Entity\Campagne $campagne)
{
$this->campagnes[] = $campagne;
return $this;
}
/**
* Remove campagne.
*
* #param \XxBundle\Entity\Campagne $campagne
*
* #return boolean TRUE if this collection contained the specified element, FALSE otherwise.
*/
public function removeCampagne(\XxBundle\Entity\Campagne $campagne)
{
return $this->campagnes->removeElement($campagne);
}
/**
* Get campagnes.
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCampagnes()
{
return $this->campagnes;
}
}
campagne controller:
class CampagneController extends Controller
{
/**
* Lists all campagne entities.
*
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$campagnes= $em->getRepository('XxBundle:Campagne')->findAll();
return $this->render('campagne/index.html.twig', array(
'campagnes' => $campagnes,
));
}
/**
* Creates a new campagne entity.
*
*/
public function newAction(Request $request)
{
$campagne = new Campagne();
$form = $this->createForm('XxBundle\Form\CampagneType', $campagne);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return $this->redirectToRoute('campagne_show', array('id' => $campagne->getId()));
}
return $this->render('campagne/new.html.twig', array(
'campagne' => $campagne,
'form' => $form->createView(),
));
}
/**
* Finds and displays a campagne entity.
*
*/
public function showAction(Campagne $campagne)
{
$deleteForm = $this->createDeleteForm($campagne);
return $this->render('campagne/show.html.twig', array(
'campagne' => $campagne,
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing campagne entity.
*
*/
public function editAction(Request $request, Campagne $campagne)
{
$deleteForm = $this->createDeleteForm($campagne);
$editForm = $this->createForm('XxBundle\Form\CampagneType', $Campagne);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('campagne_edit', array('id' => $campagne->getId()));
}
return $this->render('Campagne/edit.html.twig', array(
'campagne' => $campagne,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Deletes a campagne entity.
*
*/
public function deleteAction(Request $request, Campagne $campagne)
{
$form = $this->createDeleteForm($campagne);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->remove($campagne);
$em->flush();
}
return $this->redirectToRoute('campagne_index');
}
/**
* Creates a form to delete a campagne entity.
*
* #param Campagne $campagne The campagne entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm(Campagne $campagne)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('campagne_delete', array('id' => $campagne->getId())))
->setMethod('DELETE')
->getForm()
;
}
}
user controller:
class UserController extends Controller
{
/**
* Lists all user entities.
*
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$users = $em->getRepository('XxBundle:User')->findAll();
return $this->render('user/index.html.twig', array(
'users' => $users,
));
}
/**
* Creates a new user entity.
*
*/
public function newAction(Request $request)
{
$user = new User();
$form = $this->createForm('XxBundle\Form\UserType', $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($user);
$em->flush();
return $this->redirectToRoute('user_show', array('id' => $user->getId()));
}
return $this->render('user/new.html.twig', array(
'user' => $user,
'form' => $form->createView(),
));
}
/**
* Finds and displays a user entity.
*
*/
public function showAction(User $user)
{
$deleteForm = $this->createDeleteForm($user);
return $this->render('user/show.html.twig', array(
'user' => $user,
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing user entity.
*
*/
public function editAction(Request $request, User $user)
{
$deleteForm = $this->createDeleteForm($user);
$editForm = $this->createForm('XxBundle\Form\UserType', $user);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('user_edit', array('id' => $user->getId()));
}
return $this->render('user/edit.html.twig', array(
'user' => $user,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Deletes a user entity.
*
*/
public function deleteAction(Request $request, User $user)
{
$form = $this->createDeleteForm($user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->remove($user);
$em->flush();
}
return $this->redirectToRoute('user_index');
}
/**
* Creates a form to delete a user entity.
*
* #param User $user The user entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm(User $user)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('user_delete', array('id' => $user->getId())))
->setMethod('DELETE')
->getForm()
;
}
}
You've run into a NOT NULL constraint on your database table. You'll either need to alter the table to allow for null insertion or ensure that you're always passing a user_id within your request.
We have an error when trying to create a relationship within 2 tables like this
Llamadas -||--|<- LlamadaDerivada ->|--||- PersonaDerivada
And we are trying to create an only one create form with the "LlamadaDerivada" into it.
Inside Llamada entity
<?php
namespace xxxxBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
class Llamada {
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="SEQUENCE")
* #ORM\SequenceGenerator(sequenceName="llamada_id_seq", allocationSize=1, initialValue=1)
*/
private $id;
/**
* #var string
* #Assert\Length(
* max = 50,
* maxMessage = "Your first name cannot be longer than {{ limit }} characters",
* )
* #ORM\Column(name="nombre", type="string", length=150, nullable=false)
*/
private $nombre;
/**
*
* #ORM\OneToMany(targetEntity="LlamadaDerivado", mappedBy="llamada")
*/
private $derivados;
function __construct() {
$this->derivados = new ArrayCollection();
}
function getId() {
return $this->id;
}
function getNombre() {
return $this->nombre;
}
function setId($id) {
$this->id = $id;
}
function setNombre($nombre) {
$this->nombre = $nombre;
}
function getDerivados(){
return $this->derivados;
}
function setDerivados($derivados){
$this->derivados = $derivados;
}
}
Then inside LlamadaDerivado Entity we have this
<?php
namespace xxxBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* LlamadaDerivado
*
* #ORM\Table(name="llamada_derivado")
* #ORM\Entity
*/
class LlamadaDerivado
{
/**
* #var \AgendaBundle\Entity\Llamada
*
* #ORM\ManyToOne(targetEntity="AgendaBundle\Entity\Llamada",inversedBy="derivados",cascade={"persist"})
* #ORM\Id
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_llamada", referencedColumnName="id")
* })
*/
private $llamada;
/**
* #var \AgendaBundle\Entity\PersonaDerivado
*
* #ORM\ManyToOne(targetEntity="AgendaBundle\Entity\PersonaDerivado",inversedBy="llamadas",cascade={"persist"})
* #ORM\Id
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_derivado", referencedColumnName="id")
* })
*/
private $derivado;
/**
* #var DateTime
*
* #ORM\Column(name="fecha_derivacion", type="date", nullable=false)
*/
private $fechaDerivacion;
function getLlamada(){
return $this->llamada;
}
function getDerivado(){
return $this->derivado;
}
function getFechaDerivacion() {
return $this->fechaDerivacion;
}
function setLlamada( $llamada) {
$this->llamada = $llamada;
}
function setDerivado( $derivado) {
$this->derivado = $derivado;
}
function setFechaDerivacion($fechaDerivacion) {
$this->fechaDerivacion = $fechaDerivacion;
}
}
And inside PersonaDerivado entity
<?php
namespace xxxBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
* ReunionLugar
*
* #ORM\Table(name="persona_derivado")
* #ORM\Entity
*/
class PersonaDerivado
{
public function __construct() {
$this->llamadas = new ArrayCollection();
}
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="SEQUENCE")
* #ORM\SequenceGenerator(sequenceName="reunion_lugar_id_seq", allocationSize=1, initialValue=1)
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="nombre", type="string", length=150, nullable=false)
*/
private $nombre;
/**
* #ORM\OneToMany(targetEntity="LlamadaDerivado", mappedBy="derivado")
*/
private $llamadas;
function getId() {
return $this->id;
}
function getNombre() {
return $this->nombre;
}
function setId($id) {
$this->id = $id;
}
function setNombre($nombre) {
$this->nombre = $nombre;
}
function setLlamadas($llamadas) {
$this->llamadas = $llamadas;
}
}
And the LlamadaType is
class LlamadaDto extends AbstractType {
public function buildForm(FormBuilderInterface $builder, array $options) {
$disabled = $options['disabled'];
$builder
->add('id', HiddenType::class)
->add('nombre', TextType::class, array(
'disabled' => $disabled,
'attr' => ['maxlength'=>'50']
))->add('apellido', TextType::class, array(
'disabled' => $disabled,
'attr' => ['maxlength'=>'50']
))->add('fecha', DateType::class, array(
'format' => 'dd/MM/yyyy',
'disabled' => $disabled,
'widget' => 'single_text',
'attr' => ['class' => 'datepicker']
))->add('hora', TimeType::class, array(
'disabled' => $disabled
))->add('motivo', TextareaType::class, array(
'disabled' => $disabled,
'attr' => ['maxlength'=>'400']
))->add('telefonoContacto', TextType::class, array(
'disabled' => $disabled,
'attr' => ['maxlength'=>'9']
))->add('derivados', EntityType::class, array(
'class' => 'AgendaBundle:PersonaDerivado',
'choice_label' => 'apellidoNombre',
'placeholder' => 'Seleccionar un derivado',
'multiple' => true,
));
}
public function configureOptions(OptionsResolver$resolver) {
$resolver->setDefaults(array('data_class' => Llamada::class));
}
}
Inside the controller we have this code
<?php
/**
* #Route("/Llamada/save",name="saveLlamada")
*/
public function saveLlamadaAction(Request $request) {
$llamadaService = $this->get('llamadaService');
$derivadoService = $this->get('derivadoService');
$form = $this->createForm(LlamadaDto::class);
$form->handleRequest($request);
$editar = TRUE;
$llamada = $form->getData();
$derivados = $request->request->get("llamada_dto")["derivados"];
$derivadosActuales = $derivadoService->getLlamadaDerivados($llamada->getId());
foreach ($derivados as $key1 => $d) {
foreach ($derivadosActuales as $key2 => $da) {
if($da->getDerivado()->getId()==$d){
array_splice($derivados, array_search($d, $derivados),1);
}
}
}
if ($llamadaService->saveLlamada($llamada)) {
$this->addFlash(
'exitoLlamada', 'Datos de llamada guardados exitosamente'
);
$derivadoService->saveDerivados($derivados,$llamada);
} else {
$this->addFlash(
'errorLlamada', 'Disculpe, hubo un error en el registro de la llamada'
);
}
return new RedirectResponse($this->generateUrl('listaLlamadas', array(), UrlGeneratorInterface::RELATIVE_PATH));
}
And the services called are this ones:
public function saveLlamada($llamada ){
try{
if($llamada->getId()){
$this->em->merge($llamada);
}else{
$this->em->persist($llamada);
}
$this->em->flush();
return TRUE;
} catch (Exception $ex){
return FALSE;
}
}
public function saveDerivados($derivados,$llamada){
foreach ($derivados as $key => $derivado) {
$llamadaDerivado = new LlamadaDerivado();
$personaLlamada = $this->getDerivado($derivado);
$llamadaDerivado->setLlamada($llamada);
$llamadaDerivado->setDerivado($personaLlamada);
$llamadaDerivado->setFechaDerivacion(new \DateTime('now', (new \DateTimeZone('America/Argentina/Ushuaia'))));
$this->em->persist($llamadaDerivado);
$this->em->flush();
}
}
This is the error that we are getting:
Uncaught PHP Exception Doctrine\ORM\ORMInvalidArgumentException: "Expected value of type "Doctrine\Common\Collections\Collection|array" for association field "xxxBundle\Entity\Llamada#$derivados", got "xxxBundle\Entity\PersonaDerivado" instead." at project\vendor\doctrine\orm\lib\Doctrine\ORM\ORMInvalidArgumentException.php line 206
We've been 1 week with this.
Many thanks in advance
You can try to use a CollectionType instead of EntityType in your formtype, although I have a piece of code in front of me that works just fine with EntityType and the multiple flag for a OneToMany relationship.
look at Llamada entity, $derivados is an array collection of LlamadaDerivado and in your LlamadaType you make it entityType of AgendaBundle:PersonaDerivado, that is why you got this error. Think to use Collection Type to add everytime all the object LlamadaDerivado to well respect the mapping.
Hi and thank you for taking the time reading this.
English is not my first language so I hope you'll excuse me for any errors.
Currently I'm doing a project to get familiar with Symfony 3.
This is what I'm trying to do:
I have a oneToMany relation, Game to PlayLog.
The relation is established and I can view a list of dates in my games.
I want to create a new PlayLog and be associated with the Game so I can access all my related PlayLogs via Game.
A view is shown with the id of the game (log.html.twig)
My question:
How do I create a new PlayLog with a form and date formField(dateType), and add it to an existing game?
Update: with the current code I now get this error:
An exception occurred while executing 'INSERT INTO play_log (date,
game_id) VALUES (?, ?)' with params ["2017-03-04", null]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'game_id'
cannot be null
This is my code:
--- entity/Game.php
<?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")
*/
private $playlogs;
public function __construct()
{
$this->playlogs = new ArrayCollection();
}
/**
* #ORM\ManyToOne(targetEntity="Type", inversedBy="games")
* #ORM\JoinColumn(name="type_id", referencedColumnName="id")
*/
private $type;
/**
* #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 getType()
{
return $this->type;
}
/**
* #ORM\Column (options={"default" = none})
* #param mixed $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* #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);
}
}
--- entity/PlayLog.php
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* PlayLog
*
* #ORM\Table(name="play_log")
* #ORM\Entity(repositoryClass="AppBundle\Repository\PlayLogRepository")
*/
class PlayLog
{
/**
* #ORM\ManyToOne(targetEntity="Game", inversedBy="playlogs")
* #ORM\JoinColumn(name="game_id", referencedColumnName="id")
*/
private $game;
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="date", type="date")
*/
private $date;
/**
* #var int
*
* #ORM\Column(name="game_id", type="integer")
*/
private $gameId;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set date
*
* #param \DateTime $date
*
* #return PlayLog
*/
public function setDate($date)
{
$this->date = $date;
return $this;
}
/**
* Get date
*
* #return \DateTime
*/
public function getDate()
{
return $this->date;
}
/**
* Set gameId
*
* #param integer $gameId
*
* #return PlayLog
*/
public function setGameId($gameId)
{
$this->gameId = $gameId;
return $this;
}
/**
* Get gameId
*
* #return int
*/
public function getGameId()
{
return $this->gameId;
}
public function addGame(Game $game)
{
$this->games->add($game);
$game->setType($this);
}
public function removeGame(Game $game)
{
$this->games->removeElement($game);
}
}
--- GameController.php
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\Game;
use AppBundle\Entity\PlayLog;
use AppBundle\Entity\Type;
use AppBundle\Form\GameType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\HttpFoundation\Request;
/**
* Game controller.
*
* #Route("game")
*/
class GameController extends Controller
{
/**
* Lists all game entities.
*
* #Route("/", name="game_index")
* #Method("GET")
*/
public function indexAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
// $games = $em->getRepository('AppBundle:Game')->findAll();
$dql = "SELECT game FROM AppBundle:Game game JOIN game.type type ORDER BY game.name";
$query = $em->createQuery($dql);
/*
* #var $paginator \Knp\Component\Pager\Paginator
*/
$paginator = $this->get('knp_paginator');
$result = $paginator->paginate(
$query,
$request->query->getInt('page', 1),
$request->query->getInt('limit', 25)
);
// dump(get_class($paginator));
return $this->render('game/index.html.twig', array(
'games' => $result,
'max_limit_error' => 25
));
}
/**
* Creates a new game entity.
*
* #Route("/new", name="game_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$game = new Game();
$form = $this->createForm('AppBundle\Form\GameType', $game);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($game);
$em->flush($game);
return $this->redirectToRoute('game_show', array('id' => $game->getId()));
}
return $this->render('game/new.html.twig', array(
'game' => $game,
'form' => $form->createView(),
));
}
/**
* Finds and displays a game entity.
*
* #Route("/{id}", name="game_show")
* #Method("GET")
*/
public function showAction(Game $game)
{
$deleteForm = $this->createDeleteForm($game);
return $this->render('game/show.html.twig', array(
'game' => $game,
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing game entity.
*
* #Route("/{id}/edit", name="game_edit")
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, Game $game)
{
$deleteForm = $this->createDeleteForm($game);
$editForm = $this->createForm('AppBundle\Form\GameType', $game);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('game_show', array('id' => $game->getId()));
}
return $this->render('game/edit.html.twig', array(
'game' => $game,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing game entity.
*
* #Route("/{id}/log", name="game_log")
* #Method({"GET", "POST"})
*/
public function addLogAction(Request $request, Game $game)
{
$playlog = new PlayLog();
$form = $this->createForm(GameType::class, $game);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
//Save playLog
$em = $this->getDoctrine()->getManager();
$em->persist($playlog);
$em->flush();
}
// Render / return view incl. formulier.
return $this->render('game/log.html.twig', array(
'game' => $game,
'form' => $form->createView(),
));
}
/**
* Deletes a game entity.
*
* #Route("/{id}", name="game_delete")
* #Method("DELETE")
*/
public function deleteAction(Request $request, Game $game)
{
$form = $this->createDeleteForm($game);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->remove($game);
$em->flush($game);
}
return $this->redirectToRoute('game_index');
}
/**
* Creates a form to delete a game entity.
*
* #param Game $game The game entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm(Game $game)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('game_delete', array('id' => $game->getId())))
->setMethod('DELETE')
->getForm()
;
}
}
--- PlayLogController.php
<?php
namespace AppBundle\Controller;
use AppBundle\Entity\PlayLog;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;use Symfony\Component\HttpFoundation\Request;
/**
* Playlog controller.
*
* #Route("playlog")
*/
class PlayLogController extends Controller
{
/**
* Lists all playLog entities.
*
* #Route("/", name="playlog_index")
* #Method("GET")
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$playLogs = $em->getRepository('AppBundle:PlayLog')->findAll();
return $this->render('playlog/index.html.twig', array(
'playLogs' => $playLogs,
));
}
/**
* Creates a new playLog entity.
*
* #Route("/{gameId}/new", name="playlog_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request, $gameId)
{
$playlog = new PlayLog();
$form = $this->createForm('AppBundle\Form\PlayLogType', $playlog);
$form->handleRequest($request);
$playlog->setGameId($gameId);
echo $playlog->getGameId()."!";
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($playlog);
$em->flush();
// return $this->redirectToRoute('game_show', array('id' => $gameId));
}
return $this->render('playlog/new.html.twig', array(
'playLog' => $playlog,
'form' => $form->createView(),
));
}
return $this->render('playlog/new.html.twig', array(
'playLog' => $playLog,
'form' => $form->createView(),
));
}
/**
* Finds and displays a playLog entity.
*
* #Route("/{id}", name="playlog_show")
* #Method("GET")
*/
public function showAction(PlayLog $playLog)
{
$deleteForm = $this->createDeleteForm($playLog);
return $this->render('playlog/show.html.twig', array(
'playLog' => $playLog,
'delete_form' => $deleteForm->createView(),
));
}
/**
* Displays a form to edit an existing playLog entity.
*
* #Route("/{id}/edit", name="playlog_edit")
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, PlayLog $playLog)
{
$deleteForm = $this->createDeleteForm($playLog);
$editForm = $this->createForm('AppBundle\Form\PlayLogType', $playLog);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('playlog_edit', array('id' => $playLog->getId()));
}
return $this->render('playlog/edit.html.twig', array(
'playLog' => $playLog,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Deletes a playLog entity.
*
* #Route("/{id}", name="playlog_delete")
* #Method("DELETE")
*/
public function deleteAction(Request $request, PlayLog $playLog)
{
$form = $this->createDeleteForm($playLog);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->remove($playLog);
$em->flush();
}
return $this->redirectToRoute('playlog_index');
}
/**
* Creates a form to delete a playLog entity.
*
* #param PlayLog $playLog The playLog entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm(PlayLog $playLog)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('playlog_delete', array('id' => $playLog->getId())))
->setMethod('DELETE')
->getForm()
;
}
}
--- game/log.html.twig
{% extends 'base.html.twig' %}
{% block content %}
Adding log for {{ game.name }}
{{ form_widget(form.playlogs) }}
<input type="submit" value="Create" class="btn btn-default pull-left" />
{% endblock content %}
--- PlayLogType.php
<?php
namespace AppBundle\Form;
use AppBundle\Entity\PlayLog;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class PlayLogType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('date');
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => PlayLog::class
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_playlog';
}
}
--- GameType.php
<?php
namespace AppBundle\Form;
use AppBundle\Entity\PlayLog;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class GameType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class, [
'attr' => [
'class' => 'form-control',
],
]);
$builder
->add('type', EntityType::class, [
'class' => 'AppBundle:Type',
'choice_label' => function ($type) {
return $type->getName();
},
'multiple' => false,
'expanded' => false,
'attr' => [
'class' => 'form-control',
],
]);
$builder->add('playlogs', CollectionType::class, array(
'entry_type' => PlayLogType::class,
'label' => false
));
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Game'
));
}
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return 'appbundle_game';
}
}
Not sure if this is the answer you looking for..
You can tweek your newAction and his Route annotation in the Playlog controller a bit so that you add the gameId in the route
/**
* Creates a new playLog entity.
*
* #Route("/{gameId}/new", name="playlog_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request, $gameId)
{
$em = $this->getDoctrine()->getManager();
$game = $em->getRepository('AppBundle:Game')->find($gameId);
if(null === $game) {
throw $this->createNotFoundException('The game with id ' . $gameId . ' does not exist.');
}
$playLog = new Playlog();
$playLog->SetGame($game);
$form = $this->createForm('AppBundle\Form\PlayLogType', $playLog);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($playLog);
$em->flush($playLog);
return $this->redirectToRoute('playlog_show', array('id' => $playLog->getId()));
}
return $this->render('playlog/new.html.twig', array(
'playLog' => $playLog,
'form' => $form->createView(),
));
}
I've figured it out, I tried to persist with just an ID ($gameId) but it expected the entire Game object. (1) So I first had to get the actual repository object with the ID and after that I can persist this object:
public function newAction(Request $request, $gameId)
{
$playlog = new PlayLog();
$em = $this->getDoctrine()->getManager();
// (1) Get Game object with given gameId:
$game = $em ->getRepository(Game::class)->find($gameId);
//Set the Game object
$playlog->setGame($game);
$form = $this->createForm('AppBundle\Form\PlayLogType', $playlog);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
/* #var $playLog PlayLog */
$playlog = $form->getData();
$em->persist($playlog);
$em->flush();
}
return $this->render('playlog/new.html.twig', array(
'playLog' => $playlog,
'form' => $form->createView(),
));
}
i'm having trouble with crud and user entity ( playing a little with sf2). i've been following the symfony cookbook for saving users in database and roles and i've generated crud for user entity and role entity. on user entity i have the field for assigning the role yet in the select option it shows the id of the role instead of the name and i'm not sure how modify the field to show the role name. can you help me please ?
User Controller:
namespace UserBundle\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use UserBundle\Entity\User;
use UserBundle\Form\UserType;
/**
* User controller.
*
* #Route("/user")
*/
class UserController extends Controller
{
/**
* Lists all User entities.
*
* #Route("/", name="user")
* #Method("GET")
* #Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('UserBundle:User')->findAll();
return array(
'entities' => $entities,
);
}
/**
* Creates a new User entity.
*
* #Route("/", name="user_create")
* #Method("POST")
* #Template("UserBundle:User:new.html.twig")
*/
public function createAction(Request $request)
{
$entity = new User();
$factory = $this->get('security.encoder_factory');
$form = $this->createCreateForm($entity);
$form->handleRequest($request);
$encoder = $factory->getEncoder($entity);
$password = $encoder->encodePassword($entity->getPassword(), $entity->getSalt());
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('user_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Creates a form to create a User entity.
*
* #param User $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createCreateForm(User $entity)
{
$form = $this->createForm(new UserType(), $entity, array(
'action' => $this->generateUrl('user_create'),
'method' => 'POST',
));
$form->add('submit', 'submit', array('label' => 'Create'));
return $form;
}
/**
* Displays a form to create a new User entity.
*
* #Route("/new", name="user_new")
* #Method("GET")
* #Template()
*/
public function newAction()
{
$entity = new User();
$form = $this->createCreateForm($entity);
return array(
'entity' => $entity,
'form' => $form->createView(),
);
}
/**
* Finds and displays a User entity.
*
* #Route("/{id}", name="user_show")
* #Method("GET")
* #Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('UserBundle:User')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find User entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
);
}
/**
* Displays a form to edit an existing User entity.
*
* #Route("/{id}/edit", name="user_edit")
* #Method("GET")
* #Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('UserBundle:User')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find User entity.');
}
$editForm = $this->createEditForm($entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Creates a form to edit a User entity.
*
* #param User $entity The entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createEditForm(User $entity)
{
$form = $this->createForm(new UserType(), $entity, array(
'action' => $this->generateUrl('user_update', array('id' => $entity->getId())),
'method' => 'PUT',
));
$form->add('submit', 'submit', array('label' => 'Update'));
return $form;
}
/**
* Edits an existing User entity.
*
* #Route("/{id}", name="user_update")
* #Method("PUT")
* #Template("UserBundle:User:edit.html.twig")
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('UserBundle:User')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find User entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
$em->flush();
return $this->redirect($this->generateUrl('user_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a User entity.
*
* #Route("/{id}", name="user_delete")
* #Method("DELETE")
*/
public function deleteAction(Request $request, $id)
{
$form = $this->createDeleteForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('UserBundle:User')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find User entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('user'));
}
/**
* Creates a form to delete a User entity by id.
*
* #param mixed $id The entity id
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('user_delete', array('id' => $id)))
->setMethod('DELETE')
->add('submit', 'submit', array('label' => 'Delete'))
->getForm()
;
}
}
UserType
<?php
namespace UserBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class UserType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username')
->add('password')
->add('email')
->add('isActive')
->add('roles')
;
}
/**
* #param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'UserBundle\Entity\User'
));
}
/**
* #return string
*/
public function getName()
{
return 'userbundle_user';
}
}
UserEntity
<?php
namespace UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\Common\Collections\ArrayCollection;
/**
* UserBundle\Entity\User
*
* #ORM\Table(name="acme_users")
* #ORM\Entity(repositoryClass="UserBundle\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")
*/
private $roles;
public function __construct()
{
$this->isActive = true;
$this->roles = new ArrayCollection();
// may not be needed, see section on salt below
// $this->salt = md5(uniqid(null, true));
}
/**
* #inheritDoc
*/
public function getUsername()
{
return $this->username;
}
/**
* #inheritDoc
*/
public function getSalt()
{
// you *may* need a real salt depending on your encoder
// see section on salt below
return null;
}
/**
* #inheritDoc
*/
public function getPassword()
{
return $this->password;
}
/**
* #inheritDoc
*/
public function getRoles()
{
return $this->roles->toArray();
}
/**
* #inheritDoc
*/
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;
}
/**
* Add roles
*
* #param \UserBundle\Entity\Role $roles
* #return User
*/
public function addRole(\UserBundle\Entity\Role $roles)
{
$this->roles[] = $roles;
return $this;
}
/**
* Remove roles
*
* #param \UserBundle\Entity\Role $roles
*/
public function removeRole(\UserBundle\Entity\Role $roles)
{
$this->roles->removeElement($roles);
}
public function __toString() {
return (string) $this->getId();
}
}
Implement __toString() method in the Role entity class.
public function __toString()
{
return $this->name;
}
You could also pass 'property' => 'name' option to roles field
Read more about other form type options here http://symfony.com/doc/current/reference/forms/types/entity.html
I have these entities: - Store and Package
I'd like to build a StoreType form where i add package Id.
I've made a StoreType Form class: (I would expect to get a select box from this, where all package are listed)
I've add the package through one to one, but my problem is when i add package in store form then form is create but in my database store table column package are empty.i don't know why?
Store.php
/**
* #ORM\Entity
*/
class Store
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length="255")
*/
protected $title;
/**
* #ORM\Column(type="string", length="255")
*/
protected $domain;
/**
* #ORM\OneToOne(targetEntity="Package",cascade={"persist", "remove"})
* #ORM\JoinColumn(name="package_id", referencedColumnName="id")
*/
protected $package;
}
Package.php
/**
* #ORM\Entity
*/
class Package
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=255)
*/
protected $title;
/**
* #ORM\Column(type="text", length="4000")
*/
protected $description;
/**
* #ORM\Column(type="boolean")
*/
protected $active;
public function __toString()
{
return $this->getTitle();
}
}
StoreType.php
class StoreType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('title')
->add('domain')
->add('package','entity',array(
'class' => 'WebmuchProductBundle:Package',
));
}
public function getName()
{
return 'webmuch_productbundle_storetype';
}
}
StoreController.php
/**
* Store controller.
*
* #Route("/store")
*/
class StoreController extends Controller
{
/**
* Lists all Store entities.
*
* #Route("/", name="store")
* #Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getEntityManager();
$entities = $em->getRepository('WebmuchProductBundle:Store')->findAll();
return array('entities' => $entities);
}
/**
* Finds and displays a Store entity.
*
* #Route("/{id}/show", name="store_show")
* #Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('WebmuchProductBundle:Store')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Store entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(), );
}
/**
* Displays a form to create a new Store entity.
*
* #Route("/new", name="store_new")
* #Template()
*/
public function newAction()
{
$store = new Store();
$form = $this->createForm(new StoreType(), $store);
return array(
'entity' => $store,
'form' => $form->createView()
);
}
/**
* Creates a new Store entity.
*
* #Route("/create", name="store_create")
* #Method("post")
* #Template("WebmuchProductBundle:Store:new.html.twig")
*/
public function createAction()
{
$entity = new Store();
$request = $this->getRequest();
$form = $this->createForm(new StoreType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('store_show', array('id' => $entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView()
);
}
/**
* Displays a form to edit an existing Store entity.
*
* #Route("/{id}/edit", name="store_edit")
* #Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('WebmuchProductBundle:Store')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Store entity.');
}
$editForm = $this->createForm(new StoreType(), $entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Edits an existing Store entity.
*
* #Route("/{id}/update", name="store_update")
* #Method("post")
* #Template("WebmuchProductBundle:Store:edit.html.twig")
*/
public function updateAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('WebmuchProductBundle:Store')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Store entity.');
}
$editForm = $this->createForm(new StoreType(), $entity);
$deleteForm = $this->createDeleteForm($id);
$request = $this->getRequest();
$editForm->bindRequest($request);
if ($editForm->isValid()) {
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('store_edit', array('id' => $id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a Store entity.
*
* #Route("/{id}/delete", name="store_delete")
* #Method("post")
*/
public function deleteAction($id)
{
$form = $this->createDeleteForm($id);
$request = $this->getRequest();
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('WebmuchProductBundle:Store')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Store entity.');
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('store'));
}
private function createDeleteForm($id)
{
return $this->createFormBuilder(array('id' => $id))
->add('id', 'hidden')
->getForm()
;
}
}
I think you forget to do this in your createAction :
$request = $this->getRequest();
$form->setData($request->getPost());