It's my code:
file Entity/Article.php
namespace Kaker\FormularzBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Table(name="article")
* #ORM\Entity(repositoryClass="Kaker\FormularzBundle\Entity\ArticleRepository")
*/
class Article {...}
file Entity/ArticleRepository:
namespace Kaker\FormularzBundle\Entity;
use Doctrine\ORM\EntityRepository;
class ArticleRepository extends EntityRepository
{
public function getNickInfo($nick)
{
return $this->getEntityManager()
->createQuery(
'SELECT a FROM KakerFormularzBundle:Article a WHERE a.nick = :nick '
)
->setParameter('nick', $nick)
->getResult();
}
}
file UserController
$em = $this->getDoctrine()->getManager();
$article = $em->getRepository("KakerFormularzBundle:Article")
->getNickInfo($nick);
And I have this error:
Warning: Missing argument 1 for Doctrine\ORM\EntityRepository::__construct(), called in /var/www/apps/sf2-podstwy/app/cache/dev/appDevDebugProjectContainer.php on line 1496 and defined
Related
I try to create default repository in my Symfony 3. First I created Repository class with method 'findByParentOrderedByName'. In next step I added in Entity line:
* #ORM\Entity(repositoryClass="AppBundle\Repository\ChildRepository")
Unfortunelly when I try to run findByParentOrderedByName() I get error
Undefined method 'findAllOrderedByName'. The method name must start with either findBy, findOneBy or countBy!
What I make incorrect?
Repository code:
<?php
namespace AppBundle\Entity;
/**
* Child
* #ORM\Entity(repositoryClass="AppBundle\Repository\ChildRepository")
*/
class Child
{
........
}
To use custom repository class properly, firstly repository class name must be defined in entity class.
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="AppBundle\Repository\ChildRepository")
*/
class Child
{
}
Then repository class created as like this:
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
class ChildRepository extends EntityRepository
{
/**
* #return Child[]
*/
public function findAllOrderedByName()
{
return $this->getEntityManager()
->createQuery('SELECT * c FROM AppBundle:Child c ORDERED BY c.name ASC')
->getResult();
}
}
I can't understand, if i create crud controller with
bin/console make:crud all routes work from controller
like
/**
* #Route("/", name="product_index", methods="GET")
*/
public function index(ProductRepository $productRepository): Response
{
return $this->render('product/index.html.twig', ['products' => $productRepository->findAll()]);
}
.
If i create controller with bin/console make:controller
and define controller with annotation by myself they don't work
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use JMS\Serializer\SerializerBuilder;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Entity\Product;
use App\Repository\ProductRepository;
use JMS\Serializer\SerializationContext;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
class FirstApiController extends AbstractController
{
/**
*
* #Route("/first_api", name="first_api")
*/
public function index(ProductRepository $productRepository)
{
$data = $productRepository->findAll();
$serializer = SerializerBuilder::create()->build();
# $jsonContent = $serializer->serialize($data, 'json');
$jsonContent = $serializer->serialize($data, 'json', SerializationContext::create()->setGroups(array('details')));
$response = JsonResponse::fromJsonString($jsonContent);
return $response;
}
/*
* #Route("/first_api/send", name="send")
*
*/
public function send()
{
$a = "text";
return $a;
}
}
Why that route doesn't work
#Route("/first_api/send", name="send") ?
In routes.yaml i wrote nothing, just empty file.
I used wrong syntax !I used
/* <-- the error is here
* #Route("/first_api/send", name="send")
*
*/
I need to use
/** <-- i nee two "*"
* #Route("/first_api/send", name="send")
*
*/
public
I have 2 bundles and i want to override the repository of one of them in the other :
I have a source bundle : SourceBundle.
I have my override bundle : OverrideBundle
First, in OurVendorOverrideBundle.php, I added :
public function getParent()
{
return 'SomeVendorSourceBundle';
}
Then
I wanted to add a custom method for the repository of an entity of SourceBundle.
The source entity is Response.php, and its repository is ResponseRepository.php
So i did :
<?php
namespace OurVendor\OverrideBundle\Repository;
use Doctrine\ORM\EntityRepository;
use SomeVendor\SourceBundle\Repository\ResponseRepository as BaseRepository;
class ResponseRepository extends BaseRepository
{
/**
*
* #return array
*/
public function getQueryExerciseAllResponsesForAllUsers($exoId)
{
$qb = $this->createQueryBuilder('r');
$qb->join('r.paper', 'p')
->join('p.exercise', 'e')
->where('e.id = ?1')
->andWhere('p.interupt = ?2')
->setParameters(array(1 => $exoId, 2 => 0));
return $qb->getQuery();
}
}
If i dont set the Entity in the OverrideBundle i have this error :
The autoloader expected class "CPASimUSante\ExoverrideBundle\Entity\Response" to be defined in file "/home/www/myproject/vendor/ourvendor/override-bundle/OurVendor/OverrideBundle/Entity/Response.php". The file was found but the class was not in it, the class name or namespace probably has a typo.
The SourceBundle entity is :
<?php
namespace SomeVendor\SourceBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* SomeVendor\SourceBundle\Entity\Response
*
* #ORM\Entity(repositoryClass="SomeVendor\SourceBundle\Repository\ResponseRepository")
* #ORM\Table(name="source_response")
*/
class Response
{
...
}
So i add the Entity in the OverrideBudle :
<?php
namespace OurVendor\OverrideBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use SomeVendor\SourceBundle\Entity\Response as BaseEntity;
/**
* SomeVendor\SourceBundle\Entity\Response
*
* #ORM\Entity(repositoryClass="OurVendor\OverrideBundle\Repository\ResponseRepository")
* #ORM\Table(name="override_response")
*/
class Response extends BaseEntity
{
public function __construct()
{
parent::__construct();
}
}
But then i have this error :
An exception occurred while executing 'SELECT u0_.id AS id0, u0_.ip AS ip1, u0_.mark AS mark2, u0_.nb_tries AS nb_tries3, u0_.response AS response4, u0_.paper_id AS paper_id5, u0_.interaction_id AS interaction_id6 FROM ujm_exoverride_response u1_ INNER JOIN ujm_paper u2_ ON u0_.paper_id = u2_.id INNER JOIN ujm_exercise u3_ ON u2_.exercise_id = u3_.id WHERE u3_.id = ? AND u2_.interupt = ?' with params ["1", 0]:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'u0_.id' in 'field list'
This seems that fields in the table are not found. So i changed to
<?php
namespace OurVendor\OverrideBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use SomeVendor\SourceBundle\Entity\Response as BaseEntity;
/**
* SomeVendor\SourceBundle\Entity\Response
*
* #ORM\Entity(repositoryClass="OurVendor\OverrideBundle\Repository\ResponseRepository")
* #ORM\Table(name="source_response")
*/
class Response extends BaseEntity
{
public function __construct()
{
parent::__construct();
}
}
And it worked.
...But when i reinstalled the bundle, to test if everything was ok i had this fatal error stating that source_response is already defined (which is, indeed).
So what can i do then ?
I have also read that i can't override an entity unless the source extends MappedSuperclass, in my case, it doesn't.
But i am doomed if i only want to override its repository ? Is it possible ? If then, what is the right way ?
If i remove altogether the annotation for the override entity, i have :
Class "OurVendor\OverrideBundle\Entity\Response" sub class of "SomeVendor\SourceBundle\Entity\Response" is not a valid entity or mapped super class.
500 Internal Server Error - MappingException
Doctrine mapping in another bundles can be overriden on entity class metadata loading.
EventListener
<?php
namespace Lol\RandomBundle\EventListener;
use Doctrine\ORM\Event\LoadClassMetadataEventArgs;
class ClassMetadataListener
{
/**
* Run when Doctrine ORM metadata is loaded.
*
* #param LoadClassMetadataEventArgs $eventArgs
*/
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
{
$classMetadata = $eventArgs->getClassMetadata();
if ('AnotherLol\AnotherRandomBundle\Entity\Response' === $classMetadata->name) {
// Do whatever you want...
$classMetadata->customRepositoryClassName = 'ThirdLol\SomeBundle\Repository\NewResponseRepository';
}
}
}
Service configuration
services:
lol.random.listener.class_metadata:
class: Lol\RandomBundle\EventListener\ClassMetadataListener
tags:
- { name: doctrine.event_listener, event: loadClassMetadata }
For the below route I want to return a list of Events that are on or after the current date - however I'm having problems as I'm only aware of how to do either:
Return all objects sorted by date
Return all objects after 'today'
...but I can't work out how to do both together.
Below is my current code:
Controller
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use AppBundle\Entity\Events;
class DefaultController extends Controller
{
/**
* #Route("/events", name="events")
*/
public function eventsAction(Request $request)
{
$calendar = $this->getDoctrine()->getRepository('AppBundle:Events')->findAll();
$criteria = new \Doctrine\Common\Collections\Criteria();
$criteria->where($criteria->expr()->gt('eventdate',new \DateTime('now') ));
$list=$calendar->matching($criteria);
if (!$calendar) {
throw $this->createNotFoundException('No event found for ID ',$list);
}
return $this->render('default/events.html.twig', array(
'title' => 'Events',
'list' => $list,
'message' => '',
));
}
}
Entity repository
namespace AppBundle\Entity\Repository;
use Doctrine\ORM\EntityRepository;
class EventRepository extends EntityRepository
{
public function findAll()
{
return $this->findBy(array(), array('eventdate' => 'ASC'));
}
}
Events entity
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Events
*
* #ORM\Table(name="Events")
* #ORM\Entity
* #ORM\Entity(repositoryClass="AppBundle\Entity\Repository\EventRepository")
*/
class Events
{
/**
* #var \DateTime
*
* #ORM\Column(name="EventDate", type="date", nullable=false)
*/
private $eventdate;
/* .... */
}
// inside your repository
public function getAllFutureEvents()
{
return $this->getEntityManager()->createQuery(
'SELECT b FROM AppBundle:Event e
WHERE e.eventdate > CURRENT_DATE()
ORDER BY e.eventdate DESC'
)->getResult();
}
// inside your controller:
$events = $this->getDoctrine()->getRepository('AppBundle:Events')->getAllFutureEvents();
User Entity :
namespace Core\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* User
* #ORM\Entity(repositoryClass="Core\UserBundle\Entity\UserRepository")
* #ORM\Table(name="user")
*/
class User
{
}
User Repository :
<?php
# src/Core/UserBundle/Entity/UserRepository.php
namespace Core\UserBundle\Entity;
use Doctrine\ORM\EntityRepository;
class UserRepository extends EntityRepository
{
public function example()
{
return "hello word";
}
}
Controller :
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('CoreUserBundle:User');
$repo->example();
Note : get_class($repo) => Doctrine\ORM\EntityRepository
The error:
Error Message : Undefined method 'example'. The method name must start with either findBy or findOneBy!
Try with this
$repo = $em->getRepository('UserBundle:User');