Symfony 4 Using Wrong Namespace When Making Entity
I've run into this issue a few times actually, when using php bin/console make:entity it uses the wrong namespace for the ManagerRegistry in the repository.
This is what it put in there:
use Doctrine\Persistence\ManagerRegistry;
Which then gives the following error:
Cannot autowire service "App\Repository\PrivateCallBookingAvailabilityRepository": argument "$registry" of method "__construct()" has type "Doctrine\Persistence\Manage
rRegistry" but this class was not found.
Looking at other repositories it doesn't always do this, the ones that work actually use:
use Doctrine\Common\Persistence\ManagerRegistry;
Any idea why it's doing that?
1 answer
-
answered 2021-01-25 20:10
greeflas
You need to downgrade version of
symfony/maker-bundle
becauseDoctrine\Common\Persistence\ManagerRegistry
was renamed toDoctrine\Persistence\ManagerRegistry
in Doctrine and looks like your Doctrine version has old name of this class.Also as an option you can update Doctrine to newest version.
More details you can find here https://github.com/symfony/maker-bundle/pull/518.
See also questions close to this topic
-
should I put redis GET/SET in the models?
I'm trying to apply Redis in my HMVC codeigniter project. If I understand correctly, controllers should contain code for "controlling" data and models should only contain database process. but this project already has quite many modules and methods, and Redis is also a kind of database structure.
Do you think it's better to put Redis' GET and SET process in the models so that all the controllers that uses the methods will always use Redis, or should I put those Redis process in the controllers instead and risk having a "miss" here and there in the many controllers?
-
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'id' cannot be null (SQL: insert into `tbl_studentmains`)
I am getting this error when I pass values from one page to another with the same id from but I get the following error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'id' cannot be null (SQL: insert into
tbl_studentmains
(id
,Name
,Father_Name
,Student_CNIC
,Father_CNIC
,DOB
,Nationality_ID
,NativeLanguage_ID
,District_ID
,Caste_ID
,Religion_ID
,Marital_Status
,Email
,PresentAddress
,PresentResidingPlace_ID
,PermanentAddress
,StudentContactNoPersonal
,ContactResidence
,Em_name
,Em_Relationship
,Em_Contact
,Em_Residence
,Em_Address
,FG_Occupation_ID
,Monthly_income
,StudentDistinctionYesNo
,Designation
,Name_of_Employer
,EmployerContactNo
,updated_at
,created_at
) values (?, Dilawar Naseem, Shahab Naseem, 5440022939451, 5440022939459, 2021-03-08, Pakistani, Punjabi, Quetta, Sheikh, Islam, Single, dilawarnaseem@yahoo.com, Plot #17 gulbagh, Quetta, Plot #17 gulbagh, 03318042227, 03318042227, Shahab Naseem, Father, 03337826049, 0812872038, Plot #17 gulbagh, Father, 5000, Yes, Intern, Dilawar Naseem, 08122315, 2021-03-08 05:57:26, 2021-03-08 05:57:26))here is my Controller:
<?php namespace App\Http\Controllers; use Validator; use App\Models\tbl_studentmains; use App\Models\tbl_studenteducations; use Illuminate\Http\Request; use Illuminate\Support\Facades\Session; class StudentMainController extends Controller { public function StudentMain(Request $request) { $tbl_studentmains = new tbl_studentmains; $tbl_studentmains->id = $request->id; $tbl_studentmains->Name = $request->Name; $tbl_studentmains->Father_Name = $request->Father_Name; $tbl_studentmains->Student_CNIC = $request->Student_CNIC; $tbl_studentmains->Father_CNIC = $request->Father_CNIC; $tbl_studentmains->DOB = $request->DOB; $tbl_studentmains->Nationality_ID = $request->Nationality_ID; $tbl_studentmains->NativeLanguage_ID = $request->NativeLanguage_ID; $tbl_studentmains->District_ID = $request->District_ID; $tbl_studentmains->Caste_ID = $request->Caste_ID; $tbl_studentmains->Religion_ID = $request->Religion_ID; $tbl_studentmains->Marital_Status = $request->Marital_Status; $tbl_studentmains->Email = $request->Email; $tbl_studentmains->PresentAddress = $request->PresentAddress; $tbl_studentmains->PresentResidingPlace_ID = $request->PresentResidingPlace_ID; $tbl_studentmains->PermanentAddress = $request->PermanentAddress; $tbl_studentmains->StudentContactNoPersonal = $request->StudentContactNoPersonal; $tbl_studentmains->ContactResidence = $request->ContactResidence; $tbl_studentmains->Em_name = $request->Em_name; $tbl_studentmains->Em_Relationship = $request->Em_Relationship; $tbl_studentmains->Em_Contact = $request->Em_Contact; $tbl_studentmains->Em_Residence = $request->Em_Residence; $tbl_studentmains->Em_Address = $request->Em_Address; $tbl_studentmains->FG_Occupation_ID = $request->FG_Occupation_ID; $tbl_studentmains->Monthly_income = $request->Monthly_income; $tbl_studentmains->StudentDistinctionYesNo = $request->StudentDistinctionYesNo; $tbl_studentmains->Designation = $request->Designation; $tbl_studentmains->Name_of_Employer = $request->Name_of_Employer; $tbl_studentmains->EmployerContactNo = $request->EmployerContactNo; $rules = [ 'Name' => 'required|string', 'Father_Name' => 'required|string', 'Student_CNIC' =>'required|numeric', 'Father_CNIC' =>'required|numeric', 'DOB' =>'required|string', 'Nationality_ID' => 'required|string', 'NativeLanguage_ID' => 'required|string', 'District_ID' => 'required|string', 'Caste_ID' => 'required|string', 'Religion_ID' => 'required|string', 'Marital_Status' => 'required|string', 'Email' => 'required|email', 'PresentAddress' => 'required|string', 'PresentResidingPlace_ID' => 'required|string', 'PermanentAddress' => 'required|string', 'StudentContactNoPersonal' => 'required|numeric', 'ContactResidence' => 'required|numeric', 'Em_name' => 'required|string', 'Em_Relationship' => 'required|string', 'Em_Contact' =>'required|numeric', 'Em_Residence' =>'required|numeric', 'Em_Address' =>'required|string', 'FG_Occupation_ID' => 'required|string', 'Monthly_income' => 'required|numeric', 'StudentDistinctionYesNo' => 'required|string', 'Designation' => 'required|string', 'Name_of_Employer' => 'required|string', 'EmployerContactNo' => 'required|numeric', ]; $this->validate($request, $rules); $tbl_studentmains->save(); session()->put('id',$tbl_studentmains->id); return view ('/StudentEducation_form',compact('tbl_studentmains')); } public function StudentEducation(Request $request) { $tbl_studenteducations = new tbl_studenteducations; $tbl_studenteducations->ExaminationPassed_ID = $request->ExaminationPassed_ID; $tbl_studenteducations->SchoolCollege_ID = $request->SchoolCollege_ID; $tbl_studenteducations->Board_University_ID = $request->Board_University_ID; $tbl_studenteducations->RegistrationNo = $request->RegistrationNo; $tbl_studenteducations->Year = $request->Year; $tbl_studenteducations->AnnualSupplementary = $request->AnnualSupplementary; $tbl_studenteducations->RollNo = $request->RollNo; $tbl_studenteducations->MarksObtained = $request->MarksObtained; $tbl_studenteducations->TotalMarks = $request->TotalMarks; $tbl_studenteducations->Subject_ID = $request->Subject_ID; $tbl_studenteducations->std_id = session()->get('id'); $tbl_studenteducations->save(); $tbl_studenteducations = tbl_studenteducations::all(); return view ('/StudentEducation_form',compact('tbl_studenteducations')); } public function index(Request $request) { $tbl_studenteducations = tbl_studenteducations::all(); return view ('/StudentEducation_form',compact('tbl_studenteducations')); } }
Please suggest any solution
-
Want to make searchbar which carries results of any other websites
I want to make a search bar on my (PHP) web which actually search bar of another website and carries out its result..... E.g like google search bar... Show google results in my web
-
Symfony Doctrine one-to-many returns empty collection
I have three models:
User
(created with themake:user
command),FooUser
(representing a user of a third-party app), andSubmission
(representing the submissions of aFooUser
).FooUser
has a one-to-many relation withSubmission
, and a many-to-many relation toUser
.class FooUser { // ... /** * @ORM\OneToMany(targetEntity=Submission::class, mappedBy="user") * @ORM\OrderBy({"id" = "DESC"}) */ private $submissions; /** * @ORM\ManyToMany(targetEntity=User::class, mappedBy="foouser") */ private $users; // ... } class Submission { // ... /** * @ORM\ManyToOne(targetEntity=FooUser::class, inversedBy="submissions") * @ORM\JoinColumn(nullable=false) */ private $user; // ... }
In the
submissions
table the user column is calleduser_id
.The problem: When I call
$fooUser->getSubmissions()
it returns an empty collection. Similarly,$fooUser->getSubmissions()->count()
it returns0
. This despite the fact that there are submissions for thisFooUser
in the database. Is there anything obviously wrong with the way the relations are set up? -
Codeception: How to stub return of a function in a Symfony module
I need to write APItests for a project(on Symfony) using Codeception. My API test is functional and using Symfony+REST modules. The Api method I'm testing uses an external service call. I just stub the response of the class method, but the stub does not work and the real class method is called. What do I need to fix in my test code or maybe I need to use another way?
Config codeception.yml
namespace: App\Tests paths: tests: tests output: tests/_output data: tests/_data support: tests/_support envs: tests/_envs actor_suffix: Tester bootstrap: codeception_bootstrap.php extensions: enabled: - Codeception\Extension\RunFailed params: - .env.test
Config api.suite.yml
actor: ApiTester modules: enabled: - Symfony: app_path: 'src' environment: 'test' - Doctrine2: depends: Symfony cleanup: true - REST: url: /api/v1/ depends: Symfony - \App\Tests\Helper\Api
Test code /tests/api/TestCest.php
namespace App\Tests\Api; use App\Tests\ApiTester; class TestApiCest extends BaseApiCest { public function addMetrics(ApiTester $I) { $this->mockB2bService($I); $I->sendPost('/request', $body); $I->seeResponseCodeIs(201); } }
Code for stubing
/tests/_support/Helper/ApiHelper.php
namespace App\Tests\Helper; use Codeception\Module; use Symfony\Component\DependencyInjection\ContainerInterface; class ApiHelper extends Module { public function getContainer(): ContainerInterface { /** @var Module\Symfony $symfony */ $symfony = $this->getModule('Symfony'); return $symfony->kernel->getContainer(); } }
/api/BaseApiCest.php
namespace App\Tests\Api; use App\Module\Service\B2BService\B2bResponse; use App\Tests\ApiTester; use App\Tests\Helper\ApiHelper; use Codeception\Stub; abstract class BaseApiCest { protected ApiHelper $apiHelper; protected function _inject(ApiHelper $apiUser) { $this->apiHelper = $apiUser; } protected function mockB2bService(ApiTester $I): void { $container = $this->apiHelper->getContainer(); $serviceId = '\App\Module\Service\B2BService\B2bService'; $auth = Stub::make( \App\Module\Service\B2BService\B2bService::class, [ 'createSomeActive' => new B2bResponse(['success' => true, 'message' => '', 'code' => 200]) ]); $container->set($serviceId, $auth); $I->persistPermanentService($serviceId); }
Class I try to stub
/src/Module/Service/B2bService.php
class B2bService implements B2bServiceInterface { public function createSomeActive(SomeParams $params): B2bResponse { $response = $this->httpClient->post('/somerequest', $requestBody); $decodedResponse = $this->jsonDecodeResponse($response); return $decodedResponse; //if sucsess then return ['success' => true, 'message' => '', 'code' => 200] } }
-
symfony PHPUnit problem installation Xdebug for --coverage-html
i want to do
--coverage-html
command with PHPUnit for a project but i think i need to install Xdebug but I can't. I run php 7.3 and I'm on Mac. Suddenly when I runphp bin/phpunit --coverage-html web/test-coverage
, he tells meerror: No code coverage driver is available
so I try to install Xdebug, I runpecl install xdebug
but, he tells meCannot install, php_dir for channel "pecl.php.net" is not writeable by the current user
.I try to do this pecl config-set php_dir /path/to/new/dir and it does not work or I put a wrong path.
I try also with sudo but don't work
and I think my php.ini file is good.
if you have any info i'm a taker!
thank you in advance
-
Doctrine Many to Many relationship causing issues with doctrine:schema:update
I have a simple bidirectional many-to-many relationship between users and courses defined as the following:
CREATE TABLE `user_course` ( `user_id` int NOT NULL, `course_id` int NOT NULL, PRIMARY KEY (`user_id`,`course_id`), CONSTRAINT `user_course_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`), CONSTRAINT `user_course_ibfk_2` FOREIGN KEY (`course_id`) REFERENCES `course` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
User entity:
/** * Many Users have many Courses * @ORM\ManyToMany(targetEntity="Course", inversedBy="users") * @ORM\JoinTable(name="user_course") */ private $courses;
Course entity:
/** * Many Courses have many Users * @ORM\ManyToMany(targetEntity="User", mappedBy="courses") */ private $users;
When attempting to ensure the entity definitions are in sync with the database schema, I am running the command:
php bin/console doctrine:schema:update --dump-sql
The issue is that the output of this command is the following:
ALTER TABLE user_course DROP FOREIGN KEY user_course_ibfk_1; ALTER TABLE user_course DROP FOREIGN KEY user_course_ibfk_2; ALTER TABLE user_course DROP FOREIGN KEY user_course_ibfk_2; ALTER TABLE user_course ADD CONSTRAINT FK_73CC7484A76ED395 FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE; ALTER TABLE user_course ADD CONSTRAINT FK_73CC7484591CC992 FOREIGN KEY (course_id) REFERENCES course (id) ON DELETE CASCADE; CREATE INDEX IDX_73CC7484591CC992 ON user_course (course_id); ALTER TABLE user_course ADD CONSTRAINT user_course_ibfk_2 FOREIGN KEY (course_id) REFERENCES course (id);
What is the actual discrepancy between the schema and entity mapping and how can it be resolved?
-
querybuilder for a many-to-many relationship throws QueryException, why?
I'm trying to select all entities for which a property of a m-2-m relation exists.
$qb = $this->entityManager ->createQueryBuilder() ->select('attachment') ->from(Attachment::class, 'attachment') ->join('attachment.orders', 'order'); print $qb->getQuery()->getSQL(); // SELECT d0_.meta AS meta_0, d0_.type AS type_1, d0_.attachment_id AS attachment_id_2, d0_.dossier_id AS dossier_id_3 FROM dossier_attachment d0_ INNER JOIN dossier_order_attachment d2_ ON d0_.attachment_id = d2_.attachment_id INNER JOIN dossier_order d1_ ON d1_.order_id = d2_.order_id
That seems to correct sql for my many-2-many tables.
However as soon as I add a where clause to limit the attachments returned I get an QueryException. As I hav eplayed with this for over two hours, I'm asking why the exception and how would I fix it?
{ "line" : 457, "class" : "Doctrine\\ORM\\Query\\QueryException", "file" : "/home-projects/api-plhw-development/deploy/releases/20210222110730UTC/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php", "function" : "dqlError", "type" : "::", "args" : [ "SELECT attachment FROM HF\\Model\\Entity\\Dossier\\Attachment attachment INNER JOIN attachment.orders order WHERE order.orderId = :orderId" ] }, { "line" : 2679, "file" : "/home-projects/api-plhw-development/deploy/releases/20210222110730UTC/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php", "class" : "Doctrine\\ORM\\Query\\Parser", "function" : "syntaxError", "type" : "->", "args" : [ "Literal" ] }, { "type" : "->", "args" : [], "class" : "Doctrine\\ORM\\Query\\Parser", "function" : "Literal", "file" : "/home-projects/api-plhw-development/deploy/releases/20210222110730UTC/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php", "line" : 2863 }, { "args" : [], "type" : "->", "file" : "/home-projects/api-plhw-development/deploy/releases/20210222110730UTC/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php", "class" : "Doctrine\\ORM\\Query\\Parser", "function" : "ArithmeticPrimary", "line" : 2801 },
-
Model with ManyToMany relationship not persisted with Doctrine in symfony when updated
I try to update a model, but this last one is not persisted when calling flush() from entityManager.
The code is as follow
/** * @ORM\ManyToMany(targetEntity=GroupBase::class, inversedBy="baseUsers", cascade={"persist"}) */ private $GroupBase;
// this is the variable used in the entity GroupBase /** * @ORM\ManyToMany(targetEntity=BaseUser::class, mappedBy="GroupBase", cascade={"persist"}) */ private $baseUsers;
// this is the Entity GroupBase, which should contain a collection of User public function addBaseUser(BaseUser $baseUser): self { if (!$this->baseUsers->contains($baseUser)) { $this->baseUsers[] = $baseUser; $baseUser->addGroupBase($this); } return $this; }
// this methods is the one that insert Users in the GroupBase Collection public function insertUsersGroup(LdapUser $ldapUser, GroupBase $groupBase){ /** * this methods aim to insert all Users that belong to group Members into GroupBase */ $dn = $ldapUser->getDistinguishedName(); $members = $groupBase->getMembers(); if(in_array($dn, $members)){ $groupBase->addBaseUser($ldapUser); $ldapUser->addGroupBase($groupBase); } return $groupBase; }
this is the controller that insert Users in groups
/** * @Route("group/insertUsersGroup") */ public function insertUsersInGroup(){ $entityManager = $this->getDoctrine()->getManager(); $ldapUsers = $entityManager->getRepository(LdapUser::class)->findAll(); $groupBase = $entityManager->getRepository(GroupBase::class)->findAll(); foreach($groupBase as $group){ foreach($ldapUsers as $user){ $this->service->insertUsersGroup($user, $group); try{ $entityManager->persist($group); $entityManager->flush(); $response = "model saved"; } catch(Exception $e){ throw $e; } } } return new Response( $response ); }
If I call the methods $groupBase->getBaseUsers() before persisting data it show me that my users are here, and don't throw any error. But it seems data is not persisted after $entitymanager->flush()
-
Doctrine ORM geting foreign entity by non primary key
I am trying to reference foreign entity by no primary key
I have a table I may not alter due to compatibility reason and other out of my control. It is a simple locale/country with primary auto increment, unique code like 'us' and other non-relevant fields.
There was no doctrine on the project until now and some of the tables in the project reference this by id, some by code
I would like to reference this entity like this:
/** * @ORM\ManyToOne(targetEntity="Country") * @ORM\JoinColumn(name="country", referencedColumnName="code") * * @var Country */ private $countryEntity;
some other entities do use id instead. I cannot use
@ORM\Id
on both as I would need both to query it. I do not want to use second query to fetch Country entity. I need to preserve both id and code. -
Self referencing addReference getRegerence in the same fixture
I have a simple question about Fixtures in Symfony and Doctrine. I have an Entity "Project" and I would like to self-referencing this project. For example I tried this :
$project1 = new Question(); $this->addReference("initiatives", $project1); //referencing $project1->setItem('Project Initiatives'); $project1->setInverse(false); $project1->setProjectHead($this->getReference("initiatives")); // get the reference of himself $manager->persist($project1);
My entity (extract) :
/** * @ORM\ManyToOne(targetEntity=Project::class, inversedBy="projects") */ private $project_head; /** * @ORM\OneToMany(targetEntity=Project::class, mappedBy="project_head") */ private $projects; public function setProjectHead(?self $project_head): self { $this->project_head = $project_head; return $this; }
But It does not work. I have this error : SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails
I have juste ONE lign in my db. I think he can't UDPATE because when I try to add others fixtures, the message apear. But I don't know how to fix this.
Thanks a lot for helping
-
When is the order object introduced in the Database?
I'm starting in Prestashop, and i need to know in exactly what .php file an Order is introduced in the Database after you pay and everything.
-
Invalid data "client" (integer), expected "Entity" JsonDeserializationVisitor.php line 162
Recently upgraded a Symfony app from 3.4 to 4.4 and along with that upgraded
jms/serializer-bundle
from2.1.0
to3.8.0
and with that came this error message[2021-03-04 16:55:46] request.CRITICAL: Uncaught PHP Exception JMS\Serializer\Exception\RuntimeException: "Invalid data "client" (integer), expected "App\Entity\Report\Report"." at /var/www/vendor/jms/serializer/src/JsonDeserializationVisitor.php line 162 {"exception":"[object] (JMS\Serializer\Exception\RuntimeException(code: 0): Invalid data "client" (integer), expected "App\Entity\Report\Report". at /var/www/vendor/jms/serializer/src/JsonDeserializationVisitor.php:162)"} []
Now I'm near the end of the upgrade but this one issue is stopping me from making any progress and it's something to do with the way our app works with JMS.
The repo I'm working on is public UK Government application located here https://github.com/ministryofjustice/opg-digideps/pull/593/files
-
Symfony4.4: CSV output is not possible
I updated the app from Symfony 3.4 to 4.4 and verified the operation.
The function to output csv does not work, and when I press the button, the page redirects.
It is implemented by the method of the link below, but the official document is only up to 4.2.
Is there an alternative to 4.2 or later?https://symfony.com/doc/4.1/templating/formats.html
Controller
/** * @Route("/", defaults={"_format"="html"}, requirements={"_format"="html|csv"}) * @Method("GET") * * @Template("@AppBundle/Hq/Post/index.html.twig") */ public function indexAction(Request $request) { if ($request->getRequestFormat() == 'html') { // At the time of html output } elseif ($request->getRequestFormat() == 'csv') { // At the time of csv output // Set file name, no pagination $request->attributes->set('filename', 'post_article.csv'); }
index.html.twig
<button type="submit" class="btn" name="_format" value="csv"> <i class="icon-download"></i> CSV output </button>
CsvListener
class CsvResponseListener { /** * kernel.response Set the response at the time of CSV output in the event */ public function onKernelResponse(FilterResponseEvent $event) { $request = $event->getRequest(); $response = $event->getResponse(); // Set the response at the time of CSV output in the event if ($request->getRequestFormat() === 'csv' && $response->getStatusCode() == 200) { // Convert response body to CRLF, SJIS-WIN $content = str_replace("\n", "\r\n", $response->getContent()); $content = mb_convert_encoding($content, 'SJIS-WIN', 'UTF-8'); $response->setContent($content); // Get the file name $filename = $request->attributes->get('filename', 'download.csv'); // Set header for file download $response->headers->set('Content-Type', 'application/octet-stream'); $response->headers->set('Content-Transfer-Encoding', 'binary'); $response->headers->set('Content-Disposition', 'attachment; filename="'.$filename.'"'); $response->headers->set('Content-Length', strlen(bin2hex($content)) / 2); } } }
services.yaml
app.listener.csvResponseListener: class: AppBundle\Listener\CsvResponseListener tags: - { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }
-
Doctrine - multiple conditions
I would like to write doctrine query which will return
true
if it finds selected id with three different statuses like:$query = $this->createQueryBuilder('e'); $query ->select($query->expr()->countDistinct('e.id')) ->where('e.workspaceId =:workspaceId') ->andWhere("e.status IN(:statuses)") ->setParameter('workspaceId', $workspaceId) ->setParameter('statuses', array_values($statuses)) ->groupBy('e.id') ->getQuery() ->getSingleScalarResult(); if ($query === 3) { return true; } else { return false; }
If one of the combinations is not found like, for example, given id and second status, than it will be returned false..
This is my try as I can not find right approach to do that. Example with be do to id with findBy() in separate methods but I would like to find solution that can be inputed in one method with query builder.