I have a form with fields that are translated. One of this fields is a file, witch must to be uploaded (each language have different file).
I am using 'stof/doctrine-extensions-bundle' and 'a2lix/translation-form-bundle' and for uploading files 'vich/uploader-bundle' with symfony2.
found this https://github.com/a2lix/TranslationFormBundle/issues/83, but it's not working
Maximum function nesting level of '100' reached, aborting!
My Catalog entity:
/**
* Catalog.
*
* #ORM\Entity()
* #ORM\Table("catalog")
*
* #Vich\Uploadable
*
* #Gedmo\TranslationEntity(class="Entity\Catalog\CatalogTranslation")
*/
class Catalog
{
/**
* #var int
*
* #ORM\Column(type="integer")
* #ORM\Id()
* #ORM\GeneratedValue()
*/
private $id;
/**
* #var string
*
* #ORM\Column()
*
* #Gedmo\Translatable()
*
* #Assert\NotBlank()
*/
private $name;
/**
* #var File
*
* #Vich\UploadableField(mapping="product_image", fileNameProperty="imageName")
*
* #Assert\Image(maxSize = "4M")
*/
protected $imageFile;
/**
* #var string
*
* #ORM\Column(nullable=true)
* #Gedmo\Translatable()
*/
protected $imageName;
/**
* #ORM\OneToMany(
* targetEntity="CatalogTranslation",
* mappedBy="catalog",
* cascade={"persist", "remove"}
* )
*/
private $translations;
}
Also tried this when building form:
->add('imageName', 'a2lix_translationsForms', [
'form_type' => 'vich_file',
'form_options' => array(
'required' => true,
'mapping' => 'product_image',
'allow_delete' => true,
'download_link' => true,
)
])
My guess is that CatalogTranslation should be the class defined as Uploadable as otherwise it will probably confuse VichUploaderBundle.
I'd try something like this:
<?php
/**
* Catalog.
*
* #ORM\Entity()
* #ORM\Table("catalog")
*
* NOT uploadable
*
* #Gedmo\TranslationEntity(class="Entity\Catalog\CatalogTranslation")
*/
class Catalog
{
/**
* #var int
*
* #ORM\Column(type="integer")
* #ORM\Id()
* #ORM\GeneratedValue()
*/
private $id;
/**
* #var string
*
* #ORM\Column()
*
* #Gedmo\Translatable()
*
* #Assert\NotBlank()
*/
private $name;
/**
* #var string
*
* #ORM\Column(nullable=true)
* #Gedmo\Translatable()
*/
protected $imageName;
/**
* #ORM\OneToMany(
* targetEntity="CatalogTranslation",
* mappedBy="catalog",
* cascade={"persist", "remove"}
* )
*/
private $translations;
}
class CatalogTranslation
{
// ... as usual
/**
* #var File
*
* #Vich\UploadableField(mapping="product_image", fileNameProperty="imageName")
*
* #Assert\Image(maxSize = "4M")
*/
protected $imageFile;
protected $imageName;
}
Related
I started using API Platform after having a good documentation and watching a professionnel tutoriel, and now I encountered a problem.
I have two entities User & Role, the Role is nested in User.
I want to disable direct operations on Role, I want only when I post a User with Role, the post operation works but when I post directly on Role /api/roles, the post operation have to be disabled.
User:
/**
* #ApiResource(
* normalizationContext={
* "groups"={"get"}
* },
* itemOperations={
* "get"={
* "security"="is_granted('IS_AUTHENTICATED_ANONYMOUSLY')",
* "normalization_context"={
* "groups"={"get"}
* }
* },
* "put"= {
* "security"="is_granted('IS_AUTHENTICATED_ANONYMOUSLY') or is_granted('IS_AUTHENTICATED_FULLY') and object.getAuthor() == user",
* "denormalization_context"={
* "groups"={"put"}
* }
* }
* },
* collectionOperations={
* "get"={
* "security"="is_granted('IS_AUTHENTICATED_ANONYMOUSLY')"
* },
* "post"={
* "security"="is_granted('IS_AUTHENTICATED_ANONYMOUSLY')",
* "denormalization_context"={
* "groups"={"user:post"}
* }
* }
* }
* )
* #ORM\Entity(repositoryClass="App\Repository\UserRepository")
*
* #UniqueEntity(fields={"username","email"})
*/
class User implements UserInterface
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*
* #Groups({"get","get_comment_with_author","get_post_with_comments"})
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*
* #Groups({"get","user:post","get_comment_with_author","get_post_with_comments"})
*/
private $username;
/**
* #ORM\Column(type="string", length=255)
*
* #Groups({"put","user:post","get_comment_with_author","get-to-admin"})
*/
private $email;
/**
* #ORM\ManyToMany(targetEntity="Role", fetch="EAGER")
* #Groups({"put","user:post"})
*/
private $rolesCollection;
Role:
/**
* #ApiResource()
* #ORM\Entity(repositoryClass="App\Repository\RoleRepository")
*/
class Role
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
* #Groups({"user:post"})
*/
private $id;
/**
* #ORM\Column(type="string", length=255)
*/
private $label;
You can disable operations (but the get operation) like this:
/**
* #ApiResource(
* collectionOperations={"get"},
* itemOperations={"get"}
* )
* #ORM\Entity(repositoryClass="App\Repository\RoleRepository")
*/
class Role
{
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
* #Groups({"user:post"})
*/
private $id;
...
}
Now you can only read the Roles, but not create or edit them.
I have an issue with Sonata admin form...
I would like to insert music in a album with position...
My issue is when I create an album... I can add many as I want AlbumHasMusic... But when I submit my form... Each AlbumHasMusic have a null album whereas music and positions are ok.
How could I put album id to each AlbumHasMusic ?
These are my Entities :
Album:
/**
* Album
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AppBundle\Entity\AlbumRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Album
{
/**
* #var integer
*
* #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 UploadedFile
*/
private $cover;
/**
* #var String
*
* #ORM\Column(name="filename", type="string", length=255, nullable=true)
*/
private $covername;
/**
*
* #var Array<AlbumHasMusiques>
* #ORM\OneToMany(targetEntity="AppBundle\Entity\AlbumHasMusiques", mappedBy="album", cascade={"persist"})
*/
private $albumHasMusiques;
/**
* #var \DateTime
*
* #ORM\Column(name="updated", type="time", nullable=true)
*/
private $updated;
}
AlbumHasMusic:
/**
* AlbumHasMusiques
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AppBundle\Entity\AlbumHasMusiquesRepository")
*/
class AlbumHasMusiques
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var Album
*
* #ORM\ManyToOne(targetEntity="Album")
* #ORM\JoinColumn(name="album_id", referencedColumnName="id")
*/
private $album;
/**
* #var Musique
*
* #ORM\ManyToOne(targetEntity="Musique")
* #ORM\JoinColumn(name="musique_id", referencedColumnName="id")
*/
private $musique;
/**
* #var integer
*
* #ORM\Column(name="position", type="integer")
*/
private $position;
}
Music:
/**
* Musique
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="AppBundle\Entity\MusiqueRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Musique
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var \DateTime
*
* #ORM\Column(name="duree", type="time", nullable=true)
*/
private $duree;
/**
* #var \DateTime
*
* #ORM\Column(name="updated", type="time", nullable=true)
*/
private $updated;
/**
* #var string
*/
private $file;
/**
* #var String
*
* #ORM\Column(name="filename", type="string", length=255, nullable=true)
*/
private $filename;
/**
* #var string
*
* #ORM\Column(name="titre", type="string", length=255, nullable=true)
*/
private $titre;
/**
* #var Genre
*
* #ORM\ManyToOne(targetEntity="Genre", inversedBy="musiques")
* #ORM\JoinColumn(name="genre_id", referencedColumnName="id", nullable=false)
*/
private $genre;
/**
* #ORM\ManyToMany(targetEntity="MotClef", inversedBy="musiques")
*/
private $motsClef;
}
I would like to do something like Galeries and media of Sonata Media Bundle.
And this is my AlbumAdmin:
class AlbumAdmin extends Admin
{
/**
* #param FormMapper $formMapper
*/
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('titre')
->add('covername')
->add('updated')
->add('albumHasMusiques', 'sonata_type_collection', array(
'cascade_validation' => true,
'by_reference' => false,
), array(
'edit' => 'inline',
'inline' => 'table',
'sortable' => 'position',
'link_parameters' => array('context' => 'default'),
'admin_code' => 'app.admin.album_has_musiques',
)
)
;
}
/**
* {#inheritdoc}
*/
public function prePersist($album)
{
$album->setAlbumHasMusiques($album->getAlbumHasMusiques());
}
/**
* {#inheritdoc}
*/
public function preUpdate($album)
{
$album->setAlbumHasMusiques($album->getAlbumHasMusiques());
}
}
And AlbumHasMusicAdmin :
class AlbumHasMusiquesAdmin extends Admin
{
/**
* #param FormMapper $formMapper
*/
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add('musique', 'sonata_type_model_list', array('required' => true), array(
'link_parameters' => ['context' => 'default'],
))
->add('position', 'hidden')
;
}
}
Do you have any idea ?
I think that you missed something in the addAlbumHasMusiques() function in your album entity : make sure that you wrote it like that :
public function addAlbumHasMusiques(\AppBundle\Entity\AlbumHasMusiques $albumHasMusiques) {
$albumHasMusiques->setAlbum($this); // The important line !!!!
$this->albumHasMusiques[] = $albumHasMusiques;
return $this;
}
I have a series of classes with a slightly complicated set of references between the properties of those classes. I am trying to remove an entity and have that remove be cascaded to its children, but I'm running into foreign key constraint errors. Here is an example of my class structure:
<?php
/**
* #ORM\Entity
* #ORM\Table(name="student_tests")
*/
class StudentTest implements IEntityAccess {
/**
*
* #var int
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var StudentTestItem[]
* #ORM\OneToMany(targetEntity="StudentTestItem", mappedBy="studentTest", cascade{"remove","persist"})
*/
protected $studentTestItems;
/**
* #var Test
* #ORM\ManyToOne(targetEntity="Test", inversedBy="studentTests")
*/
protected $test;
/**
* #var \DateTime
* #ORM\Column(type="datetime", nullable=true)
*/
protected $created;
/**
* #var User
* #ORM\ManyToOne(targetEntity="User", inversedBy="studentTests")
*/
protected $student;
}
//...
<?php
/**
* #ORM\Entity
* #ORM\Table(name="student_test_items")
*/
class StudentTestItem {
/**
*
* #var int
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var StudentTest
* #ORM\ManyToOne(targetEntity="StudentTest", inversedBy="studentTestItems")
*/
protected $studentTest;
/**
* #var User
* #ORM\ManyToOne(targetEntity="User", inversedBy="studentTestItems", cascade={"persist"})
*/
protected $student;
/**
* #var TestItem
* #ORM\ManyToOne(targetEntity="TestItem", inversedBy="studentTestItems", cascade{"persist"})
*/
protected $testItem;
}
//...
/**
*
* #ORM\Table(name="tests")
* #ORM\Entity
*
* #ORM\HasLifecycleCallbacks
*/
class Test implements IEntityAccess {
/**
*
* #var int
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var \DateTime
* #ORM\Column(type="datetime", nullable=true)
*/
protected $startDate;
/**
* #var StudentTest[]
* #ORM\OneToMany(targetEntity="StudentTest", mappedBy="test" )
*/
protected $studentTests;
/**
* #var TestItem[]
* #ORM\OneToMany(targetEntity="TestItem", mappedBy="test", cascade={"all"})
*/
protected $items;
}
//...
/**
*
* #ORM\Table(name="test_items")
* #ORM\Entity
*/
abstract class TestItem {
/**
*
* #var int
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #var Test
* #ORM\ManyToOne(targetEntity="Test", inversedBy="items")
*/
/**
* #var StudentTestItem[]
* #ORM\OneToMany(targetEntity="StudentTestItem", mappedBy="testItem")
*/
protected $studentTestItems;
}
/**
* This is the primary user object. Used for login and all the other
* good stuff.
*
* #ORM\Table(name="users")
* #ORM\HasLifecycleCallbacks
class User implements AdvancedUserInterface, \Serializable, IEntityAccess
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
* #var int
*/
private $id;
/**
* #var StudentTest[]
* #ORM\OneToMany(targetEntity="StudentTest", mappedBy="student", cascade={"persist", "remove"})
*/
protected $studentTests;
/**
* #var StudentTestItem[]
* #ORM\OneToMany(targetEntity="StudentTestItem", mappedBy="student", cascade={"persist", "remove"})
*/
protected $studentTestItems;
}
Let's say I want to delete a student test, and have that delete cascaded to its StudentTestItem children. To do so, I run the following code inside of a controller.
//... blah blah class definition
/**
* Delete a student test
*
* #return \Symfony\Component\HttpFoundation\Response
* #Route("/studenttest/delete", name="student_test_delete")
*/
public function DeleteStudentTestAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$studentTest = $em->getRepository("MyAcmeBundle:StudentTest")->findOneBy(array("id" => 3));
$em->remove($studentTest);
$em->flush();
return $this->redirect($this->generateUrl('student_delete_success'));
}
When I try to run that code, I get the following error message:
An exception occurred while executing 'DELETE FROM student_tests WHERE id = ?' with params [3]:
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`my_acme_bundle/student_test_items`, CONSTRAINT `FK_71FA2A7F36BB1A1` FOREIGN KEY (`student_test_id`) REFERENCES `student_tests` (`id`))
500 Internal Server Error - DBALException
NOW, if I remove all references to studentTestItems from the classes, i.e. I comment out $studentTestItems from the TestItem and User classes, it deletes fine without that issue. Why is this happening? Does Doctrine keep track of the parent references through associations or something?
Looks like you forgot to add ON DELETE CASCADE to the foreign key constraint. Try changing the following association in class StudentTestItem:
/**
* #var StudentTest
* #ORM\ManyToOne(targetEntity="StudentTest", inversedBy="studentTestItems")
*/
protected $studentTest;
To this:
/**
* #var StudentTest
* #ORM\ManyToOne(targetEntity="StudentTest", inversedBy="studentTestItems")
* #ORM\JoinColumn(name="student_test_id", referencedColumnName="id", onDelete="CASCADE")
*/
protected $studentTest;
I have a easy form with a data transformer, it works correctly (update, persist and delete) but I get a error on twig.
Impossible to invoke a method ("trans") on a NULL variable ("") in SonataDoctrineORMAdminBundle:CRUD:edit_orm_one_to_many.html.twig at line 30
error is in this line:
{{ nested_field.vars['sonata_admin'].admin.trans(nested_field.vars.label) }}
All fields have value in nested_field.vars['sonata_admin'] less my custom field
My code is this:
$formMapper
->add(
$formMapper->create('articleAmount', 'text')
->addModelTransformer($articleAmountToStringTransformer)
)
...
Entities
/**
* AppShopHasArticles
*
* #ORM\Table(name="app_shop_has_articles")
* #ExclusionPolicy("all")
* #ORM\Entity(repositoryClass="Nvia\ShopAppBundle\Entity\Repository\AppShopHasArticlesRepository")
* #ORM\HasLifecycleCallbacks()
*/
class AppShopHasArticles
{
/**
* #var \Nvia\CommonBundle\Entity\Article
*
* #ORM\ManyToOne(targetEntity="Nvia\ShopAppBundle\Entity\Article", inversedBy="appShopHasArticles")
* #ORM\JoinColumn(name="article_id", referencedColumnName="id", nullable=false)
* #ORM\Id
* #Expose
*/
private $article;
/**
* #var \Nvia\CommonBundle\Entity\Country
*
* #ORM\ManyToOne(targetEntity="Nvia\CommonBundle\Entity\Country")
* #ORM\JoinColumn(name="country_id", referencedColumnName="id", nullable=false)
* #ORM\Id
* #Expose
*/
private $country;
/**
* #var \Nvia\ShopAppBundle\Entity\AppShop
*
* #ORM\ManyToOne(targetEntity="Nvia\ShopAppBundle\Entity\ArticleAmount")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="country_id", referencedColumnName="country_id", nullable=false),
* #ORM\JoinColumn(name="article_id", referencedColumnName="article_id", nullable=false)
* })
* #Expose
*/
private $articleAmount;
...
}
/**
* ArticleAmount
*
* #ORM\Table(name="article_amount")
*/
class ArticleAmount
{
/**
* #var \Nvia\CommonBundle\Entity\Article
*
* #ORM\ManyToOne(targetEntity="Nvia\ShopAppBundle\Entity\Article", inversedBy="articleAmounts")
* #ORM\JoinColumn(name="article_id", referencedColumnName="id", nullable=false)
* #ORM\Id
*/
private $article;
/**
* #var \Nvia\CommonBundle\Entity\Country
*
* #ORM\ManyToOne(targetEntity="Nvia\CommonBundle\Entity\Country")
* #ORM\JoinColumn(name="country_id", referencedColumnName="id", nullable=false)
* #ORM\Id
*/
private $country;
/**
* #var float
*
* #ORM\Column(name="amount", type="float", precision=10, scale=0, nullable=false)
* #Expose
*/
private $amount;
/**
* #var \DateTime
*
* #ORM\Column(name="created_at", type="datetime", nullable=false)
*/
private $createdAt;
}
What am I doing wrong :/ ?
When using the create method of the formMapper sonata will not insert it's own logic.
Instead try something like this
$formMapper
->add('articleAmount', 'text')
->get('articleAmount')
->addModelTransformer($articleAmountToStringTransformer)
Tested on Sonata 2.4
I'm a begginer in Symfony2...
I have a table "TUTORIEL" and an other table 'Groupe_de_categories' linked by 'id_groupe_categorie'
TABLE Tutoriels :
TABLE Groupe_de_categories
I need to count for each "titre_categorie_nv1" (here in my example 'Maison', 'Art&Loisir', 'Enseignement'...) how many "TUTORIEL" I have where "tutoriel_controle" = 'no'
Before to use Synfony2, I hade this code in PHP (works nice):
<?php
$query_nb_cat = "SELECT CATEGORIE, COUNT(*)
FROM Tutoriels
INNER JOIN Groupe_de_categories
ON TUTORIEL.id_groupe_categorie = Groupe_de_categories.id_groupe_categorie
WHERE tutoriel_controle='no'
GROUP BY CATEGORIE_TITLE";
$nb_cat = mysqli_query($BDD_connect, $query_nb_cat)or die(log_mysql($query_nb_cat));
$row_nb_cat = mysqli_fetch_assoc($nb_cat);
do {
$tableau_nb_cat[]=array(
'titre_cat_nv1'=>$row_nb_cat['titre_categorie_nv1'],
'compte_cat_nv1'=>$row_nb_cat['COUNT(*)'],
);
} while ($row_nb_cat = mysqli_fetch_assoc($nb_cat));
$val_cat=array(
'valeur_retour'=>$tableau_nb_cat
);
mysqli_free_result($nb_cat);
mysqli_close($BDD_connect);
?>
The result was something like that :
Maison => 3
Art&Loisir => 9
Enseignement => 14
...
How can I do this with Symfony2 ?
Here is my ORM :
Tutoriel 'Video2LearnBddBundle:Tutoriels':
Tutoriels
{
/**
* #var integer
*
* #ORM\Column(name="id_tutoriel", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idTutoriel;
/**
* #var string
*
* #ORM\Column(name="titre", type="string", length=70, nullable=false)
*/
private $titre;
/**
* #var string
*
* #ORM\Column(name="description", type="text", nullable=false)
*/
private $description;
/**
* #var \DateTime
*
* #ORM\Column(name="date_creation", type="datetime", nullable=false)
*/
private $dateCreation = 'CURRENT_TIMESTAMP';
/**
* #var string
*
* #ORM\Column(name="nombre_de_vues", type="string", length=45, nullable=true)
*/
private $nombreDeVues;
/**
* #var string
*
* #ORM\Column(name="FAQs", type="string", length=45, nullable=true)
*/
private $faqs;
/**
* #var string
*
* #ORM\Column(name="exclusivite", type="string", nullable=false)
*/
private $exclusivite;
/**
* #var string
*
* #ORM\Column(name="eligible_promotion", type="string", nullable=false)
*/
private $eligiblePromotion;
/**
* #var string
*
* #ORM\Column(name="info_moderateur", type="string", length=300, nullable=true)
*/
private $infoModerateur;
/**
* #var string
*
* #ORM\Column(name="tutoriel_controle", type="string", nullable=false)
*/
private $tutorielControle = 'non';
/**
* #var string
*
* #ORM\Column(name="niveau_choix_categorie_autre", type="string", nullable=true)
*/
private $niveauChoixCategorieAutre;
/**
* #var string
*
* #ORM\Column(name="categorie_autre", type="string", length=45, nullable=true)
*/
private $categorieAutre;
/**
* #var \GroupeDeCategories
*
* #ORM\ManyToOne(targetEntity="GroupeDeCategories")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_groupe_categorie", referencedColumnName="id_groupe_categorie")
* })
*/
private $idGroupeCategorie;
/**
* #var \Membres
*
* #ORM\ManyToOne(targetEntity="Membres")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="id_membre", referencedColumnName="id_membre")
* })
*/
private $idMembre;
/**
* #var \Doctrine\Common\Collections\Collection
*
* #ORM\ManyToMany(targetEntity="MotsCles", inversedBy="idTutoriel")
* #ORM\JoinTable(name="mots_cles_et_tutoriels",
* joinColumns={
* #ORM\JoinColumn(name="id_tutoriel", referencedColumnName="id_tutoriel")
* },
* inverseJoinColumns={
* #ORM\JoinColumn(name="mots_cles", referencedColumnName="mots_cles")
* }
* )
*/
private $motsCles;
Groupe_de_categorie GroupeDeCategories:
<?php
namespace Video2Learn\BddBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* GroupeDeCategories
*
* #ORM\Table(name="Groupe_de_categories", indexes={
* #ORM\Index(name="fk_Groupe_de_categories_Categories_nv11_idx", columns={"titre_categorie_nv1"}),
* #ORM\Index(name="fk_Groupe_de_categories_Categories_nv21_idx", columns={"titre_categorie_nv2"}),
* #ORM\Index(name="fk_Groupe_de_categories_Categories_nv31_idx", columns={"titre_categorie_nv3"}),
* #ORM\Index(name="fk_Groupe_de_categories_Categories_nv41_idx", columns={"titre_categorie_nv4"}),
* #ORM\Index(name="fk_Groupe_de_categories_Categories_nv51_idx", columns={"titre_categorie_nv5"})
* })
* #ORM\Entity
*/
class GroupeDeCategories
{
/**
* #var integer
*
* #ORM\Column(name="id_groupe_categorie", type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $idGroupeCategorie;
/**
* #var \CategoriesNv1
*
* #ORM\ManyToOne(targetEntity="Video2Learn\BddBundle\Entity\CategoriesNv1", inversedBy="GroupeDeCategories")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="titre_categorie_nv1", referencedColumnName="titre_categorie_nv1")
* })
*/
private $titreCategorieNv1;
/**
* #var \CategoriesNv2
*
* #ORM\ManyToOne(targetEntity="CategoriesNv2")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="titre_categorie_nv2", referencedColumnName="titre_categorie_nv2")
* })
*/
private $titreCategorieNv2;
/**
* #var \CategoriesNv3
*
* #ORM\ManyToOne(targetEntity="CategoriesNv3")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="titre_categorie_nv3", referencedColumnName="titre_categorie_nv3")
* })
*/
private $titreCategorieNv3;
/**
* #var \CategoriesNv4
*
* #ORM\ManyToOne(targetEntity="CategoriesNv4")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="titre_categorie_nv4", referencedColumnName="titre_categorie_nv4")
* })
*/
private $titreCategorieNv4;
/**
* #var \CategoriesNv5
*
* #ORM\ManyToOne(targetEntity="CategoriesNv5")
* #ORM\JoinColumns({
* #ORM\JoinColumn(name="titre_categorie_nv5", referencedColumnName="titre_categorie_nv5")
* })
*/
private $titreCategorieNv5;
Thanks !
You can do it by using createQueryBuilder in your repository, or you can use your current query as NativeQuery
Here is a sample (I assume the name of your entities are Tutoriels and GroupeDeCategories)
$em = $this->getDoctrine()->getManager();
$query = $em->getRepository('YourBundle:Tutoriels')
->createQueryBuilder('T')
->join('T.idGroupeCategorie', 'GC')
-->select('COUNT(GC.titreCategorieNv1) AS CT1')
->where("T.tutorielControle = 'no'")
->groupBy('GC.titreCategorieNv1')
->getQuery();
$result = $query->getScalarResult(); //This will return an array of the counts
In your entity I could not find CATEGORIE_TITLE to use in GroupBy and CATEGORIE to add in the selection; so I grouped them by titreCategorieNv1. You can add more fields for your select.
Maybe this link helps you more Symfony CreateQueryBuilder
I did that :
public function updateAction($type_update)
{
$request = Request::createFromGlobals();
$result = $request->isXmlHttpRequest();
if ($result === true) {
switch ($type_update) {
case "compteur_menu":
$em = $this->getDoctrine()->getManager();
$result = $em->createQuery("
SELECT TC.titreCategorieNv1, COUNT(TC.titreCategorieNv1) AS num
FROM Video2LearnBddBundle:Tutoriels T
INNER JOIN T.idGroupeCategorie GC
INNER JOIN GC.titreCategorieNv1 TC
WHERE T.tutorielControle='non'
GROUP BY TC.titreCategorieNv1"
)
->getResult();
$response = new Response();
$response->setStatusCode(Response::HTTP_OK);
$response->setContent(json_encode($result));
$response->headers->set('Content-Type', 'application/json');
return $response;
default:
break;
}
}
}
You can do a repository (more infos here : http://symfony.com/fr/doc/current/book/doctrine.html )
And you could use Doctrine Query Language.
But I think your struture is wrong and it wold be better to have a category, this category has a parent category, ...
So you'll have for example a rootcatégory who has childs named "Bricolage", "Sport", ...
"Bricolage" would have, for exemple a category "Peinture" as child, and so on ;)