Symfony2 Doctrine Migration failed - symfony

I'm new to Symfony. In Symfony 2.8.3 project I created mirgation file using
php app/console doctrine:migrations:generate
But when I put some code in up() and down() methods and try to run
php app/console doctrine:migrations:migrate
I get mistake:
Migration 20160314161511 failed during Pre-Checks. Error Notice: Undefined offset: 1
[Symfony\Component\Debug\Exception\ContextErrorException]
Notice: Undefined offset: 1
I tried to put different code by using "clear" SQL or via scheme, even left up/down methods with only //comments. But still no success.
DoctrineMigrationsBundle was installed and registered in AppKernel.php.
Here's the code of my aim mirgation:
namespace Application\Migrations;
use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;
/**
* Auto-generated Migration: Please modify to your needs!
*/
class Version20160314161511 extends AbstractMigration
{
/**
* #param Schema $schema
*/
public function up(Schema $schema)
{
$this->addSql(
"CREATE TABLE tblProductData (
intProductDataId int(10) unsigned NOT NULL AUTO_INCREMENT,
strProductName varchar(50) NOT NULL,
strProductDesc varchar(255) NOT NULL,
strProductCode varchar(10) NOT NULL,
dtmAdded datetime DEFAULT NULL,
dtmDiscontinued datetime DEFAULT NULL,
stmTimestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (intProductDataId),
UNIQUE KEY (strProductCode)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Stores product data'"
);
}
/**
* #param Schema $schema
*/
public function down(Schema $schema)
{
$this->addSql(
'DROP TABLE tblProductData'
);
}
}
Here is the doctrine_migrations section of my config.yml:
doctrine_migrations:
dir_name: "%kernel.root_dir%/DoctrineMigrations"
namespace: Application\Migrations
table_name: migration_versions
name: Application Migrations
doctrine section of config.yml I left with default value
When I use
php app/console doctrine:migrations:status
I get Available Migrations: 1 and New Migrations: 1

This is a known bug in zend-code library which is a dependency of DoctrineMigrations and this issue appears only on Windows. The temporary workaround is to go to vendors/zend-code/Generator/MethodGenerator.php#L96 and change:
protected static function clearBodyIndention($body) {
....
$lines = explode(PHP_EOL, $body);
....
$body = implode(PHP_EOL, $lines);
....
}
to:
protected static function clearBodyIndention($body) {
....
$lines = explode("\n", $body);
....
$body = implode("\n", $lines);
....
}
The developer of DoctrineMigrations is aware of this bug and you can find more info in this issue.
At this point there is a pull request to zend-code and hopefully this will be merged soon into the master which will then fix the problem.

Related

attempt to read property on null in document.php line 250

