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

Escape including same varibales when rendering twig view

$
0
0

In my Symfony project I have various twig view's with same properties as the main twig layout has some and also block twig content for every view has some new ones.

Like:

private function generateView($page, $type, $user, $pageCount = 20){    $mainImgUrl = $this->imageService->getAvatarPath($user->getId());    $places = $this->entityManager->getRepository(Place::class)->getPage($type, $page, $pageCount);    $menu = $this->builder->getMenuThings();    return $this->render('places.html.twig', ['type' => $type,'mainImgUrl' => $mainImgUrl,'places' => $places['data'],'fullName' => $user->getFirstName().''.$user->getLastName(),'menu' => $menu,'contentTitle' => $title,'contentDescription' => '','totalItems' => $p['totalItems'],'pageCount' => $workspaces['pagesCount'],'pageSize' => $pageSize,'currentPage' => $page    ]);}

So, half of these belong to main twig view and just a few in block twig view. Whenever I am generating new twig view I have to include all of them which is probably harder way to do it.

I want to ask if anyone has any suggestions how can I, for example, make a 'helper' method and call it in every new twig view so I escape including all of these in every new method I write.

Thanks


Disable doctrine cache for unittests (symfony 4)

$
0
0

I have a unittests in my Symfony 4 project which show a inconsistent behaviour and I suspect the doctrine caching is responsible for this. So I am looking for a way to disable caching for Unittests.

My current packages/test/doctrine.yaml file for the environment test looks like this:

doctrine:    orm:        auto_generate_proxy_classes: false        metadata_cache_driver:            type: service            id: doctrine.system_cache_provider        query_cache_driver:            type: service            id: doctrine.system_cache_provider        result_cache_driver:            type: service            id: doctrine.result_cache_providerservices:    doctrine.result_cache_provider:        class: Symfony\Component\Cache\DoctrineProvider        public: false        arguments:            - '@doctrine.result_cache_pool'    doctrine.system_cache_provider:        class: Symfony\Component\Cache\DoctrineProvider        public: false        arguments:            - '@doctrine.system_cache_pool'framework:    cache:        pools:            doctrine.result_cache_pool:                adapter: cache.app            doctrine.system_cache_pool:                adapter: cache.system

If I want to disable any caching in doctrine for tests, is there any cache driver, which is a non-caching dummy? If I leave those entries empty I guess my prod settings or the general settings would be used, which means the results would also be cached. Can I explicitly non-cache?

config    \__packages        |        |__ prod        |   \__doctrine.yaml        |        |__ dev        |   \__doctrine.yaml        |        |__ test        |   \__doctrine.yaml        |        \__doctrine.yaml

Disable doctrine cache for test environment / unittests (symfony 4)

$
0
0

I have a unittests in my Symfony 4 project which show a inconsistent behaviour and I suspect the doctrine caching is responsible for this. So I am looking for a way to disable caching for Unittests.

My current packages/test/doctrine.yaml file for the environment test looks like this:

doctrine:    orm:        auto_generate_proxy_classes: false        metadata_cache_driver:            type: service            id: doctrine.system_cache_provider        query_cache_driver:            type: service            id: doctrine.system_cache_provider        result_cache_driver:            type: service            id: doctrine.result_cache_providerservices:    doctrine.result_cache_provider:        class: Symfony\Component\Cache\DoctrineProvider        public: false        arguments:            - '@doctrine.result_cache_pool'    doctrine.system_cache_provider:        class: Symfony\Component\Cache\DoctrineProvider        public: false        arguments:            - '@doctrine.system_cache_pool'framework:    cache:        pools:            doctrine.result_cache_pool:                adapter: cache.app            doctrine.system_cache_pool:                adapter: cache.system

If I want to disable any caching in doctrine for tests, is there any cache driver, which is a non-caching dummy? If I leave those entries empty I guess my prod settings or the general settings would be used, which means the results would also be cached. Can I explicitly non-cache?

config    \__packages        |        |__ prod        |   \__doctrine.yaml        |        |__ dev        |   \__doctrine.yaml        |        |__ test        |   \__doctrine.yaml        |        \__doctrine.yaml

Inject constant param form getter in twig

$
0
0

I have defined constant in my entity like:

$fieldName = User::METADATA_OF_USER

It's passed as the entity getter param:

