I have this error when trying to use d:f:l on Smyony2, i got the same error for Servicio and Usuario, so I post one example and if you help me, the other one will be fixed too.
[ErrorException]
Catchable Fatal Error: Argument 1 passed to PGE\BitacoraBundle\Entity\Tarea::setServicio() must be an instance of PGE\BitacoraBundle\Entity\Servicio, integer given, called in D:\Zend\Apache2\htdocs\PGE\src\PGE\BitacoraBu
ndle\DataFixtures\ORM\Tareas.php on line 20 and defined in D:\Zend\Apache2\htdocs\PGE\src\PGE\BitacoraBundle\Entity\Tarea.php line 281
This is the code:
Tareas.php
<?php
namespace PGE\BitacoraBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use PGE\BitacoraBundle\Entity\Tarea;
class Tareas extends AbstractFixture implements OrderedFixtureInterface
{
public function getOrder()
{
return 3;
}
public function load(ObjectManager $manager)
{
for ($i = 1; $i < 5; $i++) {
$entidad = new Tarea();
$entidad->setServicio($i);
$entidad->setFechaInicio(new \DateTime());
$entidad->setFechaFinal(new \DateTime());
$entidad->setDescripcion('Descripcion aqui');
$entidad->setEstado('Pendiente');
$entidad->setPrioridad('P1');
$entidad->setResumen('Hola soy un resumen');
$entidad->setSolicitante('x068753');
$entidad->setUsuario($i);
}
$manager->flush();
}
}
Usuario.php
<?php
namespace PGE\BitacoraBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="bitacora_usuario")
*/
class Usuario
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue
*/
private $id;
/** #ORM\Column(type="string", length=255) */
private $nombre;
/** #ORM\Column(type="string", length=255) */
private $apellidos;
/** #ORM\Column(type="string", length=255) */
private $prbes;
public function __toString()
{
return $this->getNombre().' '.$this->getApellidos();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nombre
*
* #param string $nombre
* #return Usuario
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
*
* #return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Set apellidos
*
* #param string $apellidos
* #return Usuario
*/
public function setApellidos($apellidos)
{
$this->apellidos = $apellidos;
return $this;
}
/**
* Get apellidos
*
* #return string
*/
public function getApellidos()
{
return $this->apellidos;
}
/**
* Set prbes
*
* #param string $prbes
* #return Usuario
*/
public function setPrbes($prbes)
{
$this->prbes = $prbes;
return $this;
}
/**
* Get prbes
*
* #return string
*/
public function getPrbes()
{
return $this->prbes;
}
}
EDIT: I'm using Symfony 2.1.X
There is no problem with the bundle, instead it says very clearly that the first argument passed to $entidad->setServicio($i); must be an instance of PGE\BitacoraBundle\Entity\Servicio and not an integer.
So you have ot get an instance of Serivcio and pass this to the setter. If you create the servicio inside another fixture, you need to look into the sharing objects between fixtures section of the bundle documentation.
Related
I use Symfony doctrine to set and get data from my MySQL database. I can push new data without any problem but when I try to get them with a findAll for exemple, I get an array with the good length but nothing in.
Here's my controller:
namespace KGN\CoreBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\EntityManagerInterface;
use KGN\CoreBundle\Entity\Appointment;
use KGN\CoreBundle\Entity\Testy;
class AdminController extends Controller
{
public function indexAction()
{
return $this->render('KGNCoreBundle:Admin:index.html.twig');
}
public function aptAction()
{
$rep = $this->getDoctrine()
->getRepository('KGNCoreBundle:Testy');
$testy = $rep->findAll();
// return new Response('This is for show : '. count($testy) );
return new JsonResponse($testy);
}
public function createAction()
{
$em = $this->getDoctrine()->getManager();
$testy = new Testy();
$testy->setTitre('Magnifique');
$testy->setName('Helicoptere');
$em->persist($testy);
$em->flush();
return new Response('This is for create');
}
}
and what I get on my view page
[{},{}]
And it's true that there is 2 elements in my SQL table.
( I have create my entity with php bin/console doctrine:generate:entity without edition stuff in the "Testy" class or rep )
Entity/Testy
namespace KGN\CoreBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Testy
*
* #ORM\Table(name="testy")
* #ORM\Entity(repositoryClass="KGN\CoreBundle\Repository\TestyRepository")
*/
class Testy
{
/**
* #var int
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="titre", type="string", length=255)
*/
private $titre;
/**
* #var string
*
* #ORM\Column(name="name", type="string", length=255)
*/
private $name;
/**
* Get id
*
* #return int
*/
public function getId()
{
return $this->id;
}
/**
* Set titre
*
* #param string $titre
*
* #return Testy
*/
public function setTitre($titre)
{
$this->titre = $titre;
return $this;
}
/**
* Get titre
*
* #return string
*/
public function getTitre()
{
return $this->titre;
}
/**
* Set name
*
* #param string $name
*
* #return Testy
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
}
associed rep
namespace KGN\CoreBundle\Repository;
/**
* TestyRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class TestyRepository extends \Doctrine\ORM\EntityRepository
{
}
Hi The Function findAll Return the correct answer but its return as array of Objects
And JsonResponse can't desplay Object.
to fixe that you have to create a custom function in your repository that return An array exemple
public function getAll() {
$qb = $this->createQueryBuilder('u');
return $qb->getQuery()->getArrayResult();
}
$em = $this->getDoctrine()->getManager();
$records = $em->getRepository("KGNCoreBundle:Testy")->findAll();
Hope its help you
I use symfony2.4 and KNP doctrine behaviors translatable.
I have entity Site (for ID, host, enabled) and entity SiteTranslation (for translated fields: name, descriptions, …).
I use query to get results
$qb = $this->createQueryBuilder('s')
->addSelect('translation') // to eager fetch translations (optional)
->leftJoin('s.translations', 'translation') // or innerJoin ?
->orderBy('s.root', 'ASC')
->addOrderBy('s.lft', 'ASC');
I would like to print result in Twig. For ID, host and enabled fields from Site entity it's easy:
{{ item.id }}
But I can't print translated fields (name, description, …)
{{ item.name }}
It doesn't work.
Error message:
ContextErrorException: Warning: call_user_func_array() expects parameter 1 to be a valid >callback, class 'Net\ConBundle\Entity\SiteTranslation' does not have a method 'name' in >D:\Users...\vendor\knplabs\doctrine->behaviors\src\Knp\DoctrineBehaviors\Model\Translatable\TranslatableMethods.php line 140
Getters and setters for translatable fields are in SiteTranslation entity.
UPDATE:
I still didn't find a solution for an error.
Here is Site entity:
<?php
namespace Pnet\ConlocoBundle\Entity;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;
/**
* #UniqueEntity("host", message="site.host.unique", groups={"edit"})
* #Gedmo\Tree(type="nested")
* #ORM\Entity(repositoryClass="Pnet\ConlocoBundle\Entity\Repository\SiteRepository")
* #ORM\Table(name="site")
*/
class Site
{
use ORMBehaviors\Translatable\Translatable; // knp translatable strategy
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=40, unique=true)
* #Assert\NotBlank(message="site.host.notBlank", groups={"edit"})
* #Assert\Length(max = "40", maxMessage = "site.host.maxLength", groups={"edit"})
*/
protected $host;
/**
* #ORM\Column(type="string", length=255, nullable=true)
* #Assert\Image()
*/
protected $image;
/**
* #ORM\Column(type="boolean")
* #Assert\Choice(choices = {"1", "0"}, message = "site.isDefault.choice", groups={"edit"})
*/
protected $isDefault;
/**
* #ORM\Column(type="boolean")
* #Assert\Choice(choices = {"1", "0"}, message = "site.enabled.choice", groups={"edit"})
*/
protected $enabled;
/**
* #ORM\Column(type="string", length=64, nullable=true)
*/
protected $analytics;
/**
* #Gedmo\TreeLeft
* #ORM\Column(name="lft", type="integer")
*/
private $lft;
/**
* #Gedmo\TreeLevel
* #ORM\Column(name="lvl", type="integer")
*/
private $lvl;
/**
* #Gedmo\TreeRight
* #ORM\Column(name="rgt", type="integer")
*/
private $rgt;
/**
* #Gedmo\TreeRoot
* #ORM\Column(name="root", type="integer", nullable=true)
*/
private $root;
/**
* #Gedmo\TreeParent
* #ORM\ManyToOne(targetEntity="Site", inversedBy="children")
* #ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="CASCADE")
*/
private $parent;
/**
* #ORM\OneToMany(targetEntity="Site", mappedBy="parent")
* #ORM\OrderBy({"lft" = "ASC"})
*/
private $children;
private $file;
public $idByFilter;
public $nameByFilter;
/**
* Proxy translations (Knp/Doctrine Behaviors)
* An extra feature allows you to proxy translated fields of a translatable entity.
* You can use it in the magic __call method of you translatable entity so that when
* you try to call getName (for example) it will return you the translated value
* of the name for current locale:
*/
public function __call($method, $arguments)
{
return $this->proxyCurrentLocaleTranslation($method, $arguments);
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set host
*
* #param string $host
* #return Site
*/
public function setHost($host)
{
$this->host = $host;
return $this;
}
/**
* Get host
*
* #return string
*/
public function getHost()
{
return $this->host;
}
/**
* Set isDefault
*
* #param boolean $isDefault
* #return Site
*/
public function setIsDefault($isDefault)
{
$this->isDefault = $isDefault;
return $this;
}
/**
* Get isDefault
*
* #return boolean
*/
public function getIsDefault()
{
return $this->isDefault;
}
/**
* Set enabled
*
* #param boolean $enabled
* #return Site
*/
public function setEnabled($enabled)
{
$this->enabled = $enabled;
return $this;
}
/**
* Get enabled
*
* #return boolean
*/
public function getEnabled()
{
return $this->enabled;
}
/**
* Set analytics
*
* #param string $analytics
* #return Site
*/
public function setAnalytics($analytics)
{
$this->analytics = $analytics;
return $this;
}
/**
* Get analytics
*
* #return string
*/
public function getAnalytics()
{
return $this->analytics;
}
/**
* Get ID from Filter
*
* #return string
*/
public function getIdByFilter()
{
return $this->idByFilter;
}
/**
* Get name from Filter
*
* #return string
*/
public function getNameByFilter()
{
return $this->nameByFilter;
}
/**
* Set image
*
* #param string $image
* #return Site
*/
public function setImage($image)
{
$this->image = $image;
return $this;
}
/**
* Get image
*
* #return string
*/
public function getImage()
{
return $this->image;
}
/**
* Set file
*
* #param string $file
* #return Site
*/
public function setFile($file)
{
$this->file = $file;
return $this;
}
/**
* Get file
*
* #return string
*/
public function getFile()
{
return $this->file;
}
/**
*
* Tree functions
*/
public function setParent(Site $parent = null)
{
$this->parent = $parent;
}
public function getParent()
{
return $this->parent;
}
public function getRoot()
{
return $this->root;
}
public function getLvl()
{
return $this->lvl;
}
public function getChildren()
{
return $this->children;
}
public function getLft()
{
return $this->lft;
}
public function getRgt()
{
return $this->rgt;
}
/**
* Add a method to the entity class that shows the name indented by nesting level
*/
public function getLeveledName()
{
return str_repeat(
html_entity_decode(' ', ENT_QUOTES, 'UTF-8'),
($this->getLvl()) * 3
) . $this->getName();
}
public function getLeveledPosition()
{
return str_repeat(
html_entity_decode(' ', ENT_QUOTES, 'UTF-8'),
($this->getLvl()) * 3
);
}
}
And here is SiteTranslation entity:
namespace Pnet\ConlocoBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
use Knp\DoctrineBehaviors\Model as ORMBehaviors;
/**
* #ORM\Entity
*/
class SiteTranslation
{
use ORMBehaviors\Translatable\Translation;
/**
* #ORM\Column(type="string", length=60)
* #Assert\NotBlank(message="site.name.notBlank", groups={"edit"})
* #Assert\Length(max = "60", maxMessage = "site.name.maxLength", groups={"edit"})
*/
protected $name;
/**
* #ORM\Column(type="string", length=100)
* #Assert\NotBlank(message="site.title.notBlank", groups={"edit"})
* #Assert\Length(max = "100", maxMessage = "site.title.maxLength", groups={"edit"})
*/
protected $title;
/**
* #ORM\Column(type="string", length=200)
* #Assert\NotBlank(message="site.longTitle.notBlank", groups={"edit"})
* #Assert\Length(max = "200", maxMessage = "site.longTitle.maxLength", groups={"edit"})
*/
protected $longTitle;
/**
* #ORM\Column(type="string", length=250, nullable=true)
* #Assert\Length(max = "250", maxMessage = "site.keywords.maxLength", groups={"edit"})
*/
protected $keywords;
/**
* #ORM\Column(type="string", length=500, nullable=true)
* #Assert\Length(max = "500", maxMessage = "site.description.maxLength", groups={"edit"})
*/
protected $description;
/**
* Set name
*
* #param string $name
* #return Site
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* #return string
*/
public function getName()
{
return $this->name;
}
/**
* Set title
*
* #param string $title
* #return Site
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* #return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set longTitle
*
* #param string $longTitle
* #return Site
*/
public function setLongTitle($longTitle)
{
$this->longTitle = $longTitle;
return $this;
}
/**
* Get longTitle
*
* #return string
*/
public function getLongTitle()
{
return $this->longTitle;
}
/**
* Set keywords
*
* #param string $keywords
* #return Site
*/
public function setKeywords($keywords)
{
$this->keywords = $keywords;
return $this;
}
/**
* Get keywords
*
* #return string
*/
public function getKeywords()
{
return $this->keywords;
}
/**
* Set description
*
* #param string $description
* #return Site
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* #return string
*/
public function getDescription()
{
return $this->description;
}
}
TL;DR:
As a (probably dirty) workaround, use
{{ item.getName }}
in your Twig template instead of
{{ item.name }}
Explanation:
I came across the same issue and i think that this should be considered a bug in the Knp DoctrineBehaviors documentation when used with Twig. When you call this in your Twig template :
{{ item.name }}
This is what Twig does behind the scenes to get the name property :
try to get the name public property of the item object
if not found, checks for the name public method of the item object
if not found, checks for the getName() public method of the "item" object
if not found, checks for the __call() magic method (and calls it with the name parameter)
The problem here is step 4. The magic __call() method that you defined (as recommended by the official DoctrineBehaviors documentation) is called with the name parameter instead of getName. It then calls the proxyCurrentLocaleTranslation() method who tries to call the name public method of your translation class. Of course, it doesn't exist because you only have a getName() method.
See this issue in Twig : https://github.com/twigphp/Twig/issues/342
By using directly the {{ item.getName }} code in Twig, the proper method name will be called.
This work for me:
public function __call($method, $arguments)
{
try {
return $this->proxyCurrentLocaleTranslation($method, $arguments);
} catch (\Symfony\Component\Debug\Exception\ContextErrorException $e) {
return $this->proxyCurrentLocaleTranslation('get' . ucfirst($method), $arguments);
}
}
You haven't moved all the translatable properties/methods to your <Name>Translation class.
The exception clearly states that there is no name/getName method in your SiteTranslation class.
Please read my answer over here to see how Knp\DoctrineBehaviors's magic translation proxy is used correctly.
I have a Util class in a Symfony 2.4 proyect that get the slug from a book. The slug cannot be repeated. Each slug must be unique. I have the following code form the class that generate the slug. I have the error:
Fatal error: Using $this when not in object context in C:\xampp\htdocs\gens\src\
Sakya\GensBundle\Util\Util.php on line 38
namespace Sakya\GensBundle\Util;
use Symfony\Component\HttpFoundation\Response;
use Doctrine\ORM\EntityManager;
class Util
{
protected $em;
public function __construct(EntityManager $em)
{
$this->em = $em;
}
public static function getSlug($slug)
{
$separador = '-';
$tildes=array('á','é','í','ó','ú');
$vocales=array('a','e','i','o','u');
str_replace($vocales,$tildes,$slug);
$slug = iconv('UTF-8', 'ASCII//TRANSLIT', $slug);
$slug = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $slug);
$slug = strtolower(trim($slug, $separador));
$slug = preg_replace("/[\/_|+ -]+/", $separador, $slug);
$i = 1;
while (! $this->em->getRepository("GensBundle:Libro")->findBySlug($slug)){
$slug = $slug."-".$i;
$i++;
}
return $slug;
}
}
It is mi Entity "Libro"
<?php
namespace Sakya\GensBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Sakya\GensBundle\Util\Util;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Libro
*
* #ORM\Table()
* #ORM\Entity
*/
class Libro
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
*
* #ORM\Column(name="libro", type="string", length=255)
*/
private $libro;
/**
* #ORM\Column(type="string")
*
* #Assert\NotBlank()
*/
protected $slug;
/**
* #var string
*
* #ORM\Column(name="autor", type="string", length=255)
*/
private $autor;
/**
* #var string
*
* #ORM\Column(name="prefacio", type="string", length=700)
*/
private $prefacio;
/**
* #ORM\OneToMany(targetEntity="Capitulo", mappedBy="libro")
*/
private $capitulo;
public function __toString()
{
return $this->getLibro();
}
/**
* Constructor
*/
public function __construct()
{
$this->capitulo = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set libro
*
* #param string $libro
* #return Libro
*/
public function setLibro($libro)
{
$this->libro = $libro;
$this->slug = Util::getSlug($libro);
return $this;
}
/**
* Get libro
*
* #return string
*/
public function getLibro()
{
return $this->libro;
}
/**
* Set autor
*
* #param string $autor
* #return Libro
*/
public function setAutor($autor)
{
$this->autor = $autor;
return $this;
}
/**
* Get autor
*
* #return string
*/
public function getAutor()
{
return $this->autor;
}
/**
* Add capitulo
*
* #param \Sakya\GensBundle\Entity\Capitulo $capitulo
* #return Libro
*/
public function addCapitulo(\Sakya\GensBundle\Entity\Capitulo $capitulo)
{
$this->capitulo[] = $capitulo;
return $this;
}
/**
* Remove capitulo
*
* #param \Sakya\GensBundle\Entity\Capitulo $capitulo
*/
public function removeCapitulo(\Sakya\GensBundle\Entity\Capitulo $capitulo)
{
$this->capitulo->removeElement($capitulo);
}
/**
* Get capitulo
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getCapitulo()
{
return $this->capitulo;
}
/**
* Set prefacio
*
* #param string $prefacio
* #return Libro
*/
public function setPrefacio($prefacio)
{
$this->prefacio = $prefacio;
return $this;
}
/**
* Get prefacio
*
* #return string
*/
public function getPrefacio()
{
return $this->prefacio;
}
/**
* Set slug
*
* #param string $slug
* #return Libro
*/
public function setSlug($slug)
{
$this->slug = $slug;
return $this;
}
/**
* Get slug
*
* #return string
*/
public function getSlug()
{
return $this->slug;
}
}
How can I make a consult that check that the slug is not in the database form the Uti Class?
Thanks for all and sorry for my English
The problem is you are trying refer to a property from static method. Don't do it unless the property is also static.
The best way I can suggest is change the static method into not-static, then create a service from Util class, and make validation outside the entity. It's not a good idea using service inside entity class.
You didn't show the context but I can guess: if you want set slug based on a form - then the best way to achieve what you want would be create a validator.
I'm working with Symfony2 2.3 and I need sharing data between two entities trough the DotrineFixturesBundle
But the Sharing Objects between Fixtures dont work.
When the command is executed
php app/console doctrine:fixtures:load --purge-with-truncate
the data is load, But the fields with relations are NULL
Table Divterrigral
ID DESCRIPTION
1 description
Table with FK Divterribase
ID DIVTERRIGRAL_ID DESCRIPTION
1 Null descriptionInfo
if I do mysql through I can map the relationship works.
the class LoadDivterrigral.
<?php
namespace Soint\InventarioBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Soint\InventarioBundle\Entity\Divterrigral;
class LoadDivterrigral extends AbstractFixture implements OrderedFixtureInterface{
/**
* {#inheritDoc}
*/
public function load(ObjectManager $manager){
$ahuachapan = new Divterrigral();
$ahuachapan->setNombre('Ahuachapan');
$manager->persist($ahuachapan);
$manager->flush();
$this->addReference('dep-ahuachapan', $ahuachapan);
}
/**
* {#inheritDoc}
*/
public function getOrder(){
return 1; // el orden en el cual serán cargados los accesorios
}
}
The class LoadDivTerribase
<?php
namespace Soint\InventarioBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Soint\InventarioBundle\Entity\Divterribase;
class LoadDivterribase extends AbstractFixture implements OrderedFixtureInterface {
/**
* {#inheritDoc}
*/
public function load(ObjectManager $manager){
$ahuachapan = new Divterribase();
$ahuachapan->setNombre('Ahuachapan');
$ahuachapan->setDivterrigral($this->getReference('dep-ahuachapan'));
$manager->persist($ahuachapan);
$manager->flush();
}
/**
* {#inheritDoc}
*/
public function getOrder(){
return 2;
}
}
Entity Divterrigral
<?php
namespace Soint\InventarioBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Soint\InventarioBundle\Entity\Divterribase;
/**
* #ORM\Entity
*/
class Divterrigral {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue;
*/
protected $id;
/** #ORM\Column(type="string", length=100) */
protected $nombre;
/**
* #ORM\OneToMany(targetEntity="Divterribase", mappedBy="divterrigral")
*/
protected $divterribases;
public function __construct() {
$this->divterribases = new ArrayCollection();
}
public function addDivterribases(Articulo $articulos){
$this->divterribases[] = $articulos;
}
public function getDivterribases(){
return $this->divterribases;
}
/**
* Get id
* #return integer
*/
public function getId(){
return $this->id;
}
/**
* Set nombre
* #param string $nombre
* #return Divterrigral
*/
public function setNombre($nombre){
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
* #return string
*/
public function getNombre(){
return $this->nombre;
}
public function __toString(){
return $this->getNombre();
}
}
Entity Divterribase
<?php
namespace Soint\InventarioBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Soint\InventarioBundle\Entity\Divterrigral;
/**
* #ORM\Entity
*/
class Divterribase {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue;
*/
protected $id;
/** #ORM\Column(type="string", length=100) */
protected $nombre;
/**
* #ORM\ManyToOne(targetEntity="Divterrigral", inversedBy="divterribases")
* #ORM\JoinColumn(name="divterrigral_id", referencedColumnName="id")
* #return integer
*/
protected $divterrigral;
/**
* Get id
* #return integer
*/
public function getId(){
return $this->id;
}
/**
* Set nombre
* #param string $nombre
* #return Divterribase
*/
public function setNombre($nombre){
$this->nombre = $nombre;
return $this;
}
/**
* Get nombre
* #return string
*/
public function getNombre(){
return $this->nombre;
}
/**
* Set divTerriGral
* #param Soint\InventarioBundle\Entity\Divterrigral $divTerriGral
* #return Divterribase
*/
public function setDivterrigral(Divterrigral $divTerriGral = null){
$this->divTerriGral = $divTerriGral;
return $this;
}
/**
* Get divTerriGral
* #return Soint\InventarioBundle\Entity\Divterrigral
*/
public function getDivterrigral(){
return $this->divTerriGral;
}
public function __toString(){
return $this->getNombre();
}
}
Entity Divterrigral
/**
* #ORM\OneToMany(targetEntity="Divterribase", mappedBy="divterrigral",cascade={"persist", "remove"})
*/
protected $divterribases;
Further reading : http://doctrine-orm.readthedocs.org/en/2.0.x/reference/working-with-associations.html#transitive-persistence-cascade-operations
I use FOSUserBundle and 'group' function
At first in my User.php
There were such getter and setter
/**
* Add groups
*
* #param \Acme\UserBundle\Entity\Group $groups
* #return User
*/
public function addGroup(\Acme\UserBundle\Entity\Group $groups)
{
$this->groups[] = $groups;
return $this;
}
/**
* Remove groups
*
* #param \Acme\UserBundle\Entity\Group $groups
*/
public function removeGroup(\Acme\UserBundle\Entity\Group $groups)
{
$this->groups->removeElement($groups);
}
/**
* Get groups
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getGroups()
{
return $this->groups;
}
but,this error happens
FatalErrorException: Compile Error: Declaration of Acme\UserBundle\Entity\User::addGroup() must be compatible with that of FOS\UserBundle\Model\GroupableInterface::addGroup()
in FOS\UserBundle\Model\GroupableInterface
public function addGroup(GroupInterface $group);
in my Acme\UserBundle\Entity\User
public function addGroup(\Acme\UserBundle\Entity\Group $groups)
{
$this->groups[] = $groups;
return $this;
}
How can I adjust the argument type or correct this error?
For now,I have commented out these three function.
at that time it looked works well.
But now ,I use Sonataadmin bundle and in
#SonataAdminBundle/Admin/UserAdmin.php
protected function configureFormFields(FormMapper $formMapper){
$formMapper
->with('General')
->add('groups','entity',array('property' => 'name',
'multiple' => true,
'class' => 'UserBundle:Group',
))
}
it shows this form correctly but when I push submit button to regist,
it shows
Error: Call to a member function contains() on a non-object in ~~~/FOS/UserBundle/Model/User.php line 572
in /FOS/UserBundle/Model/user.php
there is function likt this
public function addGroup(GroupInterface $group)
{
var_dump($group);# I added to check
if (!$this->getGroups()->contains($group)) {
$this->getGroups()->add($group);
}
return $this;
}
var_dump($group) shows
object(Acme\UserBundle\Entity\Group)#923 (3) { ["id":protected]=> int(2) ["name":protected]=> string(12) "TeacherGroup" ["roles":protected]=> array(0) { } }
I guess it has group information correctly..
How can I fix this problem?
my whole user.php
// src/Acme/UserBundle/Entity/User.php
namespace Acme\UserBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use FOS\UserBundle\Model\GroupableInterface;
/**
* #ORM\Entity
* #ORM\Table(name="fos_user")
* #ORM\HasLifecycleCallbacks
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*
*/
protected $id;
/**
*
* #ORM\OneToOne(targetEntity="Acme\UserBundle\Entity\Lesson", mappedBy="teacher")
*/
private $LessonAsTeacher;
/**
*
* #ORM\OneToMany(targetEntity="Acme\UserBundle\Entity\Lesson", mappedBy="student*removethis : name of the variable in Lesson.php*")
*/
private $LessonAsStudent;
/**
*
* #ORM\ManyToOne(targetEntity="Acme\UserBundle\Entity\Sex", inversedBy="sex*removethis : name of the variable in user.php*")
* #ORM\JoinColumn(name="sex", referencedColumnName="id",nullable=false)
*/
private $sex;
/**
* #ORM\ManyToMany(targetEntity="Acme\UserBundle\Entity\Group")
* #ORM\JoinTable(name="fos_user_user_group",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="group_id", referencedColumnName="id")}
* )
*/
protected $groups;
/**
* #ORM\Column(type="string", length=255)
*
* #Assert\NotBlank(message="Please enter your first name.", groups={"Registration", "Profile"})
* #Assert\MinLength(limit="0", message="The name is too short.", groups={"Registration", "Profile"})
* #Assert\MaxLength(limit="255", message="The name is too long.", groups={"Registration", "Profile"})
*/
protected $firstname;
/**
* #ORM\Column(type="string", length=255)
*
* #Assert\NotBlank(message="Please enter your last name.", groups={"Registration", "Profile"})
* #Assert\MinLength(limit="0", message="The name is too short.", groups={"Registration", "Profile"})
* #Assert\MaxLength(limit="255", message="The name is too long.", groups={"Registration", "Profile"})
*/
protected $lastname;
/**
* #ORM\Column(type="date")
*/
protected $birthday;
/**
* #var \DateTime
*
* #ORM\Column(name="createdAt", type="datetime")
*/
private $createdAt;
/**
* #var \DateTime
*
* #ORM\Column(name="updatedAt", type="datetime")
*/
private $updatedAt;
public function __construct()
{
parent::__construct();
// your own logic
}
public function getFirstname()
{
return $this->firstname;
}
public function setFirstname($name)
{
$this->firstname = $name;
return $this;
}
public function getLastname()
{
return $this->lastname;
}
public function setLastname($name)
{
$this->lastname = $name;
return $this;
}
public function getSex()
{
return $this->sex;
}
public function setSex($sex)
{
$this->sex = $sex;
return $this;
}
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set age
*
* #param integer $age
* #return User
*/
public function setAge($age)
{
$this->age = $age;
return $this;
}
/**
* Get age
*
* #return integer
*/
public function getAge()
{
return $this->age;
}
/**
* Set birthday
*
* #param \DateTime $birthday
* #return User
*/
public function setBirthday($birthday)
{
$this->birthday = $birthday;
return $this;
}
/**
* Get birthday
*
* #return \DateTime
*/
public function getBirthday()
{
return $this->birthday;
}
/**
* #ORM\PrePersist
*/
public function prePersist()
{
$this->createdAt = new \DateTime;
$this->updatedAt = new \DateTime;
}
/**
* #ORM\PreUpdate
*/
public function preUpdate()
{
$this->updatedAt = new \DateTime;
}
/**
* Set createdAt
*
* #param \DateTime $createdAt
* #return User
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* #return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* #param \DateTime $updatedAt
* #return User
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* #return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Get groups
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getGroups()
{
return $this->groups;
}
/**
* Add groups
*
* #param \Acme\UserBundle\Entity\Group $groups
* #return User
*/
// public function addGroup(\Acme\UserBundle\Entity\Group $groups)
// {
// $this->groups[] = $groups;
// return $this;
// }
/**
* Remove groups
*
* #param \Acme\UserBundle\Entity\Group $groups
*/
// public function removeGroup(\Acme\UserBundle\Entity\Group $groups)
// {
// $this->groups->removeElement($groups);
// }
}
my whole Group.php
namespace Acme\UserBundle\Entity;
use FOS\UserBundle\Entity\Group as BaseGroup;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="fos_group")
*/
class Group extends BaseGroup
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
}
The problem is that you override getGroups() like this:
/**
* Get groups
*
* #return \Doctrine\Common\Collections\Collection
*/
public function getGroups()
{
return $this->groups;
}
But you never initialized $this->groups, so when you call $this->getGroups()->contains(), it says that $this->getGroups() is a non-object, which is true!
To solve this you have 2 solutions.
You can initialize groups in the constructor of User:
public function __construct()
{
parent::__construct();
&this->groups = new ArrayCollection();
}
Or you can change the getGroups() function to return a new object if groups hasn't been initialized:
public function getGroups()
{
return $this->groups ?: $this->groups = new ArrayCollection();
}
In both cases, don't forget to add use Doctrine\Common\Collections\ArrayCollection; at the beginning of User.php.
I got the same error:
FatalErrorException: Compile Error: Declaration of Acme\UserBundle\Entity\User::addGroup() must be compatible with that of FOS\UserBundle\Model\GroupableInterface::addGroup()
After searching I found out (FOS Git Issue 988) that this special error is a Doctrine 'Bug' or sth.
Doctrine should not generate the method at all because there is an implementation of addGroup() in the base class.
I worked around it by modifying the signature from
public function addGroup(\MyBundleNamespace\Entity\Group $groups)
public function removeGroup(\MyBundleNamespace\Entity\Group $groups)
to
public function addGroup(\FOS\UserBundle\Model\GroupInterface $groups)
public function removeGroup(\FOS\UserBundle\Model\GroupInterface $groups)
This way you prevent Doctrine from generating these two functions with the wrong signature.
Version Infos:
Symfony 2.2.1
DoctrineORM 2.2.3
FOSUserBundle 1.3.1
PHP 5.4.4-14
Maybe this can help someone else!
I came across this problem and the simple solution was to change the declaration of the groups variable from public to protected:
/**
* #var \Doctrine\Common\Collections\Collection
*/
protected $groups;
solution is simply: remove all setters and getters from your own entity in your own userBundle and always run doctrine:generate:entities for specyfic bundle, not for all.