One-To-One, Unidirectional Relationship - symfony

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());

Related

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null

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.

Symfony Howto create a entity and add it to another?

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(),
));
}

Notice: Undefined index: roles in Symfony 2.7

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.

symfony2 crud user entity, role assign

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

Symfony2: Show IP as string and save IP as INT

I have an Entity in Symfony called Ip and I save my IP address as integer - I use the IP as primary key, too.
But when I display and enter the IP in a form or list I want to convert it to a IP, e.g. 127.0.0.1 is saved as 2130706433.
I created the forms with the CRUD generator.
My entity comes here:
<?php
namespace IS\ClearanceBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* IS\ClearanceBundle\Entity\Ip
*/
class Ip
{
/**
* #var bigint $ip
*/
private $ip;
/**
* #var integer $high
*/
private $high;
/**
* #var string $hoster
*/
private $hoster;
/**
* #var datetime $scandate
*/
private $scandate;
/**
* #var integer $id
*/
private $id;
/**
* #var IS\ClearanceBundle\Entity\Clearance
*/
private $clearance;
public function __construct()
{
$this->clearance = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Set ip
*
* #param bigint $ip
*/
public function setIp($ip)
{
$this->ip = $ip;
}
/**
* Get ip
*
* #return bigint
*/
public function getIp()
{
return $this->ip;
}
/**
* Set high
*
* #param integer $high
*/
public function setHigh($high)
{
$this->high = $high;
}
/**
* Get high
*
* #return integer
*/
public function getHigh()
{
return $this->high;
}
/**
* Set hoster
*
* #param string $hoster
*/
public function setHoster($hoster)
{
$this->hoster = $hoster;
}
/**
* Get hoster
*
* #return string
*/
public function getHoster()
{
return $this->hoster;
}
/**
* Set scandate
*
* #param datetime $scandate
*/
public function setScandate($scandate)
{
$this->scandate = $scandate;
}
/**
* Get scandate
*
* #return datetime
*/
public function getScandate()
{
return $this->scandate;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Add clearance
*
* #param IS\ClearanceBundle\Entity\Clearance $clearance
*/
public function addClearance(\IS\ClearanceBundle\Entity\Clearance $clearance)
{
$this->clearance[] = $clearance;
}
/**
* Get clearance
*
* #return Doctrine\Common\Collections\Collection
*/
public function getClearance()
{
return $this->clearance;
}
}
And here is my Controller:
<?php
namespace IS\ClearanceBundle\Controller;
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 IS\ClearanceBundle\Entity\Ip;
use IS\ClearanceBundle\Form\IpType;
/**
* Ip controller.
*
* #Route("/ip")
*/
class IpController extends Controller
{
/**
* Lists all Ip entities.
*
* #Route("/", name="ip")
* #Template()
*/
public function indexAction()
{
$em = $this->getDoctrine()->getEntityManager();
$entities = $em->getRepository('ISClearanceBundle:Ip')->findAll();
return array('entities' => $entities);
}
/**
* Finds and displays a Ip entity.
*
* #Route("/{id}/show", name="ip_show")
* #Template()
*/
public function showAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('ISClearanceBundle:Ip')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Ip entity.');
}
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'delete_form' => $deleteForm->createView(), );
}
/**
* Displays a form to create a new Ip entity.
*
* #Route("/new", name="ip_new")
* #Template()
*/
public function newAction()
{
$entity = new Ip();
$form = $this->createForm(new IpType(), $entity);
return array(
'entity' => $entity,
'form' => $form->createView()
);
}
/**
* Creates a new Ip entity.
*
* #Route("/create", name="ip_create")
* #Method("post")
* #Template("ISClearanceBundle:Ip:new.html.twig")
*/
public function createAction()
{
$entity = new Ip();
$request = $this->getRequest();
$form = $this->createForm(new IpType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getEntityManager();
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('ip_show', array('id' => $ entity->getId())));
}
return array(
'entity' => $entity,
'form' => $form->createView()
);
}
/**
* Displays a form to edit an existing Ip entity.
*
* #Route("/{id}/edit", name="ip_edit")
* #Template()
*/
public function editAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('ISClearanceBundle:Ip')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Ip entity.');
}
$editForm = $this->createForm(new IpType(), $entity);
$deleteForm = $this->createDeleteForm($id);
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Edits an existing Ip entity.
*
* #Route("/{id}/update", name="ip_update")
* #Method("post")
* #Template("ISClearanceBundle:Ip:edit.html.twig")
*/
public function updateAction($id)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('ISClearanceBundle:Ip')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Ip entity.');
}
$editForm = $this->createForm(new IpType(), $entity);
$deleteForm = $this->createDeleteForm($id);
$request = $this->getRequest();
$editForm->bindRequest($request);
if ($editForm->isValid()) {
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('ip_edit', array('id' => $ id)));
}
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
/**
* Deletes a Ip entity.
*
* #Route("/{id}/delete", name="ip_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('ISClearanceBundle:Ip')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Ip entity.' );
}
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('ip'));
}
private function createDeleteForm($id)
{
return $this->createFormBuilder(array('id' => $id))
->add('id', 'hidden')
->getForm()
;
}
}
And here the form:
<?php
namespace IS\ClearanceBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class IpType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('ip')
->add('high')
->add('hoster')
->add('scandate')
->add('clearance','entity', array('class'=>'IS\ClearanceBundle\Entity\Clearance', 'property'=>'id','required'=>false, 'multiple'=>true))
;
}
public function getName()
{
return 'is_clearancebundle_iptype';
}
}
Thanks for any help!
IMO if you want do it, you should use data transformer http://symfony.com/doc/current/cookbook/form/data_transformers.html and implement __toString for your entity IP.
EDIT:
Created sample at gist: https://gist.github.com/3086241

Resources