Quantcast
Channel: Active questions tagged symfony4 - Stack Overflow
Viewing all 3924 articles
Browse latest View live

Symfony login_check route not found

$
0
0

I am trying to run login_check post action on user login and I keep getting no route found error:

No route found for "POST /login_check" (from "http://pmp.local/login")

My security.yaml looks like this:

login_firewall:    pattern:   ^/login$    anonymous: ~secured_area:    pattern: ^/    form_login:        check_path: login_check        login_path: login_form        default_target_path: /products    logout:        path: logout        target: login_form

Pattern for secured_area is / so I try to post the form to /login_check:

<form method="post" action="/login_check">

What could be wrong?

Everything works if I define an empty controller with login_check route like:

/** * @Route("/login_check", name="login_check") */public function loginCheckAction(){}

But this is a bad practice and login_check controller should be found without this definition.


Redirect back with Symfony and twig

$
0
0

In my Symfony project I have two views. Details view of specific entity and a button to lead me to a new view with with some other data by date param.

The problem with the code I have is of generating 'Return to previous' page button from second method back to first..

Code:

/** * @Route("/details/{id}", name="first_method") */public function firstMethod(Detail $id){    $workspace = $this->entityManager        ->getRepository(Detail::class)        ->find($id);    $build['detail'] = $detail;$form = $this->createFormBuilder()        ->add('date', DateTimeType::class, ['data' => new \DateTime(),'widget' => 'single_text'        ])        ->add('save',            SubmitType::class,            ['attr' => ['class' => 'btn-submit']            ]        )        ->getForm();    $form->handleRequest($request);    if ($form->isSubmitted() && $form->isValid()) {        $data = $form->getData();        $date = $data['date']        return $this->redirectToRoute('second_method', ['date' => $date        ]);    }    return $this->render('first-method.html.twig', ['detail' => $detail,        ]);}

And there is that 'second' method:

 /** * @Route("/second-method/{date}", name="second_method") */public function secondMethod($date){    return $this->render('second-method.html.twig', ['someData' => $someData,'date' => $date,    ]);}

I have a button on the second_method twig view which needs to return me back to method_one page.

How can accomplish that as the parameter $id is probably needed in second method but can not find a way to provide it. Maybe there is some other way? Can someone help?

I think in this first way it shoud me like:

{{ path('first_method', {'detailId':detail.id}) }}

Implement a custom error controller in Symfony 4.4

$
0
0

What i have done:

I have created this custom controller cause I want to pass to the error pages some extra variables.

#Controller/CustomErrorControler.phpnamespace App\Controller;use App\Controller\Base\BaseController;use Symfony\Component\ErrorHandler\Exception\FlattenException;use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;class CustomErrorController extends BaseController{    public function show(FlattenException $exception, DebugLoggerInterface $logger = null)    {        return $this->getView('bundles/TwigBundle/Exception/error.html.twig', ["code" => $exception->getStatusCode(),"message" =>$exception->getStatusText()        ]);    }}

and the enabled

#config/packages/framework.yamlerror_controller: App\Controller\CustomErrorController::show

I have followed the documentation directly. My problem is that I need, for non-production stages to get the default exception templates provided by the framework.

I have tried to extend Symfony\Component\HttpKernel\Controller\ErrorController but I'm getting errors for autowiring.

Maybe I should use Symfony\Component\ErrorHandler\ErrorRenderer\ErrorRendererInterfaceAny ideas how to implement this?

Foreign key fields returning null on doctrine querybuilder

$
0
0

I have this query:

    /**     * @return []     */    public function classificacao(): array    {        $qb = $this->createQueryBuilder('c')        ->select('cla')        ->andWhere('c.ativo =1')        ->leftJoin('App\Entity\Classificacao','cla', 'with', 'cla.cliente = c.id')        ->orderBy('c.codigo')        ->getQuery();        return $qb->execute();    }

but when i dump it the fields of the fk's entity return as null (and have value on the db):

enter image description here

if I select the 'c' Entity as well: ->select('cla, c') it works but passes the whole 'Cliente' entity again:

enter image description here

What am I doing wrong here and how I can get the return of the first image with the actual values inside the cliente field?

How to add image in the twig template?

