Symfony & Doctrine - Repository or Doctrine cache to clear? - symfony

My environment :
Symfony 2.7
Custom Bundle "IpadBundle".
Entity is "Checksum.php" and my controller is "MainController.php".
All work perfect when i Use the findAll() method on my repo. Then
I added 2 new properties in my entity ($file_path and $creation_date)
Getters and Setters were generated by app/console doctrine:generate:entities IpadBundle:Checksum
Mysql database has been updated via doctrine:schema:update --force
I went to my phpmyadmin to fill manually the 2 new cols
... but result of findAll() doesn't include these new cols ! I tried :
cache:clear --env=prod
cache:warmup
"$cacheDriver = new \Doctrine\Common\Cache\ArrayCache();" + "$cacheDriver->deleteAll();"
"app/console doctrine:cache:clear-metadata" + "app/console doctrine:cache:clear-query" + "app/console doctrine:cache:clear-result".
But no results.
Any idea ?

Sometimes that happend to me and the only thing I do is restart apache and whola. Is weird IDK why apache saves some cache for entities, try it and let me know if that works for you. Good Luck !

Related

PDO Exception: An exception occurred in driver: could not find driver for mysql

I know it is frequently asked question. But I reviewed and read all of it. Unfortunately I could not find a correct answer for my problem. I am using symfony. I followed the instruction and tutorial on https://symfony.com/doc/current/doctrine.html. all steps went perfectly. I run the following commands in terminal without any problem:
composer require symfony/orm-pack
composer require --dev symfony/maker-bundle
php bin/console doctrine:database:create
php bin/console make:entity
php bin/console make:migration
php bin/console doctrine:migrations:migrate
php bin/console make:controller ProductController
with the above commands I could create a database, ProductEntity, a table for Product
Till this point I suppose that the connection to my database runs perfectly.
Then in ProductController I used the Code on the symfony website:
// src/Controller/ProductController.php
namespace App\Controller;
// ...
use App\Entity\Product;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Response;
class ProductController extends AbstractController
{
/**
* #Route("/product", name="create_product")
*/
public function createProduct(): Response
{
// you can fetch the EntityManager via $this->getDoctrine()
// or you can add an argument to the action: createProduct(EntityManagerInterface $entityManager)
$entityManager = $this->getDoctrine()->getManager();
$product = new Product();
$product->setName('Keyboard');
$product->setPrice(1999);
$product->setDescription('Ergonomic and stylish!');
// tell Doctrine you want to (eventually) save the Product (no queries yet)
$entityManager->persist($product);
// actually executes the queries (i.e. the INSERT query)
$entityManager->flush();
return new Response('Saved new product with id '.$product->getId());
}
}
It gives Error: Driver not found like in the picture
I have checked database url in env, it works without problem (I created a database and product table through it). I checked phpinfo and pdo_mysql is enabled without problem.
I have tested database connection with fixature following the instruction here https://symfony.com/doc/current/testing/database.html and was successful without problem
Can you please help me?
Thanks to guillaumesmo, I used symfony php -m. Here I saw the error unable to load pdo_mysql library. I remembered, that I have 2 PHP Versions installed on my system.
I updated the PHP Version to PHP 7.4.1 and deleted the older versions. It works perfectly. I didn't understand why could I connect and update my database via Terminal and Fixature but not with EntityManagerInterface. Anyhow I works now

Symfony 4 and Doctrine, how to generate repository automatically after mapping?