public function getMetaDataField($fieldName){    $metadata = json_decode($this->metadata, true);    return $metadata[$fieldName] ?? null;}

When I try to pass it in twig:

{ item.metadataField }}

it requires that fieldName param as constant.

I tried some solution of twig constants but non of them worked for me. I there any way to inject that constant in the view?

Symfony : How to access saved entity via metadata using parameters in the route

$
0
0

I have an entity contact

<?phpnamespace App\Entity;use App\Repository\ContactRepository;use Doctrine\ORM\Mapping as ORM;/** * @ORM\Entity(repositoryClass=ContactRepository::class) */class Contact{    /**     * @ORM\Id     * @ORM\GeneratedValue     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="string", length=50)     */    private $firstName;    /**     * @ORM\Column(type="string", length=50)     */    private $lastName;    /**     * @ORM\Column(type="date", nullable=true)     */    private $dob;    /**     * @ORM\Column(type="string", length=50)     */    private $email;    /**     * @ORM\Column(type="string", length=15)     */    private $phone;    public function getId(): ?int    {        return $this->id;    }    public function getFirstName(): ?string    {        return $this->firstName;    }    public function setFirstName(string $firstName): self    {        $this->firstName = $firstName;        return $this;    }    public function getLastName(): ?string    {        return $this->lastName;    }    public function setLastName(string $lastName): self    {        $this->lastName = $lastName;        return $this;    }    public function getDob(): ?\DateTimeInterface    {        return $this->dob;    }    public function setDob(?\DateTimeInterface $dob): self    {        $this->dob = $dob;        return $this;    }    public function getEmail(): ?string    {        return $this->email;    }    public function setEmail(string $email): self    {        $this->email = $email;        return $this;    }    public function getPhone(): ?string    {        return $this->phone;    }    public function setPhone(string $phone): self    {        $this->phone = $phone;        return $this;    }}

I want to select one (or more) contact with this URL"/c00210/readallbyparam/{routeProperty}/{routeValue}"

For example"/c00210/readallbyparam/lastname/Mendelsohn"

This should return 2 records,

for Felix Mendelsohn

and Fanny Mendelsohn

How do I write the render() function?How do I write the twig instructions?

I suppose I should use the metadata, but I don't know

How to access saved entity via metadata using parameters in the route

$
0
0

I have an entity contact

<?phpnamespace App\Entity;use App\Repository\ContactRepository;use Doctrine\ORM\Mapping as ORM;/** * @ORM\Entity(repositoryClass=ContactRepository::class) */class Contact{    /**     * @ORM\Id     * @ORM\GeneratedValue     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="string", length=50)     */    private $firstName;    /**     * @ORM\Column(type="string", length=50)     */    private $lastName;    /**     * @ORM\Column(type="date", nullable=true)     */    private $dob;    /**     * @ORM\Column(type="string", length=50)     */    private $email;    /**     * @ORM\Column(type="string", length=15)     */    private $phone;    public function getId(): ?int    {        return $this->id;    }    public function getFirstName(): ?string    {        return $this->firstName;    }    public function setFirstName(string $firstName): self    {        $this->firstName = $firstName;        return $this;    }    public function getLastName(): ?string    {        return $this->lastName;    }    public function setLastName(string $lastName): self    {        $this->lastName = $lastName;        return $this;    }    public function getDob(): ?\DateTimeInterface    {        return $this->dob;    }    public function setDob(?\DateTimeInterface $dob): self    {        $this->dob = $dob;        return $this;    }    public function getEmail(): ?string    {        return $this->email;    }    public function setEmail(string $email): self    {        $this->email = $email;        return $this;    }    public function getPhone(): ?string    {        return $this->phone;    }    public function setPhone(string $phone): self    {        $this->phone = $phone;        return $this;    }}

I want to select one (or more) contact with this URL: /c00210/readallbyparam/{routeProperty}/{routeValue}

For example: /c00210/readallbyparam/lastname/Mendelsohn
This should return 2 records:

  • Felix Mendelsohn
  • Fanny Mendelsohn

How do I write the render() function?How do I write the twig instructions?

I suppose I should use the metadata, but I don't know

user checker checkPreAuth vs checkPostAuth [closed]

$
0
0

In Symfony User Checker, I'm confused between checkPreAuth& checkPostAuth

Question 1:

So for checkPreAuth how can we talk about a user before we authenticate it ?

