Custom Repository does not work - symfony

Symfony 3.3,
I do according to the documentation https://symfony.com/doc/current/doctrine/repository.html
$entityManager = $this->getDoctrine()->getManager();
$users = $entityManager->getRepository(Users::class)->findAllOrderedByName();
I get exception:
BadMethodCallException:
Undefined method 'findAllOrderedByName'. The method name must start with either findBy or findOneBy!
at vendor\doctrine\orm\lib\Doctrine\ORM\EntityRepository.php:226
at Doctrine\ORM\EntityRepository->__call('findAllOrderedByName', array())
(src\AppBundle\Controller\DefaultController.php:28)
at Doctrine\ORM\EntityRepository->findAllOrderedByName()
(src\AppBundle\Controller\DefaultController.php:28)
at AppBundle\Controller\DefaultController->indexAction(object(Request))
at call_user_func_array(array(object(DefaultController), 'indexAction'), array(object(Request)))
(var\cache\dev\classes.php:4453)
at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), 1)
(var\cache\dev\classes.php:4408)
at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), 1, true)
(vendor\symfony\symfony\src\Symfony\Component\HttpKernel\Kernel.php:171)
at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
(web\app_dev.php:29)
Users entity:
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Users
*
* #ORM\Table(name="users")
* #ORM\Entity(repositoryClass="AppBundle\Repository\UsersRepository")
*/
class Users
{
...
}
UsersRepository
namespace AppBundle\Repository;
use AppBundle\Entity\Users;
use Doctrine\ORM\EntityRepository;
/**
* Created by PhpStorm.
* User: Hett
* Date: 21.07.2017
* Time: 14:25
*/
class UsersRepository extends EntityRepository
{
public function findAllOrderedByName()
{
return $this->getEntityManager()
->createQueryBuilder()
->select("u")
->from(Users::class, "u")
->orderBy("name")
->getQuery()
->getArrayResult();
}
}
As I understand $entityManager->getRepository(Users::class) return default EntiryRepository. Why? What's my mistake?
UPD: I tried to clear cache, but it has no effect:
Hett#Range MINGW64 /c/www/symfony (master)
$ ./bin/console cache:clear
// Clearing the cache for the dev environment with debug
// true
[WARNING] Calling cache:clear without the --no-warmup option is deprecated
since version 3.3. Cache warmup should be done with the cache:warmup
command instead.
[OK] Cache for the "dev" environment (debug=true) was successfully cleared.
Hett#Range MINGW64 /c/www/symfony (master)
$ ./bin/console doctrine:cache:clear-metadata
Clearing ALL Metadata cache entries
Successfully deleted cache entries.

I have auto-generated file
src/AppBundle/Resources/config/doctrine/Users.orm.yml
As I understand .yml configs rewrites annotations congiruation,
when I remove Users.org.yml or add line repositoryClass: AppBundle\Repository\UsersRepository - all work fine.
Which method is correct?

Related

FOSUserBundle undefined method getName();

I'm trying to install FOSUserBundle for the first time. After following the steps, I tried executing php app/console doctrine:schema:update --force. This gives me the following error. I can't understand why it's looking for getName(), it's not shown in the bundle in examples online.
PHP Fatal error: Call to undefined method music\userBundle\userBundle::getName() in /home/me/public_html/music/app/bootstrap.php.cache on line 2505
my bundle:
<?php
// src/userBundle/Entity/User.php
namespace userBundle\Entity;
use FOS\UserBundle\Model\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
}
}
It seems the root directory of your application is interpreted as namespace.
The error output say music\userBundle::getName(), but call getName() on your entity name should be userBundle\User::getName() .
I think you have to re-build your application using the following class architecture :
YourNamespace\UserBundle
So, you entity should become
YourNamespace\UserBundle\Entity\User
and
YourNamespaceUserBundle::User
If you can, post your config.yml and security.yml files
First of all you need to make sure that you include your bundle in AppKernel.php, also should review your namespaces, during best practices your namespace should contain vendor name, bundle name, directory to class, so u should consider to set your namespace to something like this:
namespace music\userBundle\Entity;
Because for now it looks like you do something wrong:
music\userBundle\userBundle::getName()
and
namespace userBundle\Entity;
And after installing new bundles (or after any important changes) dont forget to clear you by cli command or manually. Try this, and if it doesnt helps then we will go deeper to your project structure.
Sorry seems like named the userBundle wrong, as following a video tutorial I did it manually, and forgot the extends part.
namespace music\userBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class userBundle extends Bundle
{
}

Symfony 2.1 error: import #ORM\Table in repository