attempt to read property on null in document.php line 250
/**
* #since 2.0.0
* #access public
*/
public function get_main_id() {
if ( ! $this->main_id ) {
$post_id = $this->post->ID;
I have the same error. In my case this ocurr after migration of site to other server with All-in-One WP Migration plugin.
The file with problem is: C:\xampp\apps\wordpress\htdocs\wp-content\plugins\elementor\core\base\document.php

How to define schema when I want to use annotations with overblog graphql?

I want to use annotations with overblog graphql in symfony. When i create a provider with an query I get an error about the schema.
error: At least one schema should be declare
I don`t know how to config the schema in the config file. Normally I use yaml as type.
When I use the defaults its using CoreQuery whats pointing to the yaml config file. I don`t know how to change this for using annotations in php. When I remove the schema from definitions i get the same error.
What do I need to change to use annotation with overblog graphql bundle?
/config/packages/graphql.yaml
overblog_graphql:
definitions:
schema:
default:
query: CoreQuery
# mutation: CoreMutation
show_debug_info: '%kernel.debug%'
mappings:
auto_discover: false
types:
- type: annotation
dir: "%kernel.project_dir%/src/GraphQL"
suffix: ~
/src/Graphql/Types/SensorProviders.php
namespace App\Graphql\Types;
use Overblog\GraphQLBundle\Annotation as GQL;
/**
* #GQL\Provider
*/
class SensorProviders {
/**
* #GQL\Query(type="[Sensor]", name="sensors")
*/
public function getSensors() {
return [];
}
}
/src/Graphql/Types/Sensor.php
namespace App\Graphql\Types;
use Overblog\GraphQLBundle\Annotation as GQL;
/**
* #GQL\Type
*/
class Sensor
{
/**
* #GQL\Field(type="Integer!")
*/
public $id;
}
I had the same issues, but after hours of debugging, i figured it out:
With your graphql.yaml you would need following additional file:
/src/Graphql/Types/CoreQuery.php:
namespace App\Graphql\Types;
use Overblog\GraphQLBundle\Annotation as GQL;
/**
* #GQL\Type
*/
class CoreQuery
{
}
Basically you need to define an empty root type and all annotated queries get automatically added.
Same for mutations.

symfony translation by using keys

If I want to translate content in symfony, I will use the translator as it is described in the book:
$translated = $this->get('translator')->trans('Symfony2 is great');
But, if this translations are already existing in a database, how can I access this?
The db looks like
ID | locale | type | field | content
1 | en | message| staff.delete | delete this user?
I wil have to tell the translator where he can get the translation information. Cann you help me with a good tutorial or tipps an tricks?
According to docs you need to register a service in order to load translations from other source like from database
You can also store translations in a database, or any other storage by
providing a custom class implementing the LoaderInterface interface.
See the translation.loader tag for more information.Reference
What i have done,i have a translation bundle where my translation entity resides so i have registered a service in config.yml and passed doctrine manager #doctrine.orm.entity_manager in order to get data from entity
services:
translation.loader.db:
class: Namespace\TranslationBundle\Loader\DBLoader
arguments: [#doctrine.orm.entity_manager]
tags:
- { name: translation.loader, alias: db}
In DBLoader class i have fetched translations from database and sets as mentioned in docs translation.loader
My Loader class
namespace YourNamespace\TranslationBundle\Loader;
use Symfony\Component\Translation\Loader\LoaderInterface;
use Symfony\Component\Translation\MessageCatalogue;
use Doctrine\ORM\EntityManager;
class DBLoader implements LoaderInterface{
private $transaltionRepository;
private $languageRepository;
/**
* #param EntityManager $entityManager
*/
public function __construct(EntityManager $entityManager){
$this->transaltionRepository = $entityManager->getRepository("YourNamespaceTranslationBundle:LanguageTranslation");
$this->languageRepository = $entityManager->getRepository("YourNamespaceTranslationBundle:Language");
}
function load($resource, $locale, $domain = 'messages'){
//Load on the db for the specified local
$language = $this->languageRepository->findOneBy( array('locale' => $locale));
$translations = $this->transaltionRepository->getTranslations($language, $domain);
$catalogue = new MessageCatalogue($locale);
/**#var $translation YourNamespace\TranslationBundle\Entity\LanguageTranslation */
foreach($translations as $translation){
$catalogue->set($translation->getLanguageToken(), $translation->getTranslation(), $domain);
}
return $catalogue;
}
}
Note: Each time you create a new translation resource (or install a bundle
that includes a translation resource), be sure to clear your cache so
that Symfony can discover the new translation resources:
php app/console cache:clear

Symfony2 fixtures with references not loading (constraint violation)

I've been struggling for several hours on my Symfony2 project fixtures. Here is the error I get :
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`wpanel_dev`.`sshuser`, CONSTRAINT `FK_612DE3EE18F45C82` FOREIGN KEY (`website_id`) REFERENCES `Website` (`id`))
Having read a lot of answers, I tried this method without success :
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 (with or without --append)
Here is the fixture code that is generating the error ($new->setWebsite($this->getReference('website-'.$i));)
<?php
namespace WPanel\AdminBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\FixtureInterface;
use WPanel\AdminBundle\Entity\SSHUser;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
class LoadSSHUserData extends AbstractFixture implements OrderedFixtureInterface
{
public function getOrder()
{
return 5;
}
public function load(ObjectManager $manager)
{
for($i = 1; $i <= 20; $i++) {
$new = new SSHUser();
$new->setUser('sshuser'.$i);
$new->setPassword('sshuser'.$i);
$new->setPath('/var/www/website'.$i.'.com');
$new->setWebsite($this->getReference('website-'.$i));
$manager->persist($new);
}
$manager->flush();
}
}
?>
I'm sure the reference is ok. I've been using add/getReference on other classes without any problem.
Thanks for your help !
This error means that there isn't any record on the website table with that ID if I understood correctly.
Either there is a problem with your ordering, or typo in reference.
It seems that you do not have 20 websites object fixtures since you are using the $i counter from 0 to 20.

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