I am new to symfony. I have to make some changes in a existing symfony project, that is hosted in aws in a ec2 instance, with no rds instance. I already clone the project code in my local pc, now where I can find a copy of the database so that I can import that in my phpmyadmin and run the project locally.
How to run a symfony project in localhost
How to override the controller for Symfony4
I want to override the tird-party bundle's controller
in Symfony4.
in this explanation.
It says.
If the controller is a service, see the next section on how to override it. Otherwise, define a new route + controller with the same path associated to the controller you want to override (and make sure that the new route is loaded before the bundle one).
What I want to do is to override this Controller.
myapp/vendor/sonata-project/admin-bundle/src/Controller/CRUDController.php
Now I make CRUDController.php in myapp/src/Controller/CRUDController.php
It doesn't work,, maybe of course though.
However, what should I do next???
Thanks to @DreamOn comment
I made the file myapp/src/Controller/CRUDController.php
<?phpnamespace App\Controller;use Sonata\AdminBundle\Controller\CRUDController as BaseCRUDController;use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;class CRUDController extends BaseCRUDController{}
But, it doesn't work, I guess I should do some routing setting.
Normally SonataAdmonBundle
is routed like this.
routing.yml
admin_area: resource: "@SonataAdminBundle/Resources/config/routing/sonata_admin.xml" prefix: /admin_sonata_admin: resource: . type: sonata_admin prefix: /admin
However Symfony4/3.4 recommend annotation routing.
It makes me confused.
How can I register/routing my Controller?
I use this instead, not override.
How can I configure webpack for use with Symfony 4 projects
I just installed Babel via the command npm install --save @ babel / preset-env
, Once installed, I created a ".babelrc" file at the root and put the following config: {"presets": ["@ babel / preset-env"]}
.
Despite that I get the error below:
WARNING The "callback" argument of configureBabel() will not be used because your app already provides an external Babel configuration (a ".babelrc" file, ".babelrc.js" file or "babel" key in "package.json"). Use null as a first argument to remove that warning. DEPRECATION configureBabel: "include_node_modules" is deprecated. Please use "includeNodeModules" instead. Error: "includeNodeModules" and "exclude" options can't be used together when calling configureBabel().
Symfony 4 How To Access Route From Entity Listener
I have an entity that has an annotation with a listener:
<?phpnamespace App\Entity;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Doctrine\Common\Collections\Criteria;use Doctrine\ORM\Mapping as ORM;/** * @ORM\Entity(repositoryClass="App\Repository\PropertyRepository") * @ORM\EntityListeners({"App\Doctrine\RightMoveDataEvent"}) */class Property extends BaseEntity implements \JsonSerializable}
What i need to be able to do is somehow determine in the postLoad event what the route was that was called in the first place.
The reason being is that i don't want the event to fire on specific routes.
Escaping is not applied in included template using Twig Bundle & Symfony 4.2
I am working on a Symfony 4.2.12 project with Twig bundle installed. Twig escaping strategy is the default 'html' one: I did not change anything about that.
I realized escaping filters |e('html'), |e('html_attr') ... are not applied in a Twig included template whereas in parent template it works normally. Perhaps i have missed something like 'context' as concerns escaping, but this creates a big issue like unwanted xss vulnerability.
Maybe this comes from a loop which calls the included template for each iteration... and escaped variables are not kept in memory, or a kind of that!
Not tested (maybe useless): i'm not sure dynamic variable names for each include could be a way to resolve the issue...
First, i observe default html autoescape is not functional in included template: furthermore a double escaping is also necessary on data to make filters do the job!
For instance, to make filters work in included template i have to declare them as follows by escaping twice: |e|e('html_attr'), etc...
Included template
<!-- Strangely default filter does not work in included template, i have also to use it by escaping twice! -->{{ myVar1|e|e('html') }} <!-- This is not 'html' escaped as it should be! -->{{ myVar1 }} <!-- Please note the necessary double escaping!? --><img src="..." alt="{{ myVar2|e|e('html_attr') }}">
Parent template loop
...<!-- This is correctly 'html' escaped as expected! -->{{ myVar }}<!-- This is correctly 'html_attr' escaped as expected! --><a href="{{ myVar|e('html_attr') }}" ...></a>{% for object in parentObject.objects %} ....{# Obviously, here, any of these passed vars are also correctly escaped with all filters! #} {% include 'my_include.html.twig' with {'myVar1': myValue1,'myVar2': myValue2,'myVar3': myValue3|e('html_attr'), ... } only %} ....{% endfor %}....
I wonder if this is a well known issue, bug (for this Twig bundle version) or a simple personal misunderstanding...
Thank you for your feedbacks!
Referer Redirect in a POST call in symfony 4 using URL with annotations comments Routes
In version symfony 4, I am trying to resolve a redirect in a action done before with a parameter. I Have annotations Routes.
The problem is it is a POST call and I do not know how convert the URL $request->headers->get('referer') in a action_name or how insert the parameters in the call.
$op = 4; //This is an example of a number$response = new RedirectResponse($request->headers->get('referer'),307,$headers=['op'=>$op]);return $response;
or
$op = 4; //This is an example of a number $response = $this->redirect($request->headers->get('referer'));return $response;
Do you know any way resolves this?
symfony 4.0 failed to install assetic-bundle
I'm trying this new symfony 4.0, so I failed to install assetic-bundle,the command I use
composer require assetic-bundle
I got a set of problems :
Updating dependencies (including require-dev)Your requirements could not be resolved to an installable set of packages.Problem 1- symfony/assetic-bundle v2.8.2 requires symfony/framework-bundle ~2.3|~3.0-> satisfiable by symfony/framework-bundle[2.3.x-dev, 2.4.x-dev,/....../ v3.4.0-RC2]but these conflict with your requirements or minimum-stability.
I got four problems like this (I just took the important part of the first because they are very long)my requirements in the json file:
"require": {"php": "^7.1.3","sensio/framework-extra-bundle": "^5.1","sensiolabs/security-checker": "^4.1","symfony/asset": "^4.0","symfony/console": "^4.0","symfony/flex": "^1.0","symfony/framework-bundle": "^4.0","symfony/lts": "^4@dev","symfony/profiler-pack": "^1.0","symfony/twig-bundle": "^4.0","symfony/web-server-bundle": "^4.0","symfony/yaml": "^4.0"},"require-dev": {"symfony/dotenv": "^4.0"},
hearing from you, thanks ^_^
How to config DoctrineMongoDBBundle in symfony 4.0
I am trying to use DoctrineMongoDBBundle
in Symfony 4.0. The only documentation I can find is for Symfony 3.
Symfony 4 has no parameters.yml
or config.yml
.
How can I configure Symfony 4.0 to make the DoctrineMongoDBBundle
work?
Mocking the Symfony HttpClient as a depednecy
I'm using Symfony 4.4.
I have a class into which I inject an instance of Symfony\Component\HttpClient\HttpClient
as a constructor parameter.
I'm looking at the documentation page at https://symfony.com/doc/current/components/http_client.html#testing-http-clients-and-responses where it is suggested to use $client = new MockHttpClient($responses);
as a way to create a Mock client.
When I pass the mocked client to my class I get the error:
TypeError: Argument 3 passed to App\Allocator\Strategy\AbstractStrategy::__construct() must be an instance of Symfony\Component\HttpClient\HttpClient, instance of Symfony\Component\HttpClient\MockHttpClient
How do I obtain a Mock that will satisfy the typing constraint and also allow me to mock up responses?
Foreach FileType in Form : symfony 4.4
I have a list of files (Identity Card, Passport, ....) in my database, and I would like tu create in my "InterimaireType" as many FileType as I have documents.
Controller\InterimaireController
public function add(Request $request, InterimaireManager $interimaireManager, ListeDocumentRepository $listeDocumentRepository) : Response { $listeDocuments = $listeDocumentRepository->findAll(); $form = $this->createForm(InterimaireFormType::class, null, ['data' => $listeDocuments ]); $form->handleRequest($request); return $this->render('interimaire/add.html.twig', ['interimaire_form' => $form->createView(), ]); }
dump "$listeDocuments"
InterimaireController.php on line 81:array:2 [▼ 0 => App\Entity\ListeDocument {#1181 ▼ -id: 16 -libelle: "ID card" -created_at: DateTime @1576461552 {#1178 ▶} -modified_at: DateTime @1588272832 {#1179 ▶} -interimaireFiles: Doctrine\ORM\PersistentCollection {#1245 ▶} } 1 => App\Entity\ListeDocument {#1250 ▼ -id: 17 -libelle: "Driving licence" -created_at: DateTime @1581921759 {#1248 ▶} -modified_at: DateTime @1588272832 {#1249 ▶} -interimaireFiles: Doctrine\ORM\PersistentCollection {#1251 ▶} }]
Form\InterimaireFormType
public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('firstname', TextType::class, [ ]) ->add('lastname', TextType::class, [ ]) ->add('phone', TelType::class, ['required' => false,'attr' => ['class' => 'phone' ] ]) ->add('email', EmailType::class, ['required' => false, ]) ; $listeDocuments = $builder->getData(); if (isset($listeDocuments) && !empty($listeDocuments)) { foreach ($listeDocuments as $key => $listeDocument) { $builder ->add(Urlizer::urlize($listeDocument->getLibelle()), FileType::class, ['label' => $listeDocument->getLibelle(),'mapped' => false,'required' => false,'multiple' => false,'attr' => ['lang' => 'fr', ] ]) ; } } $builder ->add('save', SubmitType::class, ['label' => 'form.interimaire.save.label', ]) ; }
Thank you for your help :)
ps : sorry for my english :p
How to mock the Symfony HttpClient as a dependecy?
I have a class into which I inject an instance of Symfony\Component\HttpClient\HttpClient
as a constructor parameter.
I'm looking at the documentation page at https://symfony.com/doc/current/components/http_client.html#testing-http-clients-and-responses where it is suggested to use $client = new MockHttpClient($responses);
as a way to create a Mock client.
When I pass the mocked client to my class I get the error:
TypeError: Argument 3 passed to
App\Allocator\Strategy\AbstractStrategy::__construct()
must be an instance ofSymfony\Component\HttpClient\HttpClient
, instance ofSymfony\Component\HttpClient\MockHttpClient
received.
How do I obtain a Mock that will satisfy the typing constraint and also allow me to mock up responses?
Symfony 4 Form Builder EntityType Field "not a valid class" error
I am trying to add Select form field by using values in DB table. In the official documentation it is described as in the picture below:
I did implemented in the same way but I am getting Expection:
The "App\Entity\Definition" entity has a repositoryClass set to "App\Entity\DefinitionRepository", but this is not a valid class. Check your class naming. If this is meant to be a service id, make sure this service exists and is tagged with "doctrine.repository_service".
My FormType code:
namespace App\Form;use App\Entity\Company;use App\Entity\Definition;use Doctrine\ORM\EntityRepository;use Symfony\Bridge\Doctrine\Form\Type\EntityType;use Symfony\Component\Form\AbstractType;use Symfony\Component\Form\FormBuilderInterface;use Symfony\Component\OptionsResolver\OptionsResolver;class CompanyDetailType extends AbstractType{ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('name', null, ['label' => 'Company Name']) ->add('type', EntityType::class, ['class' => Definition::class,'query_builder' => function (EntityRepository $er) { return $er->createQueryBuilder('d'); },'choice_label' => 'name','label' => 'Company Type' ]); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(['data_class' => Company::class, ]); }}
My DefinitionRepository:
namespace App\Repository;use App\Entity\Definition;use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;use Doctrine\Persistence\ManagerRegistry;class DefinitionRepository extends ServiceEntityRepository{}
the $type field of Company Entity:
/** * @var Definition * * @ORM\ManyToOne(targetEntity="App\Entity\Definition") */private $type;
Symfony 4 : How to delete a file from folder using remove function of the filesystem component
I am trying to remove a file from folder using remove function of the filesystem component in Symfony 4.
Here is my code in the controller:
//Get old logo$oldlogo = $employer->getLogo();//If there is a old logo we need to detele it if($oldlogo){ $filesystem = new Filesystem(); $path=$this->get('kernel')->getProjectDir().'/public/uploads/logos/'.$oldlogo; $filesystem->remove($path); }
I get error message:
Service "kernel" not found
I am in Symfony version 4.4. I also tried :
$path=$this->kernelRoot.'/public/uploads/logos/'.$oldlogo;
and in this case I get error message:
Notice: Undefined property: App\Controller\DashboardController::$kernelRoot
Symfony 4.4 : How to embed a form in a Bootstrap modal?
I need to embed a form in a pop-up.
I created a formType, a controller and a TWIG view containing the whole page to display and the popup form.
I mapped my form in the popup, everything is well displayed but nothing happen when I clic on submit button. It seems that the submit is not detected when embedded in a popup.
Here is my form:
namespace App\Form; class MessageType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('text', TextareaType::class, ['attr' =>['class'=>'with-border','cols'=> '10','placeholder'=> 'Message','name'=> 'textarea', ], ]) ->add('save', SubmitType::class, ['attr' =>['class'=>'button margin-top-35 full-width button-sliding-icon ripple-effect'], ]) ; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(['data_class' => Message::class, ]); } }
Here is the part of the controller related to the form:
namespace App\Controller;class FreelancerprofileController extends AbstractController{/*** @Route("/freelancer/profile/{id}", name="freelancerprofile",requirements={"id" = "\d+"})*/public function index($id, Request $request){ $message = new Message();$form = $this->createForm(MessageType::class, $message); if ($form->isSubmitted() && $form->isValid()) { $user = $this->getUser(); $receiver = $freelancer->getUser(); $messagetext = $form['message']->getData(); $message->setUser($user); $message->setReceiver($receiver); $message->setText($messagetext); $message->setCreationdate(new \DateTime('now')); return $this->render('freelancer/profile.html.twig', array( //'freelancers' => $freelancers, )); } return $this->render('freelancer/profile.html.twig', ['message' => $form->createView(), ]);}}
And this is the modal included in the TWIG view:
<!-- Message Popup ================================================== --><div id="small-dialog" class="zoom-anim-dialog mfp-hide dialog-with-tabs"><!--Tabs --><div class="sign-in-form"><ul class="popup-tabs-nav"><li><a href="#tab">Contact</a></li></ul><div class="popup-tabs-container"><!-- Tab --><div class="popup-tab-content" id="tab"><!-- Welcome Text --><div class="welcome-text"><h3>Send message</h3></div> {{ form_start(message) }}<!-- Form --><form method="post"> {{ form_widget(message.text) }}</form><!-- Button --> {{ form_widget(message.save) }} {{ form_end(message) }}</div></div></div></div></div><!-- Message Popup / End -->
symfony4: There is no extension able to load the configuration for "doctrine_mongodb"
I have an issue to configure doctrine odm with Symfony4.1
I got an error message on composer update, cache:clear subcommand
There is no extension able to load the configuration for"doctrine_mongodb" (in /home/thomas/Documents/dev/blade/vm_api/config/packages/doctrine.yaml). Looked for namespace "doctrine_mongodb", found "framework"
My composer.json look ok
{"type": "project","license": "proprietary","require": {"php": "^7.1.3","ext-ctype": "*","ext-iconv": "*","alcaeus/mongo-php-adapter": "^1.1.5","doctrine/mongodb-odm": "^1.2.4","doctrine/mongodb-odm-bundle": "^3.5","mongodb/mongodb": "1.3.2","symfony/console": "*","symfony/flex": "^1.1","symfony/framework-bundle": "*","symfony/yaml": "*" },"require-dev": {"symfony/dotenv": "*" },"config": {"preferred-install": {"*": "dist" },"sort-packages": true },"autoload": {"psr-4": {"App\\": "src/" } },"autoload-dev": {"psr-4": {"App\\Tests\\": "tests/" } },"replace": {"paragonie/random_compat": "*","symfony/polyfill-ctype": "*","symfony/polyfill-iconv": "*","symfony/polyfill-php71": "*","symfony/polyfill-php70": "*","symfony/polyfill-php56": "*","symfony/symfony": "*" },"scripts": {"auto-scripts": {"cache:clear": "symfony-cmd","assets:install %PUBLIC_DIR%": "symfony-cmd" },"post-install-cmd": ["@auto-scripts" ],"post-update-cmd": ["@auto-scripts" ] },"conflict": {"symfony/symfony": "*" }}
And the configuration file is with the "normal" parameters
parameters: # Adds a fallback DATABASE_URL if the env var is not set. # This allows you to run cache:warmup even if your # environment variables are not available yet. # You should not need to change this value. env(DATABASE_URL): ''doctrine_mongodb: #default_commit_options: ~ default_database: "%env(DATABASE_NAME)%" connections: default: server: "%env(DATABASE_HOST)%" options: username: "%env(DATABASE_USER)%" password: "%env(DATABASE_PASSWORD)%" authSource: "%env(DATABASE_AUTH_SOURCE)%" ssl: "%env(DATABASE_SSL%" replicaSet: "%env(DATABASE_REPLICA_SET)%" document_managers: default: mappings: DocumentBundle: type: annotation dir: Document/
I'am new with 4.1, and maybe I did something wrong
Thanks in advance
Symfony 4, how get the root path directory (or /src path) properly from a Service Class ? ( error : 'Call to a member function get() on null')
In Symfony 4, from a controller I can get the root path of my project via :
// From a Controller Class, in the src/Controller diruse Symfony\Bundle\FrameworkBundle\Controller\Controller;// ...Class myController extends Controller{// ...// in a public method$rootDir = $this->get('kernel')->getRootDir();
But how can I get the root path from a Service Class ? I tried this (ugly) way
// From a Service Class, in the src/Service diruse Symfony\Bundle\FrameworkBundle\Controller\Controller;// ...Class myService extends Controller{// ...// in a public method$rootDir = $this->get('kernel')->getRootDir();
But when I did that, I get the error :
"Call to a member function get() on null"
Why this solution does not work?
Symfony 5.0.8 weird issue when updating a simple entity
Here is my entity:
<?phpnamespace App\Entity\Contact;use Doctrine\ORM\Mapping as ORM;use Symfony\Component\Validator\Constraints as Assert;/** * @ORM\Entity * @ORM\Table(name="contact_contact") */class Contact{ /** * @ORM\Id * @ORM\Column(type="integer", options={"unsigned":true}) * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @Assert\NotBlank * @ORM\Column(type="string", length=40, nullable=true) */ private $fname; /** * @ORM\Column(type="string", length=40, nullable=true) */ private $lname; public function getId(): ?int { return $this->id; } public function getFname(): ?string { return $this->fname; } public function setFname(string $fname): self { $this->fname = $fname; return $this; } public function getLname(): ?string { return $this->lname; } public function setLname(?string $lname): self { $this->lname = $lname; return $this; }}
Here is the edit controller action code:
/** * @Route("/{id}/edit", name="contact_contact_edit", methods={"GET","POST"}) */public function edit(Request $request, Contact $contact): Response{ $form = $this->createForm(ContactType::class, $contact); $form->handleRequest($request); if ($form->isSubmitted()) { if ($form->isValid()) { $this->getDoctrine()->getManager()->flush(); } } return $this->render('contact/contact/edit.html.twig', ['contact' => $contact,'form' => $form->createView(), ]);}
When I post the form but leave the fname (first name) field empty...I get this error (Symfony\Component\PropertyAccess\Exception\InvalidArgumentException)
Expected argument of type "string", "null" given at property path"fname".
When creating the entity, the @Assert works as expected and the message says so...but if I leave it blank and update post...bzzzt error.
What am I missing?
EDIT | Here is the form class incase thats doing something?
<?phpnamespace App\Form\Contact;use App\Entity\Contact\Contact;use Symfony\Component\Form\AbstractType;use Symfony\Component\Form\Extension\Core\Type\TextType;use Symfony\Component\Form\FormBuilderInterface;use Symfony\Component\OptionsResolver\OptionsResolver;class ContactType extends AbstractType{ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('fname', TextType::class, ['label' => 'First Name']) ->add('lname', TextType::class, ['label' => 'Last Name']); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(['data_class' => Contact::class,'min_entry' => false, // NOTE: Must be added to every form class to disable HTML5 validation'attr' => ['novalidate' => 'novalidate'] ]); $resolver->setAllowedTypes('min_entry', 'bool'); }}
how to import typeahead.js webpack symfony
I've lost many time to find a solution of "how to import Typeahead.js by Webpack encore symfon y 4 ", so I hope this may save your time.
require('imports-loader?define=>false!typeahead.js/dist/typeahead.jquery.min.js');const Bloodhound = require('imports-loader?define=>false!typeahead.js/dist/bloodhound.min.js');
app.js:336 Uncaught TypeError: $(...).typeahead is not a function
How to start local server with symfony 5 or downgrade version to 4.4?
I started a new project in new Symfony 5 and i can't open my local server.
On Symfony 4.4 the command PHP bin/console server:run
is OK,
But with Symfony 5 the command appears not to be defined...
C:\Users\Chris\Code\api-test> php bin/console server:runCommand "server:run" is not defined.Do you want to run "server:dump" instead? (yes/no) [no]:
So how to downgrade or start the local server?
Upgrading Symfony 3.4 to 4.x with Flex - Composer Problems
I have a Symfony 3.4 project I'm trying to upgrade to 4.x with Flex but I'm falling at the first hurdle.
With the output of Composer this verbose I assume the answer is staring me straight in the face, but I'm not seeing it. What do I need to do? I've deleted everything in vendor, deleted my composer.lock file, cleared composer cache, etc.
composer.json
{"type": "project","license": "proprietary","require": {"php": "^7.1.3","ext-ctype": "*","ext-iconv": "*","sensio/framework-extra-bundle": "^5.5","symfony/console": "4.4.*","symfony/dotenv": "4.4.*","symfony/flex": "^1.3.1","symfony/framework-bundle": "4.4.*","symfony/monolog-bundle": "^3.5","symfony/orm-pack": "^1.0","symfony/profiler-pack": "^1.0","symfony/twig-pack": "^1.0","symfony/yaml": "4.4.*","friendsofsymfony/jsrouting-bundle": "^2.5","friendsofsymfony/user-bundle": "~2.0","stof/doctrine-extensions-bundle": "^1.3","symfony/swiftmailer-bundle": "^2.6.4","ext-json": "*" },"require-dev": {"symfony/debug-pack": "^1.0","phpstan/extension-installer": "^1.0","phpstan/phpstan": "^0.12.19","phpstan/phpstan-doctrine": "^0.12.10","phpunit/phpunit": "^7.5","symfony/phpunit-bridge": "^3.0" },"config": {"preferred-install": {"*": "dist" },"sort-packages": true },"autoload": {"psr-4": {"App\\": "src/" } },"autoload-dev": {"psr-4": {"App\\Tests\\": "tests/" } },"scripts": {"auto-scripts": {"cache:clear": "symfony-cmd","assets:install %PUBLIC_DIR%": "symfony-cmd" },"post-install-cmd": ["@auto-scripts" ],"post-update-cmd": ["@auto-scripts" ] },"extra": {"symfony": {"allow-contrib": false,"require": "4.4.*" } }}
Tried to composer install with:
php -d memory_limit=-1 /usr/local/bin/composer install
And it spews all this out (too big to paste here): https://pastebin.com/KLVRkYdF
Saw something elsewhere about needing to install Flex on its own first, so I tried this:
php -d memory_limit=-1 /usr/local/bin/composer update symfony/flex --no-plugins --no-scripts
But got the following error (too big to paste here): https://pastebin.com/KxG2siZi