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

Doctrine Extension with API Platform - SQL

$
0
0

I'm working on some API Platform project.I 'm using my API point /references to get some data containing subentities.

But the issue is that I use a Doctrine extension to filter my list. Using this extension I can filter which references I get.

But in the subentity Stock I stil have some data that I dont want.

My goal is to get all stocks that have the warehouse.owner = $owner.

Here is the code :

private function addWhere(QueryBuilder $queryBuilder, string $resourceClass): void{    if ($this->security->isGranted('SCOPE admin') || !$this->security->isGranted('SCOPE logistician')) {        return;    }    /** @var Client $client */    $client = $this->security->getUser();    $rootAlias = $queryBuilder->getRootAliases()[0];    switch ($resourceClass) {        case Entry::class:        case Inventory::class:            $queryBuilder->join(sprintf('%s.stock', $rootAlias), 's');            break;        case Reference::class:            // I'm here            $queryBuilder->join(sprintf('%s.stocks', $rootAlias), 's');            break;        default:            return;            break;    }    $queryBuilder->join('s.warehouse', 'w', Expr\Join::WITH, 'w.owner = :owner');    $queryBuilder->setParameter('owner', $client->getSubject());}

Here is the response :

{"@id": "/stock/references/7a00e32f-1195-43e6-a5d1-f75d64471112","@type": "Reference","id": "7a00e32f-1195-43e6-a5d1-f75d64471112","quantityAvailable": 75,"quantitiesOnHand": 100,"quantityOfExpectedEntries": -25,"archived": false,"stocks": [    {"@id": "/stock/stocks/214d9b27-d2c8-45e5-9d67-10985291022a","@type": "Stock","quantityOnHand": 50,"lastCountedEntryWasCreatedAt": "2020-07-23T10:04:32+02:00","warehouse": {"@id": "/stock/warehouses/3a61275f-4b20-4061-a64e-52783cf4d892","@type": "Warehouse","id": "3a61275f-4b20-4061-a64e-52783cf4d892","owner": "9001","name": "Adams-Reichel","createdAt": "2020-07-23T10:04:32+02:00"      },"createdAt": "2020-07-23T10:04:32+02:00"    },    {"@id": "/stock/stocks/6f2a0542-d65d-489a-b96c-c8658ff195ea","@type": "Stock","quantityOnHand": 50,"lastCountedEntryWasCreatedAt": "2020-07-23T10:04:32+02:00","warehouse": {"@id": "/stock/warehouses/cc8f3267-29b6-4ad5-9f8b-74b98aab85d6","@type": "Warehouse","id": "cc8f3267-29b6-4ad5-9f8b-74b98aab85d6","owner": "9002","name": "Steuber, Ruecker and Vandervort","createdAt": "2020-07-23T10:04:32+02:00"      },"createdAt": "2020-07-23T10:04:32+02:00"    }  ],"createdAt": "2020-07-23T10:04:32+02:00"},

How can I filter the subentity result by just using my extension and DQL ? Thanks


Stackdriver multi-channel logging with Symfony/Monolog and Google Kubernetes Engine

$
0
0

is there a current method to do some multi-channel logging of an Symfony application running on Kubernetes in Google Cloud and having the log channel data collected in Googles Stackdriver?

I've found an older solution under Google Cloud Stackdriver and monolog Symfony but it seems to be a bit legacy regarding Symfony and Google Cloud library versions.

I need the multiple channels for context related logging and I'd like to have an easy filter mechanism in the Google Console Logging (if it's possible to do it this way) so my idea was to use the Monolog channels like I use it on local development environment or old-fashioned hosting projects.

How to override namespace argument in RedisAdapter for a Symfony4 app to cache

$
0
0

I want to use custom namespace in our RedisAdapter to cache in our Symfony4 app. However, when i want to set arguments like this in our services.yaml;

cache.adapter.redis:        class: Symfony\Component\Cache\Adapter\RedisAdapter        arguments:            - '@Redis'            - 'app'

I see this error message:

Symfony\Component\Cache\Traits\RedisTrait::init() expects parameter 1 to be Redis, RedisArray, RedisCluster or Predis\ClientInterface, string given.

By the way, our cache config(config/packages/cache.yaml) is simple like below. So, how can I set namespace directly from any config?

    cache:        app: cache.adapter.redis        default_redis_provider: 'redis://%env(REDIS_HOST)%:%env(REDIS_PORT)%'

Symfony : How to set nothing as eclosure is CsvEncoder

$
0
0

I'd like to generate a very special CSV with | as delimiter but nothing as enclosure, this is my code :

file_put_contents(    $filename,    $serializer->serialize($data, 'csv',        [CsvEncoder::DELIMITER_KEY => '|', CsvEncoder::ENCLOSURE_KEY => chr(127)])    );

The chr(127) is supposed to set an empty string as enclosure, but it generates this :enter image description here

There is no problems with numeric values (columns A and C)But with string values sometimes it's ok (B) and sometimes it's not (D and F) : the value is between a special character !

The only solution I found is to use CsvEncoder::ENCLOSURE_KEY =>" " (use a space as enclosure, since I can't set an empty string), but it's not what I'm looking for : I really have to set nothing as enclosure. I've read it's a bug with the library used by Symfony's Csv Serializer, but I don't want to change the class.

Is there any solution with the used class ?

Thanks :)

How to embed images in a symfony mail?

$
0
0

So I designed an email template for my reset-password system.In the email templates, there are Images (logo).

I placed those images inside a folder called Email_Images and that folder is placed inside the Public folder!

First, I tried to link the images using Asset() twig Function like this:

<img alt="logo 1" src="{{asset('Email_Images/1.png')}}" /><img alt="logo 2" src="{{asset('Email_Images/2.jpg')}}" />

But none of them works. So I tried to get the image in the controller and send it to the template, like this :

 $email = (new TemplatedEmail())        ->from(new Address('myEmail@gmail.com', 'My Subject'))        ->to($user->getEmail())        ->subject('Your password reset request');        $img= $email ->embed(fopen('Email_Images/1.jpg', 'r'), 'img');        $email->htmlTemplate('reset_password/email.html.twig')        ->context(['resetToken' => $resetToken,'img' => $img,'tokenLifetime' => $this->resetPasswordHelper->getTokenLifetime(),        ]);

In the template I did

<img alt="logo 1" src="{{ img }}" />

and I get this error :

An exception has been thrown during the rendering of a template("Catchable Fatal Error: Object of classSymfony\Bridge\Twig\Mime\TemplatedEmail could not be converted tostring").

What is the right way to add/embed an image in an Email?

Symfony4/Behat inject function not working "you have requested a non-existen service"

$
0
0

For a testcase i need to be able to use an existing service, but this service cannot be used in my behat context:

Context:

/**class CustomContext extends MinkContext implements KernelAwareContext {    # ...     * @param EntityManagerInterface $em     * @param HttpCallResultPool $httpCallResultPool     * @param SessionInterface $session     * @param CustomService $customService     * @param string $evaluationMode     */    public function __construct(        EntityManagerInterface $em,        HttpCallResultPool $httpCallResultPool,        SessionInterface $session,        CustomService $customService,        string $evaluationMode = 'javascript'    ) {        $this->em = $em;        $this->client = new Client();        $this->inspector = new JsonInspector($evaluationMode);        $this->httpCallResultPool = $httpCallResultPool;        $this->session = $session;        $this->customService= $customService;    }

behat.yaml:

# ...    Behat\Symfony2Extension:      kernel:        bootstrap: 'config/bootstrap.php'        path: 'src/Kernel.php'        class: 'App\Kernel'        env: dev         debug: false # ...suites:    default:      contexts:        - App\CustomContext:            em: '@doctrine.orm.default_entity_manager'            session: '@session'            customService: '@App\Service\CustomService'

Fehlermeldung:

In Container.php line 289:  You have requested a non-existent service "App\Service\CustomService".

Can someone help or has an idea why this error message is shown?The Service does work in the used controller. So there should be no error with the service itself, only with injecting this service into behat.

Sylius Symfony The controller for URI "/_profiler/open" is not callable: Environment variable not found: "STRIPE_PUBLIC" [closed]

$
0
0

I'm working with sylius SYMFONY after pulling update from other branch got this error says can't find environment variable STRIPE_PUBLICWhere do I find stripe public?

Symfony 4.4 Querybuilder exclude all events during a weekend

$
0
0

Got a question, I have a query where I have to exclude events based on their days.

I have to eliminate all events where the dateStart occurs during a weekend (Friday from 19:30:00 till Sunday). But for some reason this one returned an event that was on a Sunday...

Does anyone have a clue what's wrong with the query and how to solve it?

Thanks in advance!

<?php $qb = $this->createQueryBuilder('r')    ->select('count(r.id)')    ->leftJoin('r.events', 're')    ->leftJoin('r.user', 'ru');    ->andWhere("DAYOFWEEK(re.dateStart) NOT IN (:weekend)")->setParameter('weekend', [1,7]); // Sat and Sunday    ->andWhere("DAYOFWEEK(re.dateStart) != :day AND (DATE_FORMAT(re.dateStart, '%T')) = :hour")    ->setParameter('hour', '19:30:00'])    ->setParameter('day', 6); // Friday

Symfony regex with variables in config .yaml files

$
0
0

I am using host parameter in security firewall configuration:

security:    firewalls:        admin:            pattern: ^/            #this works            host: ^admin\.test_domain\.test$            #this one does not            host: ^%admin_subdomain_name%\.%domain_name%\.%tld%$            remember_me:                secret:   '%kernel.secret%'                lifetime: 604800 # 1 week in seconds                path:     /

admin_subdomain_name, domain_name, tld variables differs between environments. Thus I need them to set as variables. I guess there is other way by creating security.yaml for each environment (config/dev/security.yaml, config/prod/security.yaml).But I wanted to know if there is a way to use regexes with variables in configuration files?

Sonata Admin List Field Template is Ignored

$
0
0

I'm using Symfony 4.1.1 and Sonata Admin Bundle 3.35.2.

I want to use a custom template for a field in an admin's list view. The template is ignored. I am using Twig as my templating engine.

In the admin:

# /src/Admin/ImageAdmin.phpprotected function configureListFields(ListMapper $listMapper) {    $listMapper        ->add('filename', 'string', ['template' => 'list_image.html.twig'])    ;}

The template:

# /templates/list_image.html.twig{% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %}{% block field %}<img src="{{ value }}" style="width: 200px" />{% endblock %}

Cleanest way to globally override a Console style

$
0
0

tl;dr: I want to change an output formatter style across my entire Console application without having to modify every command. How can I make a single set of changes that take effect globally?

I want to globally change the error output formatter style in my Symfony 4 Console application. As per the documentation, it's easy to do so in an ad hoc fashion per command, e.g.:

public function execute(InputInterface $input, OutputInterface $output): int {  $output->getFormatter()->setStyle('error', new OutputFormatterStyle('red'));}

But I don't want to add needless boilerplate to all my commands--especially not with a new operator. For maintainability and testability, I prefer to override and inject my dependencies via the service container. I tried to do this by overriding the output formatter:

MyOutputFormatter.php

use Symfony\Component\Console\Formatter\OutputFormatter;use Symfony\Component\Console\Formatter\OutputFormatterStyle;class MyOutputFormatter extends OutputFormatter {  public function __construct($decorated = FALSE, array $styles = []) {    // I've tried it this way:    $styles['error'] = new OutputFormatterStyle('red');    parent::__construct($decorated, $styles);    // I've tried it this way:    $this->setStyle('error', new OutputFormatterStyle('red'));    // And I've tried it this way:    $this->getStyle('error')->setForeground('red');    $this->getStyle('error')->setBackground();  }}

services.yml:

Symfony\Component\Console\Formatter\OutputFormatterInterface:  alias: My\Console\Formatter\OutputFormatter

MyCommand.php

use Symfony\Component\Console\Command\Command;use Symfony\Component\Console\Input\InputInterface;use Symfony\Component\Console\Output\OutputInterface;class MyCommand extends Command {  public function execute(InputInterface $input, OutputInterface $output) {    $output->writeln("<error>I'm an error.</error>");  }}

But I must be doing something wrong, because although my class definitely gets injected and interpreted, whether I try to override an existing style or create a new one, it has no effect: I expect my custom style to be used (red foreground with no background), the default style is used instead (white foreground with a red background).

Can someone correct my misunderstanding or suggest a better way? Thanks!!

Integrity constraint violation in my api platform relation

$
0
0
Symfony : 4.4API PLATFORM : 2.5 

I have to entities : Client & Location : a client have many locations, a location is related to one client

Client Entity:

    /** * @ORM\Entity(repositoryClass="App\Repository\ClientRepository") * * * @ApiResource( *     normalizationContext={"clients:get"}, *     collectionOperations={ *          "get"={ *              "normalization_context": { "groups" = {"clients:get"} }, *          }, *          "post"={ *               "security"="is_granted('IS_AUTHENTICATED_ANONYMOUSLY')", *               "normalization_context": { "groups" = {"client:get"} }, *               "denormalization_context": { "groups" = {"client:create"} }, *               "method"="POST", *               "controller"=ClientCreate::class *          } *     }, *     itemOperations={ *          "get"={ *              "normalization_context": { "groups" = {"clients:get"} }, *           }, *          "put"={ *               "security"="is_granted('IS_AUTHENTICATED_ANONYMOUSLY')", *               "normalization_context": { "groups" = {"client:get"} }, *               "denormalization_context": { "groups" = {"client:put"} }, *          }, *     } * ) * */class Client implements UserInterface{    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     *     * @Groups({"clients:get"})     *     */    private $id;    /**     * @ORM\OneToMany(targetEntity="App\Entity\Location", mappedBy="client", cascade={"persist", "remove"}), orphanRemoval=true)     *     *@Groups({"client:create","client:get","client:put"})     *     * @ApiSubresource()     *     */    private $locations;

Location Entity:

/** * @ORM\Entity(repositoryClass="App\Repository\LocationRepository") * * @ApiResource() * */class Location{    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     *     */    private $id;    /**     * @ORM\Column(type="string", length=255, nullable=true)     *     * @Groups({"client:create","client:get","client:put"})     *     */    private $address;//... others attributes    /**     * @ORM\Column(type="string", length=255)     *     * @Groups({"client:create","client:get","client:put"})     *     */    private $locationName;    /**     * @ORM\ManyToOne(targetEntity="App\Entity\Client", inversedBy="locations", fetch="EXTRA_LAZY")     * @ORM\JoinColumn(nullable=false)     */    private $client;

I'm trying to make the relation Client-Location behaves like when I create a client => locations are created => that's works OK for me with this code.and also I want when I put a client, its old locations are removed, and It creates a new locations that are attached to this client but I got error in put.

ActionPUT /api/clients/58Body:

{"locations": [        {"address": "dfsdfaaaaaaaa","locationName": "sdfsdf"        }    ]}

RESPONSE:

{"@context": "/api/contexts/Error","@type": "hydra:Error","hydra:title": "An error occurred","hydra:description": "An exception occurred while executing 'UPDATE location SET client_id = ? WHERE id = ?' with params [null, 24]:\n\nSQLSTATE[23000]: Integrity constraint violation: 1048 Column 'client_id' cannot be null","trace": [    {"namespace": "","short_class": "","class": "","type": "","function": "","file": "/home/karimengineer/Desktop/SystemFood/api/system_food_api/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/AbstractMySQLDriver.php","line": 103,"args": []    },

PRESTASHOP, ERROR 4 Start tag expected, '

$
0
0

I was working on my store translation manually thru Cpanel modules. When I finished I went to backoffice to clear cash and I got this error:

Fatal error: Uncaught Symfony\Component\Config\Util\Exception\XmlParsingException:   [ERROR 4] Start tag expected, '<' not found (in n/a - line 1, column 1)    in /home/MyDomaineName/public_html/vendor/symfony/symfony/src/Symfony/Component/Config/Util/XmlUtils.php:62 Stack trace:   #0 /home/MyDomaineName/public_html/vendor/symfony/symfony/src/Symfony/Component/Config/Util/XmlUtils.php(131): Symfony\Component\Config\Util\XmlUtils::parse('a<?xml version=...', NULL)   #1 /home/MyDomaineName/public_html/vendor/symfony/symfony/src/Symfony/Component/Translation/Loader/XliffFileLoader.php(54):   Symfony\Component\Config\Util\XmlUtils::loadFile(Object(Symfony\Component\Finder\SplFileInfo))   #2 /home/MyDomaineName/public_html/vendor/symfony/symfony/src/Symfony/Component/Translation/Loader/XliffFileLoader.php(42): Symfony\Component\Translation\Loader\XliffFileLoader->extract(Object(Symfony\Component\Finder\SplFileInfo),     Object(Symfony\Component\Translation\MessageCatalogue),'ShopThemeAction...')  #3 /home/MyDomaineName/public_ht     in /home/MyDomaineName/public_html/vendor/symfony/symfony/src/Symfony/Component/Translation/Loader/XliffFileLoader.php on line 56

I'm using Prestashop 1.7.6.5

Codeception/Symfony4 Environment variable not found: "DATABASE_URL"

$
0
0

I have a project in Symfony4 with doctrine DB, everything flies.

I would like to add some functional and unit testing with Codeception. I followed the docs and added this to my functional.suite.yml:

actor: FunctionalTestermodules:    enabled:        - Symfony:            app_path: 'src'            environment: 'test'        - Doctrine2:            depends: Symfony#            cleanup: true        - \Helper\Functional#       - Db    step_decorators: ~        

However, when running vendor/bin/codecept run I get an ugly:

In EnvVarProcessor.php line 131:

Environment variable not found: "DATABASE_URL".

I can't see anything else related in the docs, so not sure what I'm missing.

in the tests, after upgrade to symfony4, every request gets a new session

$
0
0

I want to upgrade from symfony 3.4 to 4.4. But directly after this change, many functional tests are broken. Analyzing shows that for every request, I get a new session id, so also a new session. What do I do wrong?

$client = $this->createClient();$client->request('GET', '/');dump($client->getReqest()->getSession()->getId());$client->request('GET', '/');dump($client->getReqest()->getSession()->getId());

shows a different session ID. (In symfony3.4 it is the same.)

Where is the session id saved in tests? Like normally in a cookie? I see no session cookie (in $client->getRequest()), only one other cookie. I see the session cookie in $client->getRequest()->cookies, and then a different id in $client->getResponse->headers.

Did I miss to adapt some config? I use flex before and after the update, so I did not mix it up with this change.config/packages/test/framework.yaml contains frameworks: session: storage_id: session.storage.mock_file, which is default from the recipe. The mocked session files are visible in the cache.


Apache dont load css [deployment Symfony 4.4 project] [duplicate]

$
0
0

When i set the appache directive DocumentRoot to /var/www/html/foo/public, my css files are loading successfully and everything looks great except that i dont want 'index.php' into my url.

But when i set DocumentRoot to /var/www/html/foo/public/index.php, the website is working but the css is not load at all .

My question is, how can i hide the 'index.php' and still get my css files loaded

Symfony: How can i use Remote procedure call (RPC) with Messenger?

$
0
0

I'm trying to do RPC with Symfony Messenger but I get stuck.Looking at the Messenger component it looks like the implementation has not been added:

https://github.com/webnet-fr/symfony/branches/allhttps://github.com/symfony/symfony/pull/34337/commits/06a5a434ce6e5349a33e81c97d83c8b4392603cd

But, I tell myself, if it hasn't been added it's because there should be a way for it to work but ... I can't find it.Could someone please confirm if it is possible to do RPC with Messenger? if you have any documentation, I am a taker and I will thank you.

EntityType and many to many with extra field relation presented as dropdown (select)

$
0
0

I created a form like that

$builder->add('employees', EntityType::class, ['class'         => ActivityEmployee::class,'choice_label'  => function (ActivityEmployee $employee) {        return sprintf('%s %s', $employee->getEmployee()->getName(), $employee->getEmployee()->getLastName());    },'multiple'      => true,])

As a result it presents already existing data fine. It shows me all employees with relation to edited activity.

However as choices there should be all employess to choose (employee entity) and as selected data only employess in activityEmployee relation like right now.

I tried to add a query_builder option to provide lists of all employess, but I can only use EntityRepository which means ActivityEmployeesRepository not EmployeesRepository per se.

A can't figure out how to implement it. Basically such relation can be done by CollectionType of custom activityEmployeeType but I'd like to use multi-select for selecting employees.

I can use another approach to not mapping my employees field to entity like that

$currentEmployees = [];foreach ($activity->getEmployees() as $activityEmployee) {    $currentEmployees[] = $activityEmployee->getEmployee();}$builder->add('employees', EntityType::class, ['class'        => Employee::class,'choice_label' => function (Employee $employee) {        return sprintf('%s %s', $employee->getName(), $employee->getLastName());    },'mapped'       => false,'multiple'     => true,'data'         => $currentEmployees,]);

It works fine, but I need to deal with updating relation by myself. Which is ok, however I wonder how to achieve such thing in first approach.

Symfony 4 Forms: implementing per-Entity custom sorting in QueryBuilder for ChoiceType fields

$
0
0

I seem to have some troubles getting my head around the intrinsics of the Symfony (4) Form component.

I want to:

a) store information per-Entity(Repository?) on how the default sort order should be, like $entityRepository->sortOrder = ['default' => ['LastName ASC', 'FirstName ASC'], 'custom1' => [...]];

b) use that information to instruct the Form to use that ordering with the query_builder option/attribute for the ChoiceType form field

So the question is, how/where should i ideally store that information and how should i feed this to the Form object / QueryBuilder?

Pointing me in a direction doing it in a "industry-standard" fashion would be greatly appreciated.

How to force symfony form to only display and accept positive integers?

$
0
0

I have the following code:

use Symfony\Component\Validator\Constraints\Positive;public function buildForm(FormBuilderInterface $builder, array $options){    $builder        ->add('x', IntegerType::class, ['mapped' => false,'required' => false,'constraints' => [new Positive()]            ])}

The twig form is as follows:

{{ form_widget(form.x, { 'attr': {'class': 'form-control'} }) }}

However, the rendered form (HTML) still allows users to input values with a minus sign.How do I change that, so the rendered form forbids minus sign and stops at 1 on the arrow input?

Viewing all 3925 articles
Browse latest View live


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