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.
Related
With Symfony, I have a radio form from entity :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('color', EntityType::class, [
'class' => Color::class,
'expanded' => true,
'label_attr' => [
'class' => 'radio-inline'
],
'label' => 'label.color',
....
But when I dump() in radio_widget, I don't have entity :
array:28 [▼
"value" => "1"
"attr" => []
"form" => FormView {#975 ▶}
"id" => "news_category_versions_0_color_1"
"name" => "1"
"full_name" => "news_category[versions][0][color]"
"disabled" => false
"label" => "Blue"
"label_format" => null
"multipart" => false
"block_prefixes" => array:4 [▶]
"unique_block_prefix" => "_news_category_versions_entry_color_entry"
"translation_domain" => false
"cache_key" => "_news_category_versions_entry_color_entry_radio"
"errors" => FormErrorIterator {#1186 ▶}
"valid" => true
"data" => false
"required" => true
"size" => null
"label_attr" => []
"compound" => false
"method" => "POST"
"action" => ""
"submitted" => false
"help_translation_domain" => null
"checked" => false
"parent_label_class" => "radio-inline"
"app" => AppVariable {#1216 ▶}
]
Can I get entity in radio_widget for customize it ? Each radio have a specific color in entity (blue, red, green, etc.).
Yes it is possible:
App\Entity\Color:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Class Color
*
* #package AppBundle\Entity
*
* #ORM\Table()
* #ORM\HasLifecycleCallbacks()
* #ORM\Entity(repositoryClass="AppBundle\Entity\ColorRepository")
*/
class Color
{
/**
* #var int $id
* #ORM\Id()
* #ORM\Column()
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var string $name
* #ORM\Column(type="string", length=255)
*/
protected $name;
/**
* #ORM\OneToMany(targetEntity="ColorProduct", mappedBy="color", cascade={"all"})
*/
protected $product;
/**
* Constructor
*/
public function __construct()
{
$this->product = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return string
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* #param string $name
*
* #return Color
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Add product
*
* #param \AppBundle\Entity\ColorProduct $product
*
* #return Color
*/
public function addProduct(\AppBundle\Entity\ColorProduct $product)
{
$this->product[] = $product;
return $this;
}
/**
* Remove product
*
* #param \AppBundle\Entity\ColorProduct $product
*/
public function removeProduct(\AppBundle\Entity\ColorProduct $product)
{
$this->product->removeElement($product);
}
/**
* Get product
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getProduct()
{
return $this->product;
}
}
A relation with the color entity in ColorProductEntity
namespace AppBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table()
* #ORM\HasLifecycleCallbacks()
* #ORM\Entity(repositoryClass="AppBundle\Entity\ColorRepository")
*
*/
class ColorProduct
{
/**
* #var int $id
* #ORM\Id()
* #ORM\Column()
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\ManyToOne(targetEntity="Color", inversedBy="product")
* #ORM\JoinColumn(name="color_id", referencedColumnName="id")
*/
protected $color;
/**
* Get id
*
* #return string
*/
public function getId()
{
return $this->id;
}
/**
* Set color
*
* #param \AppBundle\Entity\Color $color
*
* #return ColorProduct
*/
public function setColor(\AppBundle\Entity\Color $color = null)
{
$this->color = $color;
return $this;
}
/**
* Get color
*
* #return \AppBundle\Entity\Color
*/
public function getColor()
{
return $this->color;
}
}
The formType for colorProduct:
namespace AppBundle\Form;
use AppBundle\Entity\Color;
use AppBundle\Entity\ColorProduct;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ColorProductType extends AbstractType
{
public function buildForm( FormBuilderInterface $builder, array $options )
{
$builder->add('color', EntityType::class, array(
'class' => Color::class,
'choice_label' => 'name',
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('c');
},
'expanded' => true,
'required' => true,
));
}
public function configureOptions( OptionsResolver $resolver )
{
$resolver->setDefaults(array(
'data_class' => ColorProduct::class
)
);
}
}
In controller:
/**
* #Route("/product/color", name="product_color")
* #param \Symfony\Component\HttpFoundation\Request $request
*
* #return \Symfony\Component\HttpFoundation\Response
*/
public function addColorProduct(Request $request) {
$colorType = new ColorProduct();
$form = $this->createForm(ColorProductType::class, $colorType);
$form->handleRequest($request);
if ($form->isSubmitted()) {
//.........
}
return $this->render('AppBundle:product:color.html.twig', array('form' => $form->createView()));
}
Twig template:
<h1>Color product</h1>
{{ form_start(form) }}
{{ form_row(form.color) }}
{{ form_end(form) }}
The result:
i'm newbie in symfony and I'm trying to implement a Data Transformer. I followed the documentation and looked different solutions posted in here. But I haven't found what is wrong with my code.
I'm getting this error:
Catchable Fatal Error: Object of class AppBundle\Entity\Todo could not be converted to string
If someone knows another post with the solution, please tell me know where I could look for it.
Thank you in advance.
So, these are my Entities. Todo class
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Todo
*
* #ORM\Table(name="todo")
* #ORM\Entity(repositoryClass="AppBundle\Repository\TodoRepository")
*/
class Todo
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=20)
*/
private $name;
/**
* #var string
*
* #ORM\Column(name="category", type="string", length=20)
*/
private $category;
/**
* #var string
*
* #ORM\Column(name="description", type="string", length=10)
*/
private $description;
/**
* #var string
*
* #ORM\Column(name="priority", type="string", length=10)
*/
private $priority;
/**
*
* #ORM\ManyToOne(
* targetEntity="AppBundle\Entity\User",
* inversedBy="todos"
* )
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
private $creatorId;
//... getters and setters
User class:
<?php
// src/AppBundle/Entity/User.php
namespace AppBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct()
{
parent::__construct();
// your own logic
}
/**
* #ORM\OneToMany(
* targetEntity="AppBundle\Entity\Todo",
* mappedBy="creatorId"
* )
*/
private $todos;
}
In the User class, I don't have getter/setters
My TodoType
class TodoType extends AbstractType{
private $manager;
public function __construct(ObjectManager $manager)
{
$this->manager = $manager;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class, array(
'label' => 'Name',
'required' => true
)
)
->add('category', TextType::class, array(
'label' => 'Category'
)
)
->add('priority', EntityType::class, array(
'class' => 'AppBundle:Todo',
'choice_label' => 'priority',
)
)
->add('creatorId', TextType::class, array(
'label' => 'creator Id:',
));
$builder->get('creatorId')
->addModelTransformer(new IssueToNumberTransformer($this->manager));
}
public function getName()
{
return 'todo';
}
}
Transformer
<?php
namespace FOS\UserBundle\Form\DataTransformer;
use AppBundle\Entity\User;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\Form\DataTransformerInterface;
use Symfony\Component\Form\Exception\TransformationFailedException;
class IssueToNumberTransformer implements DataTransformerInterface
{
private $manager;
public function __construct(ObjectManager $manager)
{
$this->manager = $manager;
}
/**
* Transforms an object (creatorId) to a string (number).
*
* #param creatorId|null $creatorId
* #return string
*/
public function transform($creatorId)
{
if (null === $creatorId) {
return '';
}
return $creatorId->getId();
}
/**
* Transforms a string (number) to an object (creatorId).
*
* #param string $creatorId
* #return creatorId|null
* #throws TransformationFailedException if object (creatorId) is not found.
*/
public function reverseTransform($creatorId)
{
// no issue number? It's optional, so that's ok
if (!$creatorId) {
return;
}
$creatorId = $this->manager
->getRepository('AppBundle:User')
// query for the issue with this id
->find($creatorId);
if (null === $creatorId) {
throw new TransformationFailedException(sprintf(
'A user with number "%s" does not exist!',
$creatorId
));
}
return $creatorId;
}
}
Controller (function)
public function createAction(Request $request){
$em = $this->getDoctrine()->getManager();
// 1) build the form
$todo = new Todo();
$form = $this->createForm(new TodoType($em), $todo);
// 2) handle the submit (will only happen on POST)
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
// 3) save the Todo!
$em->persist($todo);
$em->flush();
return $this->redirectToRoute('todo_create');
}
return $this->render('todo/create.html.twig', array(
'todo'=>$todo,
'form'=>$form->createView()
));
}
It's at this part:
return $this->render('todo/create.html.twig', array(
'todo'=>$todo,
'form'=>$form->createView()
));
Because you are trying to pass the $todo object to your Twig template. You can't do that. What do you need? If you just need the Todo name and you have created getters/setter, you could instead do like this:
return $this->render('todo/create.html.twig', array(
'todo_name' => $todo->getName(),
'form' => $form->createView()
));
Hopefully that makes sense.
EDIT #2 based on comments.
Also this line is wrong in your controller:
$form = $this->createForm(new TodoType($em), $todo);
Should be like this:
$form = $this->createForm(TodoType::class, $todo);
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 don´t know how to preview a small image in my listmapper in admin class of an entity. I only see a link to the edit form of the picture, but I want to see a thumbnail of the picture.
This is my entity:
<?php
namespace ExampleBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Translatable\Translatable;
use Application\Sonata\MediaBundle\Entity\Media;
/**
* example
*
* #ORM\Table()
* #ORM\Entity
*/
class example
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
* #var \Application\Sonata\MediaBundle\Entity\Media
* #ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media", cascade={"persist"}, fetch="LAZY")
*/
private $imagenEs;
/**
* #var string
* #var \Application\Sonata\MediaBundle\Entity\Media
* #ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media", cascade={"persist"}, fetch="LAZY")
*/
private $imagenEn;
/**
* #var string
* #Gedmo\Translatable
* #ORM\Column(name="titulo", type="string", length=255)
*/
private $titulo;
/**
* #var string
*/
private $tituloEn;
/**
* #var string
* #Gedmo\Translatable
* #ORM\Column(name="texto", type="text")
*/
private $texto;
/**
* #var string
*/
private $textoEn;
/**
* #var boolean
*
* #ORM\Column(name="activo", type="boolean")
*/
private $activo;
/**
* #var integer
*
* #ORM\Column(name="ranking", type="integer")
*/
private $ranking;
/**
* #var string
* #Gedmo\Locale
*/
private $locale;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set imagen
*
* #param string $imagen
* #return BannerHome
*/
public function setImagenEs(Media $imagenEs)
{
$this->imagenEs = $imagenEs;
return $this;
}
/**
* Get imagen
*
* #return string
*/
public function getImagenEs()
{
return $this->imagenEs;
}
/**
* Set imagen
*
* #param string $imagen
* #return BannerHome
*/
public function setImagenEn(Media $imagenEn)
{
$this->imagenEn = $imagenEn;
return $this;
}
/**
* Get imagen
*
* #return string
*/
public function getImagenEn()
{
return $this->imagenEn;
}
/**
* Set titulo
*
* #param string $titulo
* #return BannerHome
*/
public function setTitulo($titulo)
{
$this->titulo = $titulo;
return $this;
}
/**
* Get titulo
*
* #return string
*/
public function getTitulo()
{
return $this->titulo;
}
/**
* Set titulo
*
* #param string $titulo
* #return BannerHome
*/
public function setTituloEn($tituloEn)
{
$this->tituloEn = $tituloEn;
return $this;
}
/**
* Get titulo
*
* #return string
*/
public function getTituloEn()
{
return $this->tituloEn;
}
/**
* Set texto
*
* #param string $texto
* #return BannerHome
*/
public function setTexto($texto)
{
$this->texto = $texto;
return $this;
}
/**
* Get texto
*
* #return string
*/
public function getTexto()
{
return $this->texto;
}
/**
* Set texto
*
* #param string $texto
* #return BannerHome
*/
public function setTextoEn($textoEn)
{
$this->textoEn = $textoEn;
return $this;
}
/**
* Get texto
*
* #return string
*/
public function getTextoEn()
{
return $this->textoEn;
}
/**
* Set activoBoolean
*
* #param string $activoBoolean
* #return BannerHome
*/
public function setActivo($activo)
{
$this->activo = $activo;
return $this;
}
/**
* Get activoBoolean
*
* #return string
*/
public function getActivo()
{
return $this->activo;
}
/**
* Set ranking
*
* #param integer $ranking
* #return BannerHome
*/
public function setRanking($ranking)
{
$this->ranking = $ranking;
return $this;
}
/**
* Get ranking
*
* #return integer
*/
public function getRanking()
{
return $this->ranking;
}
public function setTranslatableLocale($locale) {
$this->locale = $locale;
}
}?>
And this is my admin class
<?php
namespace ExampleBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Show\ShowMapper;
class PibeAdmin extends Admin
{
/**
* #param DatagridMapper $datagridMapper
*/
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
->add('id')
->add('titulo')
->add('texto')
->add('activo')
->add('ranking')
;
}
/**
* #param ListMapper $listMapper
*/
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->add('id')
->add('titulo')
->add('imagenEs') /*With this I see a link to the image, and if I click this link I saw the edit form of the image, but I want a thumbnail*/
->add('activo')
->add('ranking')
->add('_action', 'actions', array(
'actions' => array(
'show' => array(),
'edit' => array(),
'delete' => array(),
)
))
;
}
/**
* #param FormMapper $formMapper
*/
protected function configureFormFields(FormMapper $formMapper)
{
$idioma=$this->getRequest()->getLocale();
if($idioma=='es'){
$formMapper
->add('imagenEs', 'sonata_type_model_list', array(
'required' => false,
'label'=>'Imagen Español'
), array(
'link_parameters' => array(
'context' => 'default',
'provider' => 'sonata.media.provider.image'
)
)
)
->add('imagenEn', 'sonata_type_model_list', array(
'required' => false,
'label'=>'Imagen Ingles',
), array(
'link_parameters' => array(
'context' => 'default',
'provider' => 'sonata.media.provider.image'
)
)
)
->add('titulo',null,array('label'=>'Titulo Español'))
->add('tituloEn','text',array('label'=>'Titulo Ingles','data'=>''))
->add('texto','textarea', array('attr' => array('class' => 'ckeditor'),'label'=>'Texto Español'))
->add('textoEn','textarea', array('attr' => array('class' => 'ckeditor'),'label'=>'Texto Ingles','data'=>''))
;
}else{
$formMapper
->add('imagenEn', 'sonata_type_model_list', array(
'required' => false,
'label'=>'Imagen Ingles'
), array(
'link_parameters' => array(
'context' => 'default',
'provider' => 'sonata.media.provider.image'
)
)
)
->add('imagenEs', 'sonata_type_model_list', array(
'required' => false,
'label'=>'Imagen Español'
), array(
'link_parameters' => array(
'context' => 'default',
'provider' => 'sonata.media.provider.image'
)
)
)
->add('tituloEn','text',array('label'=>'Titulo Ingles','data'=>''))
->add('titulo',null,array('label'=>'Titulo Español'))
->add('textoEn','textarea', array('attr' => array('class' => 'ckeditor'),'label'=>'Texto Ingles','data'=>''))
->add('texto','textarea', array('attr' => array('class' => 'ckeditor'),'label'=>'Texto Español'))
;
}
$formMapper
->add('activo')
->add('ranking')
;
$container = $this->getConfigurationPool()->getContainer();
$em = $container->get('doctrine.orm.entity_manager');
if($idioma=='es' && $this->getSubject()->getId()!=null){
//$titoriginal=$em->getRepository('HomeBundle:ImagenesHome')->find($this->getSubject()->getId());
// $titoriginal->setTranslatableLocale('en');
//$em->refresh($titoriginal);
//buscamos su traduccion en la tabal de traducciones.
$repository = $em->getRepository('Gedmo\Translatable\Entity\Translation');
$translations = $repository->findTranslations($this->getSubject());
//rellenamos el campo con la traduccion.
if(count($translations)>0){
$formMapper->get('tituloEn')->setData($translations['en']['titulo']);
$formMapper->get('textoEn')->setData($translations['en']['texto']);
};
}else if($idioma=='en' && $this->getSubject()->getId()!=null){
$titoriginal=$em->getRepository('PibeBundle:Pibe')->find($this->getSubject()->getId());
//cambiamos el locale a 'es' para coger el texto en español
$titoriginal->setTranslatableLocale('en');
$em->refresh($titoriginal);
//una vez que lo cogemos, volvemos a cambiar el locale a 'en'
$formMapper->get('tituloEn')->setData($titoriginal->getTitulo());
$formMapper->get('textoEn')->setData($titoriginal->getTexto());
$titoriginal->setTranslatableLocale('es');
$em->refresh($titoriginal);
}
}
/**
* #param ShowMapper $showMapper
*/
protected function configureShowFields(ShowMapper $showMapper)
{
$showMapper
->add('id')
->add('titulo')
->add('texto')
->add('activo')
->add('ranking')
;
}
public function prePersist($object) {
$container = $this->getConfigurationPool()->getContainer();
$entityManager = $container->get('doctrine.orm.entity_manager');
//insertar en español.
$object->setTitulo($object->getTitulo());
$object->setTexto($object->getTexto());
$object->setTranslatableLocale('es');
$entityManager->persist($object);
$entityManager->flush();
//insertar en ingles.
$object->setTitulo($object->getTituloEn());
$object->setTexto($object->getTextoEn());
$object->setTranslatableLocale('en');
$entityManager->persist($object);
$entityManager->flush();
}
public function preUpdate($object) {
$container = $this->getConfigurationPool()->getContainer();
$entityManager = $container->get('doctrine.orm.entity_manager');
//insertar en español.
$object->setTitulo($object->getTitulo());
$object->setTexto($object->getTexto());
$object->setTranslatableLocale('es');
$entityManager->persist($object);
$entityManager->flush();
//insertar en ingles.
$object->setTitulo($object->getTituloEn());
$object->setTexto($object->getTextoEn());
$object->setTranslatableLocale('en');
$entityManager->persist($object);
$entityManager->flush();
}
}
Where it says "Imagen Es" I want the thumbnail of the image.
$listMapper
->add('thumb', null, array(
'template' => "ExampleBundle:Pibe:list_thumb.html.twig")
)
On list_thumb.html.twig
{% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %}
{% block field %}
{# {{ dump() }} you can dump all variables here #}
{# {{ value }} will return the value of getImagenEs() #}
<img class="img-responsive" alt="{{ object.name }}" src="{{ asset('path/to/uploadfolder/' ~ object.filepath) }}" /> {# or you can use a twig filter with your own logic #}
{% endblock field %}
I believe this is a more up 2 date answer :
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('title')
->add('image', 'string', ['template' => 'SonataMediaBundle:MediaAdmin:list_image.html.twig'])
->add('updatedAt')
->add('_action', null, ['actions' =>
[
'edit' => [],
'delete' => []
], 'label' => 'Actions']);
}
I'm trying to build the "edit" controller/view but i encounter this error. From i've read it could be an asociation problem, and i've tried to fix it but i don't know what it's wrong with it. It supposed to return a collection but i don't even know what "proxy" means and how it's getting it.
The entity for which i'm building the edit view:
<?php
namespace Monse\WebBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Monse\WebBundle\Entity\BasedeDatos
*
* #ORM\Table()
* #ORM\Entity
*/
class BasedeDatos
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Monse\WebBundle\Entity\ServidoresBD")
* #ORM\JoinColumn(name="servidores_id", referencedColumnName="id",nullable=false)
*
*/
private $servidorBD;
/**
* #var string $nombreBD
*
* #ORM\Column(name="nombreBD", type="string", length=255,unique=true)
*/
private $nombreBD;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set servidorBD
*
* #param integer $servidorBD
*/
public function setServidorBD(\Monse\WebBundle\Entity\ServidoresBD $servidorBD)
{
$this->servidorBD = $servidorBD;
}
/**
* Get servidorBD
*
* #return integer
*/
public function getServidorBD()
{
return $this->servidorBD;
}
/**
* Set nombreBD
*
* #param string $nombreBD
*/
public function setNombreBD($nombreBD)
{
$this->nombreBD = $nombreBD;
}
/**
* Get nombreBD
*
* #return string
*/
public function getNombreBD()
{
return $this->nombreBD;
}
public function __construct()
{
$this->servidorBD = new Doctrine\Common\Collections\ArrayCollection();
}
}
FormType:
<?php
namespace Monse\WebBundle\Form;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class BasedeDatosType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('ServidorBD','entity',
array ('class' => 'MonseWebBundle:ServidoresBD',
'multiple' => true,
'required' => true,
'label' => 'Servidor de Base de Datos: ',
'query_builder' => function(EntityRepository $er) {
return $er->createQueryBuilder('u')
->orderBy('u.url', 'ASC');
},
))
->add('nombreBD','text', array( 'required' => true, 'label' => 'Nombre Base de Datos: '))
->add('UsuarioBD','entity',array('class' => 'MonseWebBundle:UsuariosBD','multiple' => true,
'required' => true, 'label' => 'Usuario Asociado: ',
'property_path' => false,
'query_builder' => function (EntityRepository $er){
return $er->createQueryBuilder('s')
->orderBy ('s.usuario','ASC'); },))
;
}
public function getName()
{
return 'basededatos';
}
}
The entity responsible for the problem (i think):
<?php
namespace Monse\WebBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Monse\WebBundle\Entity\ServidoresBD
*
* #ORM\Table()
* #ORM\Entity
*/
class ServidoresBD
{
/**
* #var integer $id
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string $url
*
* #ORM\Column(name="url", type="string", length=255)
*/
private $url;
/**
*
* #ORM\OneToOne (targetEntity="Monse\WebBundle\Entity\Dominios")
* #ORM\JoinColumn(name="dominio_id", referencedColumnName="id",nullable=false,unique=true)
*/
private $dominio;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set dominio
*
* #param integer $dominio
*/
public function setDominio(\Monse\WebBundle\Entity\Dominios $dominio)
{
$this->dominio = $dominio;
}
/**
* Get dominio
*
* #return integer
*/
public function getDominio()
{
return $this->dominio;
}
/**
* Set url
*
* #param string $url
*/
public function setUrl($url)
{
$this->url = $url;
}
/**
* Get url
*
* #return string
*/
public function getUrl()
{
return $this->url;
}
public function __toString()
{
return $this->getUrl();
}
}
Form Type:
<?php
namespace Monse\WebBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;
class ServidoresBDType extends AbstractType
{
public function buildForm(FormBuilder $builder, array $options)
{
$builder
->add('url')
->add('dominio', 'collection', array('type' => new DominiosType()));
;
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'Monse\WebBundle\Entity\ServidoresBD'
);
}
public function getName()
{
return 'issue_selector';
}
}
Where should i add the arraycollection to be returned? How do i prevent this from happening again? I'm sorry if this is an stupid question, i'm trying to learn.
I changed the two "multiple" attributes to false in the first form type.