I am upgrading an application from Symfony 2.0 to Symfony 2.1, I followed this upgrade file and all works fine except that after a cache:clear I get an error when using some repositories. Here is the error:
[Semantical Error] The annotation "#ORM\Table" in class
edasiclinic\AlertesBundle\Repository\AlertesRepository was never imported. Did you maybe
forget to add a "use" statement for this annotation?
This is one example, I get this error with other repositories. I don't understand why I have to import #ORM\Table inside a repository file if I don't use annotation there.
Also if I wait for ~10 seconds and then refresh the browser, it works...
EDIT
This is the Entity:
<?php
namespace edasiclinic\DatabaseBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* edasiclinic\DatabaseBundle\Entity\Alertes
*
* #ORM\Table(name="alertes")
* #ORM\Entity(repositoryClass="edasiclinic\AlertesBundle\Repository\AlertesRepository")
* #ORM\HasLifecycleCallbacks()
*/
class Alertes
{
/**
* #var integer $id
*
* #ORM\Id
* #ORM\Column(name="idAlerta", type="integer")
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
...
}
And this the repository class:
<?php
namespace edasiclinic\AlertesBundle\Repository;
use Doctrine\ORM\EntityRepository;
use edasiclinic\DasiBundle\Funcions\AES;
class AlertesRepository extends EntityRepository
{
public function countUnread($user, $idioma, $fus)
{
// ...
}
}
Thanks
I had this very same problem today. the solution, after some googling, is apparently to include a comment block before the Repository class definition.
in your case:
/**
* AlertesRepository
*/
class AlertesRepository extends EntityRepository
{
...
}
without that comment block, you will receive the nonsensical error about "#ORM\Table". yet another Symfony/Doctrine oddity >_>
It was a PHP bug in versions prior to 5.3.8. From the symfony system requirements:
$this->addRecommendation(
version_compare($installedPhpVersion, '5.3.8', '>='),
'When using annotations you should have at least PHP 5.3.8 due to PHP bug #55156',
'Install PHP 5.3.8 or newer if your project uses annotations.'
);
See PHP bug #55156 for more details and possible workaround if you're unable to upgrade to a PHP version >= 5.3.8.
Looks like you forgot to add the use statement.
<?php
namespace Acme\MyBundle\Entity;
// Remember to include this use statement
use Doctrine\ORM\Mapping as ORM;
/**
* My Entity
*
* #ORM\Table()
* #ORM\Entity(repositoryClass="Acme\MyBundle\Entity\MyEntityRepository")
*/
class MyEntity
{
}
For me it only hapens with certain versions of PHP and the solution was to put the Repository class in a folder above the folder of entity class

How to add a field in entity in Symfony2

I try to add a cahmps in entity. I have this code:
/**
* #var integer $colorevent
* #ORM\Column(name="colorevent", type="integer")
*/
private $colorevent;
/**
* Get colorevent
* #return integer
*/
public function getColorevent()
{
return $this->colorevent;
}
/**
* Set colorevent
* #return integer
*/
public function setColorevent($colorevent)
{
return $this->colorevent = $colorevent ;
}
I run these commands:
php app/console doctrine:schema:update
php app/console doctrine:schema:update --dump-sql
php app/console doctrine:schema:update --force
which renders this message:
Nothing to update yopur database is already in sync with the current
entity metadata
How do I add a field in entity?
How did you generated the entity class in the first time?
It the entity file was generated via doctrine:generate:entities then what you need to do is:
update the Resources/config/doctrine/XXXXXXXXX where xxxx is the entity name.
run app/console doctrine:generate:entity. This will regenerate the php entity file, and the private property, getter and setter.
run php app/console doctrine:schema:update and update the DB
There may be some changes depending of the format you are using (I'm using yml) but the bottom line is that the doctrine:schema:update needs to find changes between the current and the cached (metadata) entity objects.
Each entity must have the Entity annotation
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
*/
class MyEntity
{
// some code
}
I would also suggest using the console tools provided to create the entities.
app/console doctrine:generate:entity
For more information please read the official book (Doctrine, Propel).
If you're using yaml or annotations as described in the other two answers you can use the doctrine command. However the command must contain the entity name:
php app/console doctrine:generate:entities AcmeMyBundle:Customer

Class ..Entity\User is not a valid entity or mapped super class

I'm getting this error when I try to clear the cache (for example):
[Doctrine\ORM\Mapping \MappingException] Class
Aib\PlatformBundle\Entity\User is not a valid entity or mapped super
class.
This is User.php:
<?php
// src/Aib/PlatformBundle/Entity/User.php
namespace Aib\PlatformBundle\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
}
}
And this is the place where User.php is stored:
javier#javier:~/programacion/aib/src/Aib/PlatformBundle/Entity$ ls
User.php UserRepository.php
This is the AppKernel.php:
public function registerBundles()
{
$bundles = array(
...
new Aib\PlatformBundle\AibPlatformBundle(),
...
);
sf 2.0.4
In my case I was missing * #ORM\Entity in my class definition.
/**
* #ORM\Entity
* #ORM\Table(name="listtype")
*/
class ListType
{
...
}
I had the exact same experience with my implementation of the FOS UserBundle and found I was able to resolve the issue by removing the MyBundle\Resources\config\doctrine folder.
I dont fully understand the cause (newbie) but think the issue is a result of having database content built in bother directions, ie from doctrine entities and by reverse engineering some tables.
I had the same problem and it turned out to be the app/config/config.yml
It needed the defintion of the default bundle as below NameBundle, then it worked fine
orm:
auto_generate_proxy_classes: %kernel.debug%
default_entity_manager: default
entity_managers:
default:
mappings:
NameBundle: ~
In my case the problem was solved by changing my servers cache from eAccelerator to APC.
Apparently eAccelerator strips all the comments from files which breaks your annotations.
I had the same error, but this was because I wasn't including the Sonata Application:
try this:
add a line to your AppKernel.php
$bundles = array(
...
new Application\Sonata\UserBundle\ApplicationSonataUserBundle(),
...
If you inherited from mapped class, you can add #ORM\SuperMappedClass in entity's annotation.
You can read most information in this article.

Issue when trying to reload the fixtures

When I try to reload my fixtures using
php app/console doctrine:fixtures:load
I'm getting this error:
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
update a parent row: a foreign key constraint fails (foo_db.Book, CONSTRAINT FK_C29271DD816C6140 FOREIGN KEY (author_id) REFERENCES Author (id))
The error is showed when the status "> purging database" is showed.
This is my code:
class Book{
...
/**
* #ORM\ManyToOne(targetEntity="Author", inversedBy="books")
*/
private $author;
...
}
class Author{
...
/**
* #ORM\OneToMany(targetEntity="Book", mappedBy="author")
*/
private $books;
}
More: my boss has the same code and it doesn't have that error.
Any idea?
sf 2.0.1 (just updated)/ubuntu 10.10.
If I'm guessing correctly, you are using a MySQL database. If yes, then you are facing a bug/problem with the current version of the doctrine-fixtures library for Doctrine2. The problem is that they are using the TRUNCATE command to purge the current database values but this command has problem deleting foreign associations in MySQL.
See this issue and this one on the GitHub repository of the library for more information and workarounds.
In my particular case, I run this command from a script, so to make the command work correctly, I do:
php app/console doctrine:database:drop --force
php app/console doctrine:database:create
php app/console doctrine:schema:update --force
php app/console doctrine:fixtures:load --append
This way, the purging is done by the drop command and appending has the same effect as not appending since the database is empty when the fixtures are loaded.
I must admit I don't know why your boss doesn't have the problem, maybe there is no book associated with an author in his database.
Hope this help.
Regards,
Matt
I've created a simple Event Subscriber class for Symfony 4. All you need to fix the self-referencing foreign keys issue is to add the below class somewhere to your Symfony 4 project.
This subscriber fires before each Symfony CLI command. In case if the command's name is doctrine:fixtures:load, it performs database purge, but doing SET FOREIGN_KEY_CHECKS = 0 first.
This solves the issue without any other modification.
use Doctrine\Common\DataFixtures\Purger\ORMPurger;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ConsoleCommandEventSubscriber implements EventSubscriberInterface
{
/**
* #var EntityManagerInterface
*/
private $entityManager;
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
public static function getSubscribedEvents()
{
return [
ConsoleEvents::COMMAND => 'onCommand',
];
}
public function onCommand(ConsoleCommandEvent $event)
{
if ($event->getCommand()->getName() === 'doctrine:fixtures:load') {
$this->runCustomTruncate();
}
}
private function runCustomTruncate()
{
$connection = $this->entityManager->getConnection();
$connection->exec('SET FOREIGN_KEY_CHECKS = 0');
$purger = new ORMPurger($this->entityManager);
$purger->setPurgeMode(ORMPurger::PURGE_MODE_DELETE);
$purger->purge();
$connection->exec('SET FOREIGN_KEY_CHECKS = 1');
}
}
Add to your composer.json new section script
"scripts": {
"load-fixtures": [
"bin/console doctrine:database:drop --if-exists --force",
"bin/console doctrine:database:create",
"bin/console doctrine:mi:m",
"bin/console doctrine:fixtures:load"
]
}
Then you can run composer install && composer load-fixtures

Resources