Symfony2 updated entity works on dev but not on prod - symfony

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.

Related

login failure in prodcution mode

I am using symfony 5.4.4.
I encounter a problem when I try to connect a user without launching the php server (I want to work in production mode).
I used make:user commands to create the User entity. Then I used the make:auth and make:registration-form commands to generate the login and registration forms.
everything works perfectly when I run the symfony server with the symfony serve command. On localhost:8000 I am able to register and login users with no problem.
I then followed the symfony documentation on deployment as I want my application to run in a server accessible from a private network. I then ran the commands:
composer require symfony/requirements-checker to check
composer install --no-dev --optimize-autoloader
Then I updated the .env file
APP_ENV=prod
APP_DEBUG=0
before clearing the cache with: php bin/console cache:clear
And finally I added rewrite rules with the command: composer require symfony/apache-pack.
now I access my application from any computer (example: http://localhost/myproject/public/user/4) in the network and I navigate without problems on the links.
However, when I try to login a user, it doesn't work.
And when I try to enter one, it works.
In summary, the login works on localhost:8000 but does not work on localhost/myproject/public while all other forms work.
Can you help me ? thank you in advance.
It's OK !
I added the method below into my App/src/Authenticator.php class
Notice : it does not work without the return type "bool" of the function
public function supports(Request $request): bool
{
return self::LOGIN_ROUTE === $request->attributes->get('_route')
&& $request->isMethod('POST');
}
I hope it will be useful to someone!
Thanks to all and especially to Cerad for the link !

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

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.

Symfony & Doctrine - Repository or Doctrine cache to clear?

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 !

Force configuration reload in Symfony2

I have a script which makes changes to the Symfony2 configuration and needs to be made aware of the new configuration before proceeding (specifically adding dbal connections). Is there a way to force the reload of the configuration during script execution?
Update: You can't reload the configuration, but you can set the parameters on-the-fly, see second "Update" paragraph
It's not really possible in Symfony2 to do that.
In production mode, everything (even the configuration) is cached, so you have to clear the cache with
app/console cache:clear --env=prod --no-debug
(maybe followed by a app/console cache:warmup --env=prod --no-debug)
to reload the configuration. In development mode you could experiment with shutdown() followed by a boot() from Symfony\Component\HttpKernel\Kernel or maybe loadClassCache - but all of this is not really that what you want.
What exactly changes are made to the configuration files? Maybe you should use different files for different environments or consider any other method to get those changes (via a simple Webservice or even a static file read from within a Controller).
Update:
I figured out that you can set your container configuration parameter on-the-fly via
$container->setParameter('parameter', value);
Have a look at the Symfony2 documentation.
My answer probably arrives very late but could be useful to someone else.
Symfony cache for "prod" environment is stored in "app/cache/prod/" folder and contains many things (Twig templates translated in PHP in "twig/" subfolder, annotations in "annotations/" subfolder, and... configuration parameters, app*ProjectContainer.php files, among many other things).
So what you can do is: when your configuration script changes parameters.yml, it can also delete appProdProjectContainer.php. The next user to hit your Symfony app will face a little longer response time, but the new configuration parameter will be taken into account and cached.
Here is the partial solution, besides I used it in Symfony 3.2, but nevertheless this code is used to reload bundle configuration on the fly.
Firstly, you should inject container instance inside the service / controller where you want to use bundle instance which was reinitialized with other config:
/**
* Service constructor.
*
* #param ContainerInterface $container
*/
public function __construct(ContainerInterface $container)
{
$container = ReinitializedBundleExtension::updateContainerWithProdConfiguration($container);
}
Secondly, you should add a method to ReinitializedBundleExtension class which will update the container with reinitialized bundle instance and dependencies:
/**
* Updates container with bundle services resolved with production configuration.
*
* #param ContainerInterface $oldContainer
*
* #return ContainerInterface $container
*/
public static function updateContainerWithProdConfiguration(ContainerInterface $oldContainer)
{
$containerBuilder = new ContainerBuilder();
// Copy external services used in the bundle.
$logger = $oldContainer->get('logger');
$containerBuilder->set('logger', $logger);
// Load the production config files.
$bundleResourcesPath = $oldContainer->get('kernel')->locateResource('#ReinitializedBundle/Resources/');
$fileLocator = new FileLocator($bundleResourcesPath . '/config');
$loader = new Loader\YamlFileLoader($containerBuilder, $fileLocator);
$loader->setResolver(new LoaderResolver([$loader]));
$loader->load($bundleResourcesPath . 'config/production/services.yml');
// Resolving bundle services with prduction config.
$containerBuilder->compile();
$containerBuilder->resolveServices($containerBuilder->getDefinitions());
// Merge resolved prod-configured services with old container.
$serviceIds = $containerBuilder->getServiceIds();
foreach ($serviceIds as $serviceId) {
// Services which are not related to the bundle.
if (strpos($serviceId, 'reinitialized_bundle_config_prefix') === false) {
continue;
}
$oldContainer->set($serviceId, $containerBuilder->get($serviceId));
}
return $oldContainer;
}
PS:
1. All the ReinitializedBundle params and services are marked with 'reinitialized_bundle_config_prefix' prefix, so it's easy to recognize them in container, i.e:
reinitialized_bundle_config_prefix.service1
reinitialized_bundle_config_prefix.param1
This is a solution for Yaml configs, so YamlFileLoader was used.
ReinitializedBundle config filestructure:
.ReinitializedBundle
└── Resources
└── config
├── production
| ├─── services.yml
| └─── other stuff
└── staging
├─── services.yml
└─── other stuff

Resources