Oh no, Symfony 2.6 is throwing a Doctrine ORMException: The EntityManager has been shut down

Currently, I am in the process of importing users from an excel file. To manage this task effectively, I have established an entity manager:

$em = $this->getDoctrine()->getManager();

Here is a snippet of the loop I am using for this operation:


...
for ($i=2; $i<=count($usersdatas); $i++) { // $userdatas: an array of users imported from excel
    $nuser = new User();
    $nuser->setEmail($usersdatas[$i]['A']); // email is unique in db
    $nuser->setFname($usersdatas[$i]['B']);
    $nuser->setLname($usersdatas[$i]['C']);
    $nuser->addChannel($channel); //ManytoMany relation
    $em->persist($nuser);
    $em->flush();
}
...
  • The Email field holds unique values in the database and I prefer not to check for duplicates before flushing (database validation).
  • I choose to flush entities one by one for logging purposes (not batch insertion).
  • All other codes and files including entities, services, configurations are free of errors.

Initially, I faced issues when attempting to handle duplicate emails during the import process. However, I resolved this issue by implementing the following adjustment:


...
try {
    $em->persist($nuser);
    $em->flush();
} catch (\Exception $e) {
    ...
}
...

Another challenge emerged in the form of "The EntityManager is closed" exception. This occurred if a duplicate email was detected, causing the automatic closure of the EntityManager ($em). To tackle this problem, I generated a new $em instance before the try/catch block:


...
if (!$em->isOpen()) {
    $em = $em->create(
    $em->getConnection(), $em->getConfiguration());
}
...

While these adjustments have helped resolve previous issues, I encountered difficulties when trying to associate a channel with a user:


...
$nuser->addChannel($channel); //ManytoMany relation
...

In this scenario, $channel is an existing entity. Despite this, post recreating EntityManager, it is treated as a new entity at the time of persisting, resulting in the mentioned error message:


ORMInvalidArgumentException {#1400 ▼
  #message: "A new entity was found through the relationship 'My\UserBundle\Entity\User#channels' that requires cascade persist operations for entity..."
  #code: 0
  #file: "...\vendor\doctrine\orm\lib\Doctrine\ORM\ORMInvalidArgumentException.php"
  #line: 91
  -trace: array:13 [▶]
}

The challenges I am facing seem to be linked to the recreation of EntityManager. It appears to be causing unexpected behavior within the system. Closing the EntityManager post encountering database errors restricts our ability to communicate effectively with the database after such occurrences.

With this context in mind, I pose two questions:

  1. Is there a method available to prevent the automatic closure of EntityManager?
  2. Would utilizing DBAL Doctrine be a viable alternative for importing users, particularly those with potentially duplicated emails?

Answer №1

Exceptions exist for unusual circumstances. They serve the purpose of allowing you to tidy up and then display a user-friendly error message. They are not intended for data validation.

In this scenario, exceptions are being used to determine if it's feasible to add a new user, and if not, to restart the database. Essentially, the goal is to prevent the entity manager from throwing exceptions rather than handling them once they occur.

If you have discovered that the entity manager is closing due to an exception when attempting to insert a duplicate user, it would be wise to check for duplicates before attempting to add them.

However, based on your previous statement about avoiding this method, you may need to resort to writing custom SQL queries, utilizing DBAL (or even classic PDOs), and managing the SQL responses on your own.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhancing Symfony's performance through optimized Ajax response time

When using Symfony2, I am experiencing differences in loading times for AJAX requests between development and production environments. In development, it takes 1 second to load, while in production it only takes 500 milliseconds for a simple call: Here is ...

How to send an html form with php, store it in a MySQL Database, and utilize Ajax and jQuery for

As a beginner in PHP form creation, I have been exploring various tutorials and combining different techniques to create my form. However, I am facing challenges as none of the tutorials cover everything comprehensively from beginning to end. While I beli ...

Remove various rows using checkboxes