All the tutorials I am finding have the repository created automatically using make:entity when creating new tables
but I have been importing from an existing database following the official documentation with the following command: php bin/console doctrine:mapping:import App\\Entity annotation --path=src/Entity
This command does not seem to create any repository... and the documentation does not talk about generating a repository
I know I can create one manually but is there a command to generate them automatically ? I have 25 tables.... Would be very useful
lazy me oO
edit: I also tried php bin\console make:entity --regenerate but I get no change on all tables and no repository created
SOLUTION 1
You can simply run
php bin/console make:entity --regenerate
This will prompt and ask for:
Enter a class or namespace to regenerate [App\Entity]:
Just press Enter or specify the location of your entity folder, and it will create missing getters/setters & Repositories.
---> WARNING:
If it does not create the repositories make sure you have the following annotation in your entities :
/**
* #ORM\Entity(repositoryClass="App\Repository\MyClassRepository")
*/
class MyClass
{
}
You also might want to clear your cache if it's not working (as noted by #Pavel Petrov in the comments)
SOLUTION 2
The SymfonyMakerBundle allows you to create your own makers. So you could make a new one called make:repositories that will generate a repository for each entity found in the /Entity folder.
To do that, create a class (MakeRepositories) that extends AbstractMaker in your src/Maker/ directory. (documentation: https://symfony.com/doc/current/bundles/SymfonyMakerBundle/index.html#creating-your-own-makers)
Use the core maker make:entity to help you create your new command (since it contains the code to generate a repository) : https://github.com/symfony/maker-bundle/blob/master/src/Maker/MakeEntity.php
After generating your entity classes from database, add the following annotation to each of your entities:
#ORM\Entity(repositoryClass="App\Repository\ClassNameRepository")
To genenerate the repository classes, run the following command:
php bin/console make:entity --regenerate App
How to Generate Entities from an Existing Database
Table name: CamelCase (eg: table_name will be TableName)
php bin/console doctrine:mapping:import App\\Entity annotation --path=src/Entity --filter="TableName"
How to Generate Entities
Run below command, it will create entity file.
php bin/console make:entity --regenerate
Next, go to your entity file and add #ORM\Entity repositoryClass
Example Entity file
/**
* XXXXXX
*
* #ORM\Table(name="XXXX")
* #ORM\Entity(repositoryClass="App\Repository\XXXXRepository")
*/
class XXXXX {
Run again this command again, and it will create repository for you.
php bin/console make:entity --regenerate
Do not copy the annotation too fast, I copied the annotation, but in my case the entities were generated automatically, so there was already a line ORM\Repository, which appeared after, delete it or replace it with the solution

Translate Validation Constraint Messages on Symfony

In order to have error messages in different languages, I am following the instructions under this link:
https://symfony.com/doc/current/validation/translations.html
I made the validator files with yaml:
For instance:
# translations/validators.en.yml
author.name.not_blank: Please enter the name of the author.
Notice: I tried the extensions yaml and yml
And in src/entity/Data.php
/**
* #var string
*#Assert\NotBlank(message="author.name.not_blank")
*/
private $author;
I just get the message "author.name.not_blank" instead of "Please enter the name of the author."
I cleared the cache like this:
https://symfony.com/doc/2.7/console/usage.html
php app/console cache:clear --env=prod
I get the temporary message on the terminal "Clearing the cache for the prod environment with debug false"
So my questions are: Am I doing something wrong in clearing the cache?
I am using Symfony 2.7
Is there something I am missing ?
By the way, all other translations from files such as
translations/messages.en.yml
are functionning perfectly well.
Thank you very much!
I see your code is fine:
now you can check additional stuff:
app/config:
translator: { fallbacks: ["%locale%"] }
and be sure which environment are you in.
instead of
php app/console cache:clear --env=prod
try
php app/console cache:clear
hope this will helps.

Symfony2 updated entity works on dev but not on prod

I recently had to add new 'field' to Product in my sonata application so i added it in entity devinition ...
/**
* #var integer $deliveryTime
*/
protected $deliveryTime;
/**
* Get deliveryTime
*
* #return integer $deliveryTime
*/
public function getDeliveryTime()
{
return $this->deliveryTime;
}
/**
* #param int $deliveryTime
*/
public function setDeliveryTime($deliveryTime)
{
$this->deliveryTime = $deliveryTime;
}
in ORM
<field name="deliveryTime" column="delivery_time" type="integer" nullable="true" />
in ProductProvider
$formMapper->add('deliveryTime', 'integer')
and in all the views
It works perfectly on my local environment but when i moved it to production it doesn't work.
Funny thing is that if i access dev environment on my production server it shows the delivery time for products but on prod environment it doesn't.
I cleared cache with --env=prod option, even physically deleted cache files from both dev and prod folders but it won't help.
Database is not the issue because it wouldn't work on dev env if the reason was database.
Any ideas what else should i do to make it work on prod env?
(i can switch to dev env without the toolbar but it's not 'nice' approach:)
UPDATE: #moonwave99 yes i did update the database and there's nothing related in app_prod.log
what doesn't work on prod and works on dev:
- showing delivery time for product from the database in product view
- showing/updating delivery time through the admin panel
This was strange - i restarted apache service on production server and now it works.
Try running a few commands,
php app/console doctrine:schema:update --force
php app/console cache:clear
php app/console cache:clear --env=prod --no-debug
if that fails re-push your code
and re run above
Hope that helps
You should to reload APC. Prod environment saves doctrine cache in this system.
If you use PHP + Apache - restart apache
If you use PHP-FPM - restart php-fpm.

Symfony2: deleted property still used in query

I deleted a property (teaser) from an enitiy (sale).
I used the CLi to update the database & entites:
$ php app/console doctrine:schema:update --complete --force
$ php app/console doctrine:generate:entities Our --no-backup
$ php app/console doctrine:cache:clear-metadata
$ php app/console doctrine:cache:clear-result
And i cleared the cache:
$ php app/console cache:clear --no-optional-warmers --no-warmup
Now i have a query created by query builder:
$qb = $this->createQueryBuilder('s');
$q = $qb
->select('s.id')
->leftJoin('s.bills','b')
->where('b.paid = true')
->getQuery()
->getResult();
This throws an error becuas eit generates a select statement that includes the old property:
Column not found: 1054 Unknown column 's0_.teaser' in 'field list'
I tried to understand how Doctrine executes the query but failed to find the source of the problem.
Does anyone have any clues?
UPDATE: I took the DQL from the query, generated by the querybuilder and then used that to create a new Query. Same Error. Then i changed one word in the DQL from uppercae to lowercase (LEFT is now Left) and that one executed just fine.
$q = $this->getEntityManager()
->createQuery('SELECT s,b FROM Our\BuyBundle\Entity\Sale s Left JOIN s.bills b WHERE s.id IN (:randomIds)')
->setParameter('randomIds', $allSaleIds);
So it seems the DQL Statement is cached somewhere, Using the DQL as a hash to get the corresponding SQL Statement.
I still can't quite figure out where and how to clear that cached Information. Especially given the fact that i deleted all content in the app/cache folder as well.
UPDATE2: Found the Solution. Had to clear the APC Cache manually since the console can't do that.
So the Solution would be:
$ php app/console doctrine:cache:clear-query
And if that doesn't work, clear your APC Cache.
My Problem was the APC Cache.
I could not clear the query-cache in CLI (app/console) since the console can't (or is not allowed to) clear the APC Cache.
So i had to clear the APC Cache manually.
Solution is:
$ php app/console doctrine:cache:clear-result
And if that doesn't work, clear the APC Cache (or whatever cache you use) manually.

Resources