$
0
0

It start getting bit annoying now. I am trying to add an image to the my TemplatedEmail

In my twig template, I have tried everything I found in the document:

<img src="{{ asset('images/logos/coffee.jpg') }}" alt="Symfony!"/><img src="{{ absolute_url(asset('images/logos/coffee.jpg')) }}" alt="Symfony!"/><img src="{{asset('build/images/1.0e73ff35.jpg')}}" title="my image" alt="My image">

None of them worked :(

Can anybody please help me how to add image in the template ?

Thank You.

React testing with Jest and Enzyme (in Symfony) got "Syntax Error: Unexpected token import"

$
0
0

im using React in Symfony, installed Jest and Enzyme to test the React components, but when trying to run tests with yarn test or even yarn test --no-cache got following error:enter image description here

here is my package.json file:

{"devDependencies": {"@symfony/webpack-encore": "^0.20.1","babel-jest": "^23.2.0","babel-preset-env": "^1.7.0","babel-preset-es2015": "^6.24.1","babel-preset-react": "^6.24.1","enzyme": "^3.3.0","enzyme-adapter-react-16": "^1.1.1","enzyme-to-json": "^3.3.4","jest": "^23.2.0","jest-enzyme": "^6.0.2","webpack-notifier": "^1.6.0"  },"dependencies": {"axios": "^0.18.0","babel-plugin-transform-object-rest-spread": "^6.26.0","moment": "^2.22.2","prop-types": "^15.6.2","rc-datetime-picker": "^1.6.1","react": "^16.4.1","react-dom": "^16.4.1","react-redux": "^5.0.7","redux": "^4.0.0"  },"scripts": {"test": "jest","test:watch": "jest --watch"  },"jest": {"transform": {"^.+\\.js$": "babel-jest"    },"setupTestFrameworkScriptFile": "./assets/js/__tests__/setup/setupEnzyme.js","testPathIgnorePatterns": ["./assets/js/__tests__/setup/"    ]  }}

and my webpack.config.js(encore) file:

var Encore = require('@symfony/webpack-encore');Encore// the project directory where all compiled assets will be stored    .setOutputPath('public/build/')    // the public path used by the web server to access the previous directory    .setPublicPath('/build')    // will create public/build/app.js and public/build/app.css    .addEntry('app', './assets/js/index.js')    // allow legacy applications to use $/jQuery as a global variable    .autoProvidejQuery()    // enable source maps during development    .enableSourceMaps(!Encore.isProduction())    // empty the outputPath dir before each build    .cleanupOutputBeforeBuild()    // show OS notifications when builds finish/fail    .enableBuildNotifications()    .enableReactPreset()    // first, install any presets you want to use (e.g. yarn add babel-preset-es2017)    // then, modify the default Babel configuration    .configureBabel(function(babelConfig) {        // add additional plugins        babelConfig.plugins.push('transform-object-rest-spread');        // no plugins are added by default, but you can add some        // babelConfig.plugins.push('styled-jsx/babel');    })// create hashed filenames (e.g. app.abc123.css)// .enableVersioning()// allow sass/scss files to be processed// .enableSassLoader();// export the final configurationmodule.exports = Encore.getWebpackConfig();

and finally my setupEnzyme.js:

const Enzyme = require('enzyme');// this is where we reference the adapter package we installed// earlierconst EnzymeAdapter = require('enzyme-adapter-react-16');// This sets up the adapter to be used by EnzymeEnzyme.configure({ adapter: new EnzymeAdapter() });

I tried all of the available solutions but none of them worked for me!any idea about it? :(

Symfony Distinct On date_trunc

$
0
0

Hi i have a problem i want use symfony doctrine for my request in native SQL it works but i want make it in doctrine. I use symfony4

I have create custom DQL date_trunc and register

What i want to do is that :

DISTINCT ON (date,ipp.link) date_trunc('day', ip.date) AS date

I have try this one

$qb->select("i,COUNT(DISTINCT CONCAT(date,ipp.link)  date_trunc('day',ip.date) as date) AS maxScore");

but not work

say :

"[Syntax Error] line 0, col 31: Error: Expected '.' or '(', got 'date'"}

When i test without CONCAT just DISTINCT(date,ipp.link) i got this:

Expected Doc…ine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got ','"}

I think problem is cause on native it s DISTINCT ON and here it s DISTINCT CONCAT but don t know how do that in doctrine

Someone can help me ?

Thanks

PHP 7.2 throws run "composer require symfony/dotenv", 7.1 does not

$
0
0

A Symfony 4.2 application built (& working) in PHP 7.1, when switched to 7.2 throws

Fatal error: Uncaught RuntimeException: Please run "composer require symfony/dotenv" to load the ".env" files configuring the application...

Further, composer update yields Nothing to install or update and then

Script cache:clear returned with error code 255 !! !! Fatal error: Uncaught RuntimeException: You need to add "symfony/framework-bundle" as a Composer dependency. in G:\Documents\workspace\mana\bin\console:14

After updating composer.json to require PHP 7.2, it now includes:

"require": {"php": "^7.2","ext-ctype": "*","ext-iconv": "*","beberlei/doctrineextensions": "^1.1","easycorp/easyadmin-bundle": "^2.0","knplabs/knp-snappy-bundle": "^1.6","ob/highcharts-bundle": "^1.6","sensio/framework-extra-bundle": "^5.1","symfony/asset": "4.2.*","symfony/console": "4.2.*","symfony/dotenv": "4.2.*","symfony/expression-language": "4.2.*","symfony/flex": "^1.1","symfony/form": "4.2.*","symfony/framework-bundle": "4.2.*","symfony/monolog-bundle": "^3.1","symfony/orm-pack": "*","symfony/process": "4.2.*","symfony/security-bundle": "4.2.*","symfony/serializer-pack": "*","symfony/swiftmailer-bundle": "^3.1","symfony/templating": "4.2.*","symfony/test-pack": "^1.0","symfony/translation": "4.2.*","symfony/twig-bundle": "4.2.*","symfony/validator": "4.2.*","symfony/web-link": "4.2.*","symfony/webpack-encore-bundle": "^1.0","symfony/yaml": "4.2.*"},

Edit: If, as suggested in the error message, composer update is run, the following occurs. As can be seen in composer.json above, this is nonsensical.

Fatal error: Uncaught RuntimeException: You need to add"symfony/framework-bundle" as a Composer dependency. in G:\Documents\workspace\mana\bin\console:14

Edit #2:This does not appear to be a Symfony or a PHP issue. I'm working in Windows and have a Hyper-V Ububtu 18 server running a clone of the app in Apache/2.4.29, PHP Version 7.2.19 without a problem. Makes it a whole lot harder to sort out. Place this Q on hold?

Edit #3:Restored a two month old Windows image and got the same effect. Returned to current image and learned that the errors described above start somewhere between PHP 7.10 & 7.16 on this box. Upgrading Symfony to 4.3 does not help. ARRRGGGHHH!

Final edit:Sorting this out is beyond my skill set. I'll end with the output of PHP 7.2.20. There is no dev.log created. Netbeans 11 does not seem to recognize xdebug. Here:

(1/1) FatalErrorException

Error: During class fetch: Uncaught ReflectionException: Class PHPUnit\Framework\TestCase not found in G:\Documents\workspace\mana\vendor\symfony\framework-bundle\Test\KernelTestCase.php:24 Stack trace:

0 G:\Documents\workspace\mana\vendor\symfony\debug\DebugClassLoader.php(159):

require('G:\Documents\wo...')

1 [internal function]: Symfony\Component\Debug\DebugClassLoader->loadClass('Symfony\Bundle\...')

2 G:\Documents\workspace\mana\vendor\symfony\framework-bundle\Test\WebTestCase.php(22):

spl_autoload_call('Symfony\Bundle\...')

3 G:\Documents\workspace\mana\vendor\symfony\debug\DebugClassLoader.php(159):

require('G:\Documents\wo...')

4 [internal function]: Symfony\Component\Debug\DebugClassLoader->loadClass('Symfony\Bundle\...')

5 G:\Documents\workspace\mana\vendor\liip\functional-test-bundle\src\Test\WebTestCase.php(41):

spl_autoload_call('Symfony\Bundle\...')

6 G:\Documents\workspace\mana\vendor\symfony\debug\DebugClassLoader.php(159):

require('G:\Documents\wo...')

7 [internal function]: Sy in KernelTestCase.php line 24


Temporarly disabling a doctrine entity listener

$
0
0

I use doctrine entity listeners to send mail whenever an entity is created. I want to be able to disable this event listener when performing certain operations (fixtures are mailbombing me as soon as I try to populate my database with fake entities).

I tried to disable the listener by using the clear method of the EntityListenerResolver class without success.

Here is my listener configuration:

services:    mail_on_create_document_listener:        class: App\EventListener\MailOnCreateDocumentListener        autowire: true        tags:            -                name: 'doctrine.orm.entity_listener'                event: 'postPersist'                entity: 'App\Entity\Document'

I try to disable the listener with this code:

<?phpnamespace App\DataFixtures;use Doctrine\Bundle\FixturesBundle\Fixture;use Doctrine\Common\Persistence\ObjectManager;class DebugFixture extends Fixture implements FixtureGroupInterface{    public function load(ObjectManager $manager)    {        $manager->getConfiguration()->getEntityListenerResolver()->clear(MailOnCreateDocumentListener::class);        dump($manager->getConfiguration()->getEntityListenerResolver());    }}

Here is the resulting dump of the EntityListenerResolver

^ Doctrine\Bundle\DoctrineBundle\Mapping\ContainerEntityListenerResolver^ {#1233  -container: Symfony\Component\DependencyInjection\Argument\ServiceLocator^ {#5278    -factory: Symfony\Component\DependencyInjection\Container::getService($registry, string $id, ?string $method, $load)^ {#283      this: ContainerHYiq7Ex\srcApp_KernelDevDebugContainer {#4404 …}    }    -serviceMap: array:1 ["mail_on_create_document_listener" => array:4 [        0 => "privates"        1 => "mail_on_create_document_listener"        2 => "getMailOnCreateDocumentListenerService.php"        3 => true      ]    ]    -serviceTypes: array:1 ["mail_on_create_document_listener" => "?"    ]    -externalId: null    -container: null    -factories: array:1 ["mail_on_create_document_listener" => array:4 [        0 => "privates"        1 => "mail_on_create_document_listener"        2 => "getMailOnCreateDocumentListenerService.php"        3 => true      ]    ]    -loading: []    -providedTypes: null  }  -instances: []  -serviceIds: array:1 ["App\EventListener\MailOnCreateDocumentListener" => "mail_on_create_document_listener"  ]}

Reading the code, it seems that the clear from EntityListenerResolver affects the instance part, but not the serviceIds.

How does this clear method is supposed to work?Is my service declaration wrong?

EDIT: I also tried this code with no success

        $evm = $manager->getEventManager();        $listeners = $evm->getListeners("postPersist");        while (count($listeners))        {            $evm->removeEventListener(array("postPersist"), array_pop($listeners));        }

But I read that entity listeners were quite different from other listeners, though it was not clear which was the difference. Here is the quote from the doc:

Different from Events an Entity Listener is invoked just to the specified entity

Symfony form not returning date range data

$
0
0

I have wrote a form in my Symfony project so it can return all results for given data range. I think problem is within the form as my query builder method works as it should.

When I input from 10.1 to 10.7 it returns till 10.6 not an input from last day (23:59:59).

First solution that returns that output was:

$startDate = new DateTime('first day of this month');$endDate = new DateTime('last day of this month');

and now I tried this with no luck:

    $start = \DateTime::createFromFormat( "Y-m-d H:i:s", date("Y-m-d 00:00:00") );    $end = \DateTime::createFromFormat( "Y-m-d H:i:s", date("Y-m-d 23:59:59") );    $form = $this->createFormBuilder()        ->add('startDate', DateTimeType::class, ['data' => $start,'widget' => 'single_text','html5' => false,'attr' => ['class' => 'text-center',            ],'format' => 'yyyy-MM-dd HH:mm','label' => 'Start Date','required' => true,        ])        ->add('endDate', DateTimeType::class, ['data' => $end,'widget' => 'single_text','html5' => false,'attr' => ['class' => 'text-center',            ],'format' => 'yyyy-MM-dd HH:mm','label' => 'End Date','required' => true,        ])        ->add('save',            SubmitType::class,            ['label' => 'Submit','attr' => ['class' => 'btn-submit']            ]        )        ->getForm();    $form->handleRequest($request);    if ($form->isSubmitted() && $form->isValid()) {        $data = $form->getData();        $startDate = $data['startDate'];        $endDate = $data['endDate'];        return $this->redirectToRoute('report', ['startDate' => $startDate->format("Y-m-d"),'endDate' => $endDate->format("Y-m-d")        ]);    }    return $this->render('details.html.twig', ['form' => $form->createView()        ]);

I tought the problem is with

->format("Y-m-d")

but when I remove this it throws:

expects parameter 1 to be string, object given

I except all date that is entered to give all results in from 2020-10-01T00:00:00 to 2020-10-07T23:59:59

App\Entity\Article object not found by the @paramconverter annotation Symfony

$
0
0

I try to be redirected after modifying the comment but I have the error App \ Entity \ Article object not found by the @paramconverter annotation do you have any idea of ​​the problem?

/** * @Route("/{id}/modifier", name="comment_edit", methods={"GET","POST"}, requirements={"id" = "\d+"}) * @param Request $request * @param Article $article * @param Comment $comment * @param LinkRepository $linkRepository * @param MoreRepository $moreRepository * @return Response */public function editComment(Request $request,Article $article, Comment $comment, LinkRepository $linkRepository,MoreRepository $moreRepository): Response{    $form = $this->createForm(CommentType::class, $comment);    $form->handleRequest($request);    if ($form->isSubmitted() && $form->isValid()) {        $this->getDoctrine()->getManager()->flush();        return $this->redirectToRoute('article_details',['id' => $article->getId()]);    }}   

Is it possible to get all the fields of a POST API?

$
0
0

I want to create a POST REST API, but I do not know the name of the fields posted,and their type. In Nodejs we can get the fields by using req.bodyIs there a way to know the posted fields in Symfony 4 ?

How to attach image to the email using symfony mailer?

$
0
0

I need to add image into the email. My images are located inside the public folder. I have defined in my twig.yaml like this:

twig:    globals:        image_dir: '%kernel.project_dir%/public/images/logos'    default_path: '%kernel.project_dir%/templates'    debug: '%kernel.debug%'    strict_variables: '%kernel.debug%'    exception_controller: null

Now in my twig.html file, I am calling image like below.

<img src="{{ image_dir }}/logo.png" alt="pngss" />

But the image is not appearing.

How to fetch data of an object when im getting the parent object (ex. process have actions, im fetching process) DOCTRINE

$
0
0

Let's say I have a class named Process, that has name, data.. etc. Then, this process class has a subclass called actions that have: [name, year, data]. So when I want to take all processes I just want to fetch the actions which have the year set in 2020 instead of getting all the actions with all the years.

Is there any way to do this in doctrine?

Something like SELECT PROCESS WHERE PROCESS.ACTIONS.YEAR LIKE 2020 (but in doctrine)

Sorry for the bad explanation, I hope you can understand it.

ps. I'm trying to print all processes in one twig file but I just want the latest actions.

Thank you very much

how to edit or add custom validation to FosUser validation from database - symfony 4

$
0
0

I have a problem!I want to manage regex password by adminIn such a way that the administrator can manage all passwords by setting regexI saved regex like this in database

{"regex":"^(?=.*[a-z])(?=.*[-!$%^@&*(#)_+|~=`{}\\[\\]:;<>?,.\\\/]).{8,}$","title":"__TITLE_FOR_SHOWING__"}

Please , help me.thanks


EasyAdmin 3 : Nested forms

$
0
0

I'm trying to embed forms into forms. In my case : I want to embed Period and Price form into Offer form into Poi form. The architecture :

  • Poi form
    • Offer form
      • Price form
      • Period form

Relations:

  • Poi entity has relation OneToMany with Offer entity
  • Offer entity has relation OneToMany with Price entity and ManyToMany with Periodentity.

I've been looking for solution for couple of days and I really need help, so if someone could help me it will be great.

1. First test : usage of CollectionFieldIn my PoiCrudController :

        public function configureFields(string $pageName): iterable{        $offers = CollectionField::new('offers')        ->setFormTypeOptions(['delete_empty' => true,'by_reference' => false,        ])        ->setEntryIsComplex(false)        ->setCustomOptions(['allowAdd' => true,'allowDelete' => true,'entryType' => 'App\Form\OfferType','showEntryLabel' => false,        ]),

In OfferType :

`class OfferType extends AbstractType {

public function buildForm(FormBuilderInterface $builder, array $options) {    $builder        ->add('description', CollectionType::class, array('allow_add' => true,'allow_delete' => true,'delete_empty' => true,'by_reference' => false,'entry_type' => TextEditorType::class,'entry_options' => ['label' => false,            ],'label' => 'Description',          ))        ->add('createdAt')        ->add('updatedAt')        ->add('periods')        ->add('poi')    ;}`

ERROR MESSAGE => The "App\Entity\Poi" entity has a repositoryClass set to "App\Entity\PoiRepository", 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".

If I replace 'entryType' => 'App\Form\OfferType', with 'entryType' => 'App\Form\PoiType' in PoiCrudController, and add this code in PoiType :

`class PoiType extends AbstractType {

public function buildForm(FormBuilderInterface $builder, array $options) {    $builder        ->add('offers', CollectionType::class, array('allow_add' => true,'allow_delete' => true,'delete_empty' => true,'by_reference' => false,'entry_type' => TextType::class, // cette ligne pose problème'entry_options' => ['label' => false,            ],'label' => 'Offres',          ))

Then the Poi form is nested into Poi form where the field 'offer' appears.If I replace 'entry_type' => TextType::class with 'entry_type' => TextEditorType::class, a new error appears :

ERROR MESSAGE : Impossible to access an attribute ("customOptions") on a null variable.in vendor\easycorp\easyadmin-bundle\src\Resources\views\crud\form_theme.html.twig (line 424){% set numOfRows = form.vars.ea_crud_form.ea_field.customOptions.get('numOfRows') %}

2. Second test : usage of CollectionField

In PoiCrudController :

CollectionField::new('offers', 'Offres')            ->allowAdd()             ->allowDelete()            ->setEntryIsComplex(true)            ->setEntryType(OfferCrudController::class)        ->setFormTypeOptions(['by_reference' => 'false'        ]),

ERROR MESSAGE => Could not load type "App\Controller\Admin\OfferCrudController": class does not implement "Symfony\Component\Form\FormTypeInterface.My forms implement AbstractType so...

3. Third test : usage of AssociationField

In PoiCrudController :

AssociationField::new('offers')            ->setFormTypeOptions(['by_reference' => false,'multiple' => true,'allow_add' => true            ]),

ERROR MESSAGE => An error has occurred resolving the options of the form "Symfony\Bridge\Doctrine\Form\Type\EntityType": The option "allow_add" does not exist=>Issue #3528 [https://github.com/EasyCorp/EasyAdminBundle/issues/3528][2]

Symfony 4 Sonata Media Bundle Installation

$
0
0

I have a few errors during installation of Sonata Media Bundle on Symfony 4 application which had no place with Symfony 2.8.

The first error:

 sensio/generator-bundle v3.1.6 requires symfony/framework-bundle ~2.7|~3.0

Next one, after solving the previous:

- php-amqplib/php-amqplib v2.7.0 requires ext-bcmath * -> the requested PHP extension bcmath is missing from your system.

Another one:

Unrecognized options "naming_strategy, auto_mapping, mappings" under "doctrine.orm"

And then, when I tried to clear the cache:

Class Application\Sonata\MediaBundle\ApplicationSonataMediaBundle not found in home/user/projects/svoya-fignia/config/services.yaml (which is loaded in resource "/home/user/projects/svoya-fignia/config/services.yaml").

or this one

Class Sonata\MediaBundle\PHPCR\BaseGalleryHasMediaRepository not found in home/user/projects/svoya-fignia/config/services.yaml (which is loaded in resource "/home/user/projects/svoya-fignia/config/services.yaml").

Why is log not displayed?

$
0
0

I want to display messages on the terminal, but there is no text displayed. Here is code :

<?phpnamespace App\Controller;use FOS\RestBundle\Controller\Annotations as Rest;use FOS\RestBundle\View\View;use Psr\Log\LoggerInterface;use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;use Symfony\Component\HttpFoundation\Request;class IteropController extends AbstractController{    /**     * @Rest\Post("/api/getiterop", name ="api_get_iterop")     *     * @return JsonResponse     */    public function getIteropForm(Request $req, LoggerInterface $logger)    {        $logger->info("====================== log");        return new View("Form posted Successfully", Response::HTTP_OK);    }}?>

I run the server from the Windows command line interface : php bin/console server:run

So how to fix it ?

Symfony 4.4 Event Dispatcher

$
0
0

**I'm getting the following error: **Service "event_dispatcher" not found: even though it exists in the app's container, the container inside "App\Controller\RatingApiController" is a smaller service locator that only knows about the "form.factory", "http_kernel", "parameter_bag", "request_stack", "router", "security.authorization_checker", "security.csrf.token_manager", "security.token_storage", "serializer", "session" and "twig" services. Try using dependency injection instead.

I'm used to using

 $this->get('event_dispatcher')->dispatch( AverageRatingEvent::NAME, new AverageRatingEvent($rating));

for dispatching an event but 'event_dipatcher' is giving an error I can't seem to find the source.

This is part of my controller:

<?phpnamespace App\Controller;use Symfony\Component\Routing\Annotation\Route;use Doctrine\ODM\MongoDB\MongoDBException;use Symfony\Component\HttpFoundation\RedirectResponse;use App\Document\Rating;use App\Event\AverageRatingEvent;use App\Form\Type\RatingType;use App\Helpers\FormErrorsSerializer;use Doctrine\ODM\MongoDB\DocumentManager;use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;use Symfony\Component\EventDispatcher\EventDispatcherInterface;use Symfony\Component\HttpFoundation\JsonResponse;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\EventDispatcher\Event;class RatingApiController extends AbstractController{    private $documentManager;    public function __construct(DocumentManager $documentManager)    {        $this->documentManager = $documentManager;    }class RatingApiController extends AbstractController{    private $documentManager;    public function __construct(DocumentManager $documentManager)    {        $this->documentManager = $documentManager;    }    /**     * @Route("api/rating/create", name="CreateRating",  methods={"POST"})     * @param DocumentManager $dm     * @param Request $request     * @return RedirectResponse|Response     * @throws MongoDBException     */    public function addRating(Request $request, EventDispatcherInterface $dispatcher)    {        $response = [];        $form = $this->        createForm(RatingType::class, new Rating() ,array('csrf_protection' => false));          $request = json_decode($request->getContent(), true);        $form->submit($request);        if($form->isSubmitted() && $form->isValid())        {           $rating = $form->getData();           $this->documentManager->persist($rating);           $this->documentManager->flush();        //    $event = new AverageRatingEvent($rating);           $this->get('event_dispatcher')->dispatch( AverageRatingEvent::NAME, new AverageRatingEvent($rating));        //    $dispatcher->dispatch(AverageRatingEvent::NAME, $event);}}

How do I get a service from the container directly, if I didn't/couldn't inject the service using DI?

$
0
0

I have a part of code where I'm injecting two services $checker and $paginator by dependency injection. It works perfectly:

public function index(Request $request, Paginator $paginator, Checker $checker)    {        $result = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];        $partialResult = $paginator->getPartial($result, 0, 3);        $checker->isValid('A');        var_dump("test");        die;    }

Below the configuration on services.yaml file:

   paginator:        public: true        class: 'App\Helper\Paginator'    checker:        public: true        class: 'App\Helper\Checker'        arguments:         $paginator: '@paginator'

But I'd like to inject for some reasons service by method:

$checker = $this->container->get('checker');

But it doesn't work. In previous versions Symfony like 3.4 it used to.

I'm receiving an error:

Service "checker" not found: event though it exists in the app's container, the container inside "App\Controller\DefaultController" is a smaller service locator that only knows about the "http_kernel", "parameter_bag", "request_stack", "router", "session", and "twig" services. Try using dependency injection instead.

How should I solve this?

Viewing all 3924 articles
Browse latest View live


Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>