Here is some jQuery code I have for deleting multiple rows in a table: $(function(){ $("a.delete").click(function(){ page=$(this).attr("href"); ids=new Array() a=0; $("input.chk:checked").each(function(){ id ...

Display each table within a modal that is triggered by a separate table loop

I have a modal that includes a table. The modal is loaded from a looped table, and despite my confident code, the display seems off. When I run the code, this odd result occurs. Click the link to view the image. <tbody> <?php ...

It appears that my JSON array is unexpectedly displaying directly on the page

I am 'echoing' a json array back to ajax, however it is displaying the entire array on the screen. I have tried everything but nothing seems to work! Can someone please review the code below and see if there's any mistake causing this issue? ...

What is the best method for sharing a php variable in a post?

To retrieve the file extension of an uploaded file, I utilized the following PHP code: $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Extract the file extension from the filename. Now, my goal is to pass this variable ...

PHP- Validate user input before sending email

Hello there! I am diving into the world of PHP and HTML, but I must admit that I am still a beginner. Currently, I am in the process of creating a contact form using PHP and HTML, and I'm facing some confusion when it comes to validating field inputs ...

Tips on transforming JSON output into an array with JavaScript

Looking for a solution to convert a Json response into an array using JavaScript. I currently have the following json response: ["simmakkal madurai","goripalayam madurai"]. I need to transform these results into an array format. Any suggestions on how I ...

The issue of having the same name for two children in a Google Visualization Org Chart not being

Is there a solution when assigning two sub names (Same name) for the same superior and only one sub level is displayed? <html> <head> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script ...

Tips for boosting performance in PHP when working with extensive arrays

Apologies if my question seems trivial, but I am seeking guidance on how to resolve a particular issue. Currently, I have a large multidimensional array that looks like the following: $array_value = Array ( [0] => Array ...

Bug Alert: Incompatibility between Angular $resource and PHP causing issues with Update and Delete functionalities

As a newcomer to both AngularJS and PHP, I have been struggling to find comprehensive documentation on using $resource to update records in a database. While I did come across a helpful tutorial here that covers most aspects of $resource usage, I am having ...

The getimagesize functionality seems to be malfunctioning

I have developed a function that resizes images to fit as a background image for a div. I provide the function with the div size and the image path. It works perfectly when the height is larger than the width, but it fails when the width is larger than the ...

Issues with jquery ajax php call's functionality restrictions

I'm facing an issue with this ajax call that I copied from a working one. For some reason, it's not successful. Here is the code snippet: $.ajax({ type: "POST", url: "addTune.php", data: { database: setlist, name: tun ...

Launching a new tab in Google Chrome using Selenium for Facebook login with PHP WebDriver

Hey there! I'm diving into the world of Selenium using Facebook's PHP Webdriver and feeling a bit lost. I've been trying to figure out how to open a new tab in Chrome with this technology, but haven't had any luck. Any insights or tips ...

Is there a way to divide a string that has two characters and store each of them in different variables?

I need to extract two characters from an array element by using a substring function. For instance, the value stored in the array element rank_tier is 52. I aim to store 5 into $firstnumber and 2 into $secondnumber. The error message I received is: A ...

What are the steps for incorporating information into a designated PhpMyAdmin account?

Currently, I am experimenting with HTML and Php. The website is quite simple at the moment and lacks adequate security measures. My objective is to update a specific user's competition field in the users table located within the authentication folder ...

Is there a workaround for automatically printing generated PDF files (such as labels and packing slips) from the backend to pre-selected printers directly from a browser?

In the process of creating my web application, I am in need of a solution for automatically printing PDF files (such as labels and packing slips) to pre-selected LAN network printers located in my warehouse from the admin backend. I understand that due to ...

What is the best way to submit a form using Vue Axios in combination with Symfony 4

Need help! I am struggling with sending data from my Vue app to Symfony using axios. Even though I try to send the data, the Symfony request doesn't seem to receive it. Check out my controller code below: $form = $this->createForm(TeacherType::cl ...

Retrieve specific attribute information from the output of a recursive search

In this scenario, we are showcasing how to populate a tree and utilize a table with a parent_id column effectively. The data retrieval process involves the use of a recursive query. $data = [{ "id": 1, "name": "parent 1&qu ...

What is the appropriate method for passing parameters in PHP and how can you handle returned empty values

I'm looking to pass parameters in the action method because I am unable to do so via the header. <form name="mailinglist1" method="post" action="report1.php" > In this form, I'm using a download button to connect my report (HTML). ...