Question 2:

What's the real difference between checkPreAuth& checkPostAuth and in what case we should put our test in checkPreAuth and not in checkPostAuth ?

Question 3:

Where is the CustomUserMessageAccountStatusException is catched, because I found that it create for us a flash message with the message we had put in its constructor ?

namespace App\Security;use App\Security\User as AppUser;use Symfony\Component\Security\Core\Exception\AccountExpiredException;use Symfony\Component\Security\Core\Exception\CustomUserMessageAccountStatusException;use Symfony\Component\Security\Core\User\UserCheckerInterface;use Symfony\Component\Security\Core\User\UserInterface;class UserChecker implements UserCheckerInterface{    public function checkPreAuth(UserInterface $user)    {        if (!$user instanceof AppUser) {            return;        }        if ($user->isDeleted()) {            // the message passed to this exception is meant to be displayed to the user            throw new CustomUserMessageAccountStatusException('Your user account no longer exists.');        }    }    public function checkPostAuth(UserInterface $user)    {        if (!$user instanceof AppUser) {            return;        }        // user account is expired, the user may be notified        if ($user->isExpired()) {            throw new AccountExpiredException('...');        }    }}

Symfony 4 default_locale is not working on Security library messages

$
0
0

I am building single language Symfony (v4.4.7) application.As I understood from the documentation I need to set

framework:    default_locale: tr    translator:        default_path: '%kernel.project_dir%/translations'        fallbacks:            - en

in config/packages/translation.yamlto change lang in the whole application.

Using configuration above custom translations are working!However, Symfony Security library still showing messages in English (e.g Invalid credentials. when user password is incorrect).Removing default_path: '%kernel.project_dir%/translations' line does not help.I tried to change the default_locale to other languages still the same result.

Edit 1 more details:Content of translations directory:enter image description here

messages.tr.yaml contains following lines:

security:   roles_label: "Roller"   roles:       ROLE_SUPER_ADMIN: "Super Admin"       ROLE_ADMIN: "Admin"       ROLE_USER: "Genel Kullanıcı"

I deleted content of the messages.tr.yaml and tried again but it is still not working. Other tr translation files does not contain security keyword


Why are .env files preferred over .yaml files for environment variables?

$
0
0

What is/are the main reason(s), for which Symfony preferres to use .env files - for holding values of environment variables in them - instead of using the more flexible .yaml files?

I am asking this, because I read this comment, which states:

It was much simpler when we were using .yaml file.
I totally understand why we needed to switch to .env file, but IMHO we should rethink everything.

Thank you for your time.

No identifier/primary key specified for Entity why using KNP Translatable

$
0
0

I am using Knp/DoctrineBehaviors to translate my database content.I followed the manual and created 2 entities, 1 for non-translatable content and the other for translatable fields.

namespace App\Entity;use Doctrine\ORM\Mapping as ORM;use Knp\DoctrineBehaviors\Contract\Entity\TranslatableInterface;use Knp\DoctrineBehaviors\Model\Translatable\TranslatableTrait;    /**     * Class Test     * @package App\Entity     * @ORM\Entity()     */    class Test implements TranslatableInterface    {        use TranslatableTrait;        /**         * @var integer         * @ORM\Column(type="integer")         * @ORM\GeneratedValue(strategy="AUTO")         * @ORM\Id()         */        private $id;        /**         * @return int         */        public function getId(): int        {            return $this->id;        }        /**         * @param int $id         */        public function setId(int $id): void        {            $this->id = $id;        }    }

and the Translation entity:

namespace App\Entity;use Doctrine\ORM\Mapping as ORM;use Knp\DoctrineBehaviors\Contract\Entity\TranslationInterface;use Knp\DoctrineBehaviors\Model\Translatable\TranslationTrait;/** * Class TestTranslation * @package App\Entity * @ORM\Entity() */class TestTranslation implements TranslationInterface{    use TranslationTrait;    /**     * @var     * @ORM\Column(type="string")     */    private $name;    /**     * @return mixed     */    public function getName()    {        return $this->name;    }    /**     * @param mixed $name     */    public function setName($name): void    {        $this->name = $name;    }}

I also added the Bundle in my bundles.php file.

But when I run the command php bin/console doctrine:schema:update --force to create the table in give the error: No identifier/primary key specified for Entity "App\Entity\TestTranslation". Every Entity must have an identifier/p rimary key.

How to cache routes responses in symfony4(5)

$
0
0

Looking for lib or built in solution (if there is one) how to cache some routes htmls. Need them just for history. There should not be any repository calls, except if it's to get cached page.Problem is that I want to rebuild from scratch lots of logic and controllers and other depended entities, but I need some how to save some routes for history reasons. On those oages there is not lot of design.. Bet there is a lot of tables. And i do not want to rewrite those routes by habnd without variables... Also dont want to go to each of those pages and save their (by hand) sources from browser

Symfony/Twig: How to force locale in Twig after setLocale is deprecated

$
0
0

I need to render documents in different languages. Therefore I used to use the following code:

use Symfony\Component\Translation\TranslatorInterface;....$this->translator->setLocale($documentData->getLocale());$html = $this->templating->render('admin/request/pdf/document.pdf.twig', ['data' => $data,]);...

And everything worked fine.

But then "Symfony\Component\Translation\TranslatorInterface" got deprecated and one should use "Symfony\Contracts\Translation\TranslatorInterface". In the new class there is no "setLocale()" anymore.

I tried a lot of things but I finally have no idea to work around.

Did anyone mange it?

Thanks a lot!

EDIT:

I am looking for a solution where I can set the translation locale for the Twig template globally. Actually I don't want to write this for every key in the twig:

{{ 'pdf.document.title'|trans({}, 'documents', locale) }} 

I want to write this like before:

{{ 'pdf.document.title'|trans }} 

optimize cascade jointure QueryBuilder

$
0
0

I have a QueryBuilder query, working, but pretty greedy. I'd like to know if I could optimize it.

Here is my entity setup :I have n (a dozen) Project (p), having n (can be thousands) medias (m), having 1 transcription (t), having n (can be thousands) transcription logs (l).

I'd like to retrieve all projects, sorted by its last transcription log (the createdAt property). I guess there some ways to optimize it but I can't figure out my own.

return $this->createQueryBuilder('p')          ->select('p')          ->leftJoin('p.medias', 'm')          ->leftJoin('m.transcription', 't')          ->leftJoin('t.transcriptionLogs', 'l')          ->andWhere('p.archived = 0')          ->addOrderBy('l.createdAt', 'DESC')          ->addOrderBy('p.id', 'DESC')          ->getQuery()          ->getResult();

Thanks !

HttpClient body params not accepted

$
0
0

I am connecting my Symfony project with external server endpoint via HttpClient. I am getting desired response.

Problem occurs when I try to pass two parameters from my request body. When this endpoint is tested in Postman it works as it should.

It's like the params are not included as I get the same response as without them. Response should return filtered results by dates I am inputing.

public function callIt($endpoint, $startDate, $endDate){    $method = 'GET';    $token = $this->authApi->getToken('test', 'test');    $url = 'http://my-endpoint.oi' . $endpoint;    $params = ['startDate' => $startDate,'endDate' => $endDate    ];    return HttpClient::create(['base_uri' => $url])->request($method, $url, ['headers' => ['Authorization' => 'Bearer ' . $token['access_token'],        ],'body' => $params    ]);}

Also tried:

'body' => ['startDate' => 'value1', '...'],

filter entity fields on symfony controller

$
0
0

How can I choose(filter) on my controller which fields I want (or don't want) to pass to my frontend?

my Controller:

/** * @Route("/", name="dashboard") */public function index(){    $aniversariantes = $this->getDoctrine()->getRepository(Usuario::class)->aniversariantes();    return $this->render('dashboard/index.html.twig', ['controller_name' => 'DashboardController','aniversariantes' => $aniversariantes    ]);}

My repository:

/** * @return [] */public function aniversariantes(): array{ $qb = $this->createQueryBuilder('u')    ->andWhere('u.ativo = 1')    ->andwhere('extract(month from u.dtNascimento) = :hoje')    ->setParameter('hoje', date('m'))    ->getQuery();    return $qb->execute();}

Dump from entity:

enter image description here

What can I do if I don't want to pass the "password" field for example?


Symfony messenger and mailer : how to add a binding_key?

$
0
0

I have a running Symfony 4.4 project with messenger and rabbitMQ.I have an async transport with 2 queues.

    transports:        # https://symfony.com/doc/current/messenger.html#transport-configuration      async:        dsn: '%env(MESSENGER_TRANSPORT_DSN)%'        options:          exchange:            name: myexchange            type: direct          queues:            email:              binding_keys:                - email            extranet:              binding_keys:                  - extranet        # failed: 'doctrine://default?queue_name=failed'        # sync: 'sync://'    routing:        # Route your messages to the transports'App\Message\ExtranetMessage': async'Symfony\Component\Mailer\Messenger\SendEmailMessage': async

I need to send email with the symfony/mailer component to the email queue.

public function contact(Request $request, MailerInterface $mailer){    if($request->isXmlHttpRequest())    {        //dd($request->request->all());        $body ='Nouveau message depuis le front<br />             Nom = '.$request->request->get('nom').'<br />             Prénom = '.$request->request->get('prenom').'<br />             Société = '.$request->request->get('societe').'<br />             Email = '.$request->request->get('mail').'<br />';        $email = (new Email())            ->from('from@email.tld')            ->replyTo($request->request->get('mail'))            ->to('$request->request->get('mail')')            ->subject('test')            ->html($body);        $mailer->send($email);        return new JsonResponse('OK', 200);    }}

How can I add the binding_key to the mailer in order to let rabbitMQ know how to handle the email ?

AJAX calls not showing in the profiler toolbar (Symfony 4)

$
0
0

enter image description here

I can't see the ajax calls loaded in the profiler toolbar. is there any solution for this?this happened only with symfony 4 version and greater.thanks.

Symfony 4 - passing response to another view after form submit

$
0
0

I have two methods in my symfony project. With one I am building a form which on submit needs to redirect in new view with it's response.

I keep getting an error but the wierd thing is that my response is running like it should on first method but on second I keep getting an error:

Could not resolve argument $date of"App\Controller\ItController::render()", maybe youforgot to register the controller as a service or missed tagging itwith the "controller.service_arguments"?

public function getIt(Request $request){    $form = $this->createFormBuilder()        ->add('startDate', DateTimeType::class, ['data' => new \DateTime('first day of this month'),'widget' => 'single_text','html5' => false,        ])        ->add('save',            SubmitType::class,            ['label' => 'Generate Billing Report','attr' => ['class' => 'btn-submit btn-primary action-save']            ]        )        ->getForm();    $form->handleRequest($request);    if ($form->isSubmitted() && $form->isValid()) {        $data = $form->getData();        $startDate = $data['date'];        $this->render($date->format('Y-m-d'));        return $this->redirectToRoute('rr');    }       return $this->render('details.html.twig', ['form' => $form->createView()            ]);

And other method that needs to generate that second view with response:

/** * @Route("/test", name="rr") */public function render($date){    $response = $this->someService('route/defined/from/other/external/service, $date);    dump($response);    return $this->render('response.html.twig', ['response' => $response    ]);}

When I dump response in first method It returns it successfully but when I try to pass it on that other method it return this error. Maybe there is an option to render second view in first method?Can someone help? Thanks

Panther Chrome WebDriver : Full screen?

$
0
0

In my functional test of my symfony 4 application, i use the Chrome Webdriver with PANTHER_NO_HEADLESS=1 to see what happen.

My problem is : Chrome browser starting with Debug Tool (F12) and not in full screen.This is a problem because i want to test elements that appears only on full screen.

My test :

public function testMyTest(){    $client = Client::createChromeClient();    $crawler = $client->request('GET', 'http://example.com/form');    $form = $crawler->selectButton('valider')->form(['formField' => 'value'    ]);    $client->submit($form)    // Some assertions here}

Command :

$export PANTHER_NO_HEADLESS=1

Then

phpunit -c phpunitFunctional.xml --filter="testMyTest" path/to/FileTest.php

How can i start with full screen and without debug tool ?

Symfony 4 fosrestbundle cant recognize routing_lader configuration as an array, instead expecting a boolean

$
0
0

Symfony 4.4 returns "Invalid type for path "fos_rest.routing_loader". Expected boolean, but got array.", after configuring the fos_rest.yml as it follows:

fos_rest:  view:    view_response_listener: 'force'    formats:      json: true  format_listener: true  param_fetcher_listener: true  routing_loader:    default_format: json  serializer:    groups: ['default']

This configuration was valid in previous versions of the symfony framework. Please some help here, cant find anythink on documentation.

Viewing all 3924 articles
Browse latest View live


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