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

My profiler toolbar isn't showing up in symfony 4.3.1

$
0
0

In my .env file, I have specified my app environment to be dev and debug to be true like so:

APP_ENV=dev
APP_DEBUG=true

In my config/packages/dev/web_profiler.yaml file I have the following:

web_profiler:
    toolbar: true
    intercept_redirects: false

framework:
    profiler: { only_exceptions: false }

The routing within config/routes/dev/web_profiler.yaml seems to be fine:

web_profiler_wdt:
    resource: '@WebProfilerBundle/Resources/config/routing/wdt.xml'
    prefix: /_wdt

web_profiler_profiler:
    resource: '@WebProfilerBundle/Resources/config/routing/profiler.xml'
    prefix: /_profiler

So when I run the server with symfony server:start everything is fine, but the profiler doesn't appear. Did I miss something that enables that feature within Symfony?

To clarify, the page is outputting a proper HTML page with the appropriate content. There is just no profiler showing up.


My base twig template:

<!DOCTYPE html>
<html lang="en" dir="ltr">
    <head>
        <meta charset="utf-8">
        <title>{% block title %} {% endblock %}</title>
        {{ encore_entry_script_tags('base') }}
        <link rel="icon" type="image/x-icon" href="{{ asset('build/images/favicon.ico') }}" />
        <link href="https://fonts.googleapis.com/css?family=IBM+Plex+Sans:400,500|Playfair+Display:400,700&display=swap" rel="stylesheet">
        {{ encore_entry_link_tags("base") }}
        {% block stylesheet %}{% endblock %}
    </head>
    <body {% if app.request.get('_route') == 'home' %} class='homepage' {% endif %} >
        <header>
            <div id='top-navigation' class='padding-lg__left-md padding-lg__right-md padding-lg__top-sm padding-lg__bottom-sm row row__align-center row__justify-start'>
                <span class='text-color__white text-size__small text-weight__bold margin-lg__right-lg'>Our Mission</span>
                <span class='text-color__white text-size__small text-weight__bold margin-lg__right-lg'>Our Team</span>
                <span class='text-color__white text-size__small text-weight__bold margin-lg__right-lg'>Where the Money Goes</span>
                <span class='text-color__white text-size__small text-weight__bold margin-lg__right-lg'>Community Leadership</span>
                <span class='text-color__white text-size__small text-weight__bold'>Policies</span>
                <span class='text-color__white text-size__small text-weight__bold margin-lg__left-auto icon-set'> <span class='icon size__small color__white margin-lg__right-xsm'>{{ source('@public_path'~asset('build/images/icons/feedback.svg')) }}</span>Submit Feedback</span>
            </div>
            <nav class="padding-lg__top-md padding-lg__bottom-md padding-lg__left-md padding-lg__right-md row row__align-center row__justify-start {% if app.request.get('_route') == 'home' %} homepage {% endif %}">
                <div id='logo'>
                    <a href="{{ url('home') }}">
                        <img src="{{ asset('build/images/logo_placeholder.png') }}" alt="logo">
                    </a>
                </div>
                {% if app.request.get('_route') == 'creator-register' %}

                {% else %}
                    {% if not is_granted('IS_AUTHENTICATED_FULLY') %}
                        <div class='margin-lg__left-auto'>
                            <a href="{{ url('login') }}">
                                <div class='icon-set'>
                                    <span class='icon margin-lg__right-xsm'>
                                        {{ source('@public_path'~asset('build/images/icons/user.svg')) }}
                                    </span>
                                    <span class='nav-item'>Login</span>
                                </div>
                            </a>
                        </div>
                    {% endif %}

                {% endif %}
            </nav>
        </header>
        {% if app.request.get('_route') != 'home' %} <div class='container is_top'> {% endif %}
            {% block body %} {% endblock %}
        {% if app.request.get('_route') != 'home' %} </div> {% endif %}
    </body>
</html>

Security.yaml firewall:

    firewalls:
            dev:
                pattern: ^/(_(profiler|wdt)|css|images|js)/
                security: false
            main:
                anonymous: true
                guard:
                    authenticators:
                        - App\Security\LoginFormAuthenticator
                logout:
                    path : logout
                remember_me:
                    secret: '%kernel.secret%'
                    lifetime: 2592000 #<- 30 days in seconds - defaults to one year if you take this out!

Results on php bin/console debug:router | grep _profiler:

  _profiler_home             ANY      ANY      ANY    /_profiler/                        
  _profiler_search           ANY      ANY      ANY    /_profiler/search                  
  _profiler_search_bar       ANY      ANY      ANY    /_profiler/search_bar              
  _profiler_phpinfo          ANY      ANY      ANY    /_profiler/phpinfo                 
  _profiler_search_results   ANY      ANY      ANY    /_profiler/{token}/search/results  
  _profiler_open_file        ANY      ANY      ANY    /_profiler/open                    
  _profiler                  ANY      ANY      ANY    /_profiler/{token}                 
  _profiler_router           ANY      ANY      ANY    /_profiler/{token}/router          
  _profiler_exception        ANY      ANY      ANY    /_profiler/{token}/exception       
  _profiler_exception_css    ANY      ANY      ANY    /_profiler/{token}/exception.css 

Lastly homepage controller:

<?php
namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class HomepageController extends AbstractController{

    /**
    * @Route("/", name="home")
    */

    public function output(){
        return $this->render('homepage/home.html.twig',[
            'title' => 'yo',
        ]);
    }
}

?>

Added public/index.php:

<?php

use App\Kernel;
use Symfony\Component\Debug\Debug;
use Symfony\Component\HttpFoundation\Request;

require dirname(__DIR__).'/config/bootstrap.php';

if ($_SERVER['APP_DEBUG']) {
    umask(0000);

    Debug::enable();
}

if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? $_ENV['TRUSTED_PROXIES'] ?? false) {
    Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST);
}

if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? $_ENV['TRUSTED_HOSTS'] ?? false) {
    Request::setTrustedHosts([$trustedHosts]);
}

$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);

Display last post on my symfony site from my wordpress blog

$
0
0

I have a Symfony (v4.3) website which integrates a blog. I decided to use wordpress for the blogging part of the site, so I had setup wordpress into a "/public/blog" folder in my Symfony architecture. The blog works as expected, however I want to display the X last posts of my blog into my Symfony pages, I found some bundles like: https://github.com/ExtremeSensio/EasyWordpressBundle . But they working with symfony 2 or 3 only... Does someone have an idea or already do that on his side?

Thanks in advanced.

Use function Javascript on TWIG page using WebPack Encore and Symfony 4

$
0
0

i'm using Symfony 4.2 and i use last WebPack Encore.

I have issu because i need to use function from my javascript on my twig template, but this never work.

I always have same problem:

Uncaught ReferenceError: consoleText is not defined at (index):17

assets/js/app.js:

require('../css/app.css');
const $ = require('jquery');
global.$ = global.jQuery = $;

assets/js/myFunctions.js

const consoleText = function (log = "Auncun log") {
console.log(log);
};

module.exports = {
    consoleText: consoleText
};

webpack.config.js

var Encore = require('@symfony/webpack-encore');

Encore
    .setOutputPath('public/build/')
    .setPublicPath('/build')
    .addEntry('app', './assets/js/app.js')
    .enableSingleRuntimeChunk()
    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    .autoProvidejQuery()
;

module.exports = Encore.getWebpackConfig();

I need to get access to my function consoleText() outside my file.

If i want to get access on javascript file, this work. Exemple: In my app.js i can add:

let myTest = require('./myFunctions');
myTest.consoleText('Blablabla');

this work fine after compilation.

BUT i need to get access this function on my twig template (home.html.twig)

In my base.html.twig i called my script file with:

{% block javascripts %}
    {{ encore_entry_script_tags('app') }}


    // NEED HERE USE MY FUNCTION LIKE:
    {{ encore_entry_script_tags('myFunctions') }}
    <script>
        consoleText("This don't work");
    </script>
{% endblock %}

my consoleTest() function don't work and i don't understand why. I try to use Module.export, and tried to use lot of thinks but i don't know why i can't call my function on my twig template, so i need your help.

Thank you

Symfony & AWS BS - Env vars for console outside .env files

$
0
0

I have a symfony API which runs on AWS beanstalk instances. My .env file registers the environment variables that I need in my app. I override all of them in the AWS console to adapt to my environments.

For exemple :

  • Env file : DEFAULT_CONNECTION_DSN=bolt://user:password@host:port
  • Test server : DEFAULT_CONNECTION_DSN=bolt://test:azerty@test.toto.com:7687
  • Prod server : DEFAULT_CONNECTION_DSN=bolt://prod:azerty@toto.com:7687

This works because AWS overrides the environment variables when the PHP server is started, so the values placed in the .env file are ignored.

The problem is that I try to create a CRON on the server. The CRON is executed from command line, and I saw that, in this case, the variables still have the value specified in the .env file at runtime.

If I list the environment variables on the server, I see that DEFAULT_CONNECTION_DSN has the value that I want, but if I dump the value in my code (or execute php bin/console debug:container --env-vars), DEFAULT_CONNECTION_DSN has the .env file value. I already tried to delete the entry from my .env file. In this case, I have an error saying my environment variable is not found.

I must precise that I work with a .env.local locally, file which is not versionned, and the deploys are based on git versionning, so it seems difficult to add a .env.env-name file for each environement.

What could I do ?

sFetch datas with specified fields as entity

$
0
0

My Symfony 4.3 applications is very heavy on data consumption and i need to do some optimizations. One important step would be to limit the fields i select from my entities as most of them are only used in the backend.

Here is an example function in my repository class:

public function getPerson(int $id): ?Person
{
    $qb = $this->createQueryBuilder('Person');

    $qb->addSelect('person.firstName');
    $qb->where('person.id = ' . $id);

    return $qb->getQuery()->getOneOrNullResult();
}

And this is the result I get:

Return value of MyRepository::getPerson() must be an instance of App\Entity\getPerson or null, array returned

Which makes sense since it's missing properties. But I've been banging my head on this for a while and can't find a way to map my array result to an object. I've read the documentation about the Symfony serializer but it's unclear to me how to work with a PHP array and not a JSON or XML document.

How can I submit a form as soon as I have a data? [duplicate]

$
0
0

This question already has an answer here:

I am under Symfony 4.3 and building a webapp.

I have a form, with only one field: FileType. This form is used to allow the user to upload a profile picture.

I want the form to be sent as soon as a photo is selected, so basically.... No submit button.

The reason is simple: This form is intended for a webapp, usable via smartphone therefore.

What is the most effective way to achieve this? I was thinking about the FormEvents but I never really used it and I'm not sure about it.

Thank you!

How can resolve problem with variable roles in Symfony 4? [closed]

$
0
0

I am trying to teach the symfony 4 framework and I have a problem with the variable responsible for permissions, i.e. Roles. This is a REST application and everything is fine when adding a user via a postman (json). When I try to add from the administration panel (no json format), the operation is aborted with the error

"This value should have a string of type".

Image

REPO: https://github.com/DariuszKitel/Workers

Symfony3.2 to symfony4 security.encoder_factory deprecated error

$
0
0

I updated my website from Symfony 3.2 to Symfony 4, by creating a new symfony4 skeleton and moved the source code from symfony3.2 to symfony4.

I had been made the changes as mentioned in Upgrading Symfony4.Also I installed all the required packages.Now I can make routing and successfully got my web page on the display,the problem I am facing is login form doesn't work.

In my login controller for symfony3.2 version,

I used security.encoder_factory service

And when I am running it in symfony4 it results:

The "security.encoder_factory" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.

My controller code for encoding password is:

public function loginAction(Request $request)
{
    #$defaultEncoder = new MessageDigestPasswordEncoder('bcrypt', true, 5000);
    $defaultEncoder = new MessageDigestPasswordEncoder('bcrypt');

    $encoders = [
        User::class => $defaultEncoder, // Your user class. This line specify you ant sha512 encoder for this user class
        ];

    $encoderFactory = new EncoderFactory($encoders);

    $data = [
        'error' => null,
        '_username' => null,
    ];
    if ($request->isMethod('POST')) {
        $_username = $request->request->get('_username');
        $_password = $request->request->get('_password');

        $data['_username'] = $_username;
        $user = $this->getDoctrine()->getManager()
            ->getRepository("App:User")
            ->findOneBy(array('username' => $_username);
        if (!$user) {
            $data['error']  = 'User-Id does not exist';
            return $this->render(
                'login.html.twig',
                $data
            );
        }

        $encoder = $encoderFactory->getEncoder($user);
        $salt = $user->getSalt();
        #$encoder = $this->encodePassword($_password, $salt);

        if (!$encoder->isPasswordValid($user->getPassword(), $encoder)) {
            $data['error'] = 'User-Id or Password not valid.';
            return $this->render(
                'login.html.twig',
                $data
            );
        } 

        return $this->redirect($this->generateUrl('default__home_page'));
    }

    return $this->render(
        'login.html.twig',
     $data
    );
}

My security for encoding is:

security:
   encoders:
        App\Entity\User: bcrypt
        App\Security\User\WebserviceUser: bcrypt
        Symfony\Component\Security\Core\User\User: bcrypt
        FOS\UserBundle\Model\UserInterface: sha512
# https://symfony.com/doc/current/security.html#where-do-users-come-from-    user-providers
    providers:
        #in_memory: { memory: ~ }
        our_db_provider:
            entity:
                class: App:User
                property: username
    fos_userbundle:
        id: fos_user.user_provider.username_email
firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    secured_area:
        anonymous: ~
        pattern:    ^/s/login$
        http_basic: ~
        provider: fos_userbundle
        user_checker: security.user_checker

        form_login:
            login_path: login_page
            check_path: login_page
            failure_handler: security.authentication.failure_handler
        guard:
            authenticators:
                - App\Security\LoginControllerAuthenticator
        # activate different ways to authenticate

        # http_basic: ~
        # http://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate

        # form_login: ~
        # http://symfony.com/doc/current/cookbook/security/form_login_setup.html

        logout:
            path:   /logout/
            target: /login/

Is there any alternative way or service to encoding my password as the above code represents.

error:

No encoder has been configured for account "App\Entity\User".

  at vendor/symfony/security/Core/Encoder/EncoderFactory.php:51
  at Symfony\Component\Security\Core\Encoder\EncoderFactory->getEncoder(object(User))
     (src/Controller/Controller.php:65)
  at App\Controller\Controller->loginAction(object(Request))
     (vendor/symfony/http-kernel/HttpKernel.php:149)
  at Symfony\Component\HttpKernel\HttpKernel->handleRaw(object(Request), 1)
     (vendor/symfony/http-kernel/HttpKernel.php:66)
  at Symfony\Component\HttpKernel\HttpKernel->handle(object(Request), 1, true)
     (vendor/symfony/http-kernel/Kernel.php:188)
  at Symfony\Component\HttpKernel\Kernel->handle(object(Request))
     (public/index.php:37)

Thanks in advance.


How to use ICU's select with decimals on Symfony4?

$
0
0

Symfony4 uses ICU for translations. I want a rich display of time values in my translation - in French. For instance, 1.25 hours should display "One hour and a quarter" - pardon my french.

Yet, i found no way to escape dots, or wrap my "key" value with quotes. The following example always returns a U_PATTERN_SYNTAX_ERROR if i try any way of escaping the dot:

messages+intl-icu.fr.yml

  durationHours: >-
    {n, select,
        0     {Non précisé}
        1     {1 heure}
        1.25  {1 heure et quart}
        other {{n} heures}
    }

TaskService.php

$this->tl->trans('task.durationHours', ['n' => $task->getDurationInHours()]);

The docs i based my research upon:

How to retrieve information from a file with an html form?

$
0
0

I have a problem with my form.

This is the situation:
I use the CraueFormFlowBundle bundle to create a step-by-step form (4 steps).

So, I use the create form of the bundle $form = $flow->createForm(); to create the form.

But when I set up the Symfony file uploader, I can't get the information from the file.

Does anyone have a solution or even a small lead?

My controller:

/**
  * @Route("/classified/new", name="classified_create")
  * @IsGranted("ROLE_USER")
  * @param Request $request
  * @param ObjectManager $manager
  * @param CreateVehicleFlow $createVehicleFlow
  * @param FileUploader $fileUploader
  * @return Response
 */
 public function create(Request $request, ObjectManager $manager, CreateVehicleFlow $createVehicleFlow, FileUploader $fileUploader)
 {
     $user = $this->getUser();
     $vehicle = new Vehicle();
     $vehicle->setCity($user->getCity());
     $vehicle->setAuthor($user);

     $flow = $createVehicleFlow;
     $flow->setGenericFormOptions([
         'action' => $this->generateUrl('classified_create')
     ]);
     $flow->bind($vehicle);
     $form = $flow->createForm();
     if ($flow->isValid($form)) {
         $flow->saveCurrentStepData($form);
         if ($flow->nextStep()) {
             $form = $flow->createForm();
         } else {
             foreach ($vehicle->getImages() as $image) {
                 $image->setVehicle($vehicle);
                    $manager->persist($image);
                 }
                 /** @var UploadedFile $imageCoverFile */
                 $imageCoverFile = $form['imageCover']->getData();

                 if ($imageCoverFile) {
                     $imageCoverFileName = $fileUploader->upload($imageCoverFile);
                     $vehicle->setImageCoverName($imageCoverFileName);
                 }

                 $manager->persist($vehicle);
                 $manager->flush();

                 $flow->reset();

                 $this->addFlash(
                     'success',
                     "Votre annonce <i>{$vehicle->getId()}</i> a bien été enregistrée"
                 );

                 return $this->redirect($this->generateUrl('account_index'));
             }
         }

         return $this->render('front/classified/new_vehicle.html.twig', [
             'form' => $form->createView(),
             'flow' => $flow,
             'vehicle' => $vehicle,
         ]);
     }

My form type:

->add(
    'imageCover',
    FileType::class, [
        'label' => 'Image de couverture',
        'mapped' => false,
        'required' => false,
        'constraints' => [
            new File([
                'maxSize' => '3M',
                'mimeTypes' => [
                    'application/jpeg',
                    'application/png',
                ],
                'mimeTypesMessage' => 'Vous devez télécharger un format valide'
            ])
        ]
    ]
);

My entity: I am only the name of the file that is in my entity and only the name of the file that is saved in the database.

/**
 * @ORM\Column(type="string", length=255)
*/
private $imageCoverName;

public function getImageCoverName(): ?string
{
   return $this->imageCoverName;
}

public function setImageCoverName(string $imageCoverName): self
{
   $this->imageCoverName = $imageCoverName;

   return $this;
}

I have tried this solution but nothing works.

$imageCoverFile = $form['createVehicle']['imageCover']->getData();

symfony4 doctrine 2 multiple db - migrate data from migrate data from 2 databases into third one

$
0
0

I am migrating data to the next project. It integrates two dedicated systems. I have to map data into new databases, but new structure require to merge data from both databases into tables with some logic. Logic is not a problem, but how can I create Entities/connections to 2 databases (selects) and insert into third database? All of them are located in different locations and different credentials. I tried https://symfony.com/doc/current/doctrine/multiple_entity_managers.html but no success. Does any one have a working solution with multiple databases? I already spent a lot of time to figure it out:(

Symfony 4 demo running with local server gives fatal error [closed]

$
0
0

I just installed the demo but I get a Fatal Error when I try to run it with the local web server. This is the log:

Nov 15 12:02:03 |DEBUG| PHP    Stack trace: 
Nov 15 12:02:03 |DEBUG| PHP    #0 /home/flm/workspace_neon/sf4-demo/vendor/symfony/dotenv/Dotenv.php(492): Symfony\Component\Dotenv\Dotenv->populate(Array, false) 
Nov 15 12:02:03 |DEBUG| PHP    #1 /home/flm/workspace_neon/sf4-demo/vendor/symfony/dotenv/Dotenv.php(65): Symfony\Component\Dotenv\Dotenv->doLoad(false, Array) 
Nov 15 12:02:03 |DEBUG| PHP    #2 /home/flm/workspace_neon/sf4-demo/vendor/symfony/dotenv/Dotenv.php(85): Symfony\Component\Dotenv\Dotenv->load('/home/flm/works...') 
Nov 15 12:02:03 |DEBUG| PHP    #3 /home/flm/workspace_neon/sf4-demo/config/bootstrap.php(17): Symfony\Component\Dotenv\Dotenv->loadEnv('/home/flm/works...') 
Nov 15 12:02:03 |DEBUG| PHP    #4 /home/flm/workspace_neon/sf4-demo/public/index.php(7): require('/home/flm/works...') 
Nov 15 12:02:03 |DEBUG| PHP    #5 /home/flm/.symfony/php/493f2362a36fdff7d64a072f34086eae4dfbaa1a-router.php(26): require('/home/flm/works...') 
Nov 15 12:02:03 |DEBUG| PHP    #6 {main} 
Nov 15 12:02:03 |DEBUG| PHP      thrown in /home/flm/workspace_neon/sf4-demo/vendor/symfony/dotenv/Dotenv.php on line 167 
Nov 15 12:02:03 |ERROR| SERVER GET  (500) / ip="127.0.0.1"```

The console gives:
```Symfony 4.3.8 (env: dev, debug: true)```

Symfony: How can I get hold of tagged services and processed configuration at the same time?

$
0
0

I'm trying to symfony Configuration to determine how to wire some tagged services, but am running into problems. I've tried to boil the problem down into as little code as possible to help explain, but still - sorry for the length!

Here's the configuration part of things...

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('acme_test');
        $treeBuilder
            ->getRootNode()
            ->addDefaultsIfNotSet()
            ->children()
                ->scalarNode('email_sender')->isRequired()->end()
                ->scalarNode('email_title')->defaultValue('Notification email')->end()
            ->end();

        return $treeBuilder;
    }
}
acme_test:
    email_sender: 'test@example.com'

I've also got an arbitrary service which takes $emailSender and $emailTitle. It's been tagged with the 'arbitrary-services' tags in services.yaml:

class ArbitraryService
{
    protected $emailSender;

    protected $emailTitle;

    public function __construct(string $emailSender, string $emailTitle)
    {
        $this->emailSender = $emailSender;
        $this->emailTitle = $emailTitle;
    }
}
services:
    App\Acme\TestBundle\ArbitraryService:
        tags: ['arbitrary-services']

The Symfony documentation tells me to do my tagged services finding in a CompilerPass - fair enough:

class AcmeTestCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $configs = $container->getExtensionConfig('acme_test');

        $taggedServices = $container->findTaggedServiceIds('arbitrary-services');

        // Great - got the tagged service definitions
        // Now going to wire things passed via config into those services (e.g. via binding)

        dump('From CompilerPass:');
        dump($taggedServices);
        dump($configs);
    }
}

In my full use-case, I want to tag different directories of services to cause them to receive different params based upon config options (e.g. services tagged with inject.alpha get parameters based upon config keys in acme -> alpha).

The problem tho' is that at this point, whilst the tagged services return fine, the configuration has not been processed, and so we're missing the email_title key which has a defaultValue:

wobble@pop-os:~/test$ bin/console c:c
"From CompilerPass:"
array:1 [
  0 => array:1 [
    "email_sender" => "test@example.com"
  ]
]
array:1 [
  "App\Acme\TestBundle\ArbitraryService" => array:1 [
    0 => []
  ]
]

If I check within the Extension / load() class on the other hand...

class AcmeTestExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $taggedServices = $container->findTaggedServiceIds('arbitrary-services');

        dump('From load()');
        dump($taggedServices);
        dump($config);
    }
}

I'll find that I have the fully-processed configuration (yey!) but no tagged services as presumably I'm too early for that (hence the docs telling me to use a CompilerPass):

wobble@pop-os:~/test$ bin/console c:c
"From load()"
[]
array:2 [
  "email_sender" => "test@example.com""email_title" => "Notification email"
]

Can anyone please tell me if it's possible to get hold of both the processed configuration and the tagged services at the same time? Thanks!

I've pushed the test code that reproduces my problem up on a github repo here: https://github.com/WubbleWobble/symfony-stack-overflow-1

How to override block from base template with include? [closed]

$
0
0

I have a problem with Symfony 4. My templates all extend base.html.twig.

And in my base.html.twig, I want to include my sidebar (sidebar.html.twig), which will have to include the

{% block body %}{% endblock %}

for the body of my templates to embed themselves directly in.

So, I would like:

#template.html.twig
{% extends 'base.html.twig' %}
{% block body %}
   <p> test <p>
{% endblock %}

With

#base.html.twig
//...
<body>
   {% include "partials/sidebar/sidebar.html.twig" %}
</body>

With

#sidebar.html.twig
//...
<div class="col-md-12">
  {% include "partials/notifications.html.twig" %}
  {% block body %}{% endblock %}
</div>

So, I will have as result my sidebar.html.twig with my template.html.twig body in the block body.

In my base.html.twig, if I paste all my sidebar.html.twig instead of doing an include, it works. But if I make an include, I've my sidebar, but not the body

I made it like this:

#template.html.twig
{% extends 'base.html.twig' %}
{% block body %}
   <p> test <p>
{% endblock %}

My base:

{% include "partials/sidebar/sidebar.html.twig" with {body: block('body')}%}

And in my sidebar:

{# Block Body #}

<div class="col-md-12">
     {% include "partials/notifications.html.twig" %}
     {{ body|raw }}
</div>

It works. Is it a good practice?

Entity with inheritance on relationship

$
0
0

I would like in Symfony 4 with doctrine use inheritance through a trait to add a new column to 2 different tables.

This is the structure of those 2 tables I want:

  • ManagerChildA has a relation OneToMany with ChildClass
  • ManagerChildB has a relation OneToMany with ChildClass
  • ChildClass is a basic entity

This is what I tried: Class ManagerChildA and ManagerChildB are same excepted the name

/**
 * @ORM\Entity(repositoryClass="App\Repository\ManagerChildARepository")
 */
class ManagerChildA
{
    use TraitManagerChild;

    ...
}

/**
 * @ORM\Entity(repositoryClass="App\Repository\ManagerChildBRepository")
 */
class ManagerChildB
{
    use TraitManagerChild;

    ...
}

This is my trait with the relation :

trait TraitManagerChild
{
    /**
     * @ORM\OneToMany(targetEntity="App\Entity\ChildClass", mappedBy="managerChildA|managerChildB", orphanRemoval=true)
     */
    private $child;

    public function __construct()
    {
        $this->child = new ArrayCollection();
    }

    ...
}

This is the Child entity:

/**
 * @ORM\Entity(repositoryClass="App\Repository\ChildClassRepository")
 */
class ChildClass
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\ManagerChildA|App\Entity\ManagerChildB", inversedBy="child")
     * @ORM\JoinColumn(nullable=false)
     */
    private $managerChild;
    ...
}

What is the easiest way to do this?


Twig print array value with variable index using attribute

$
0
0

I have a Twig global

globals:
    dayindex:
        1: 'Monday'
        2: 'Tuesday'
        3: 'Wednesday'
        4: 'Thursday'
        5: 'Friday'
        6: 'Saturday'
        7: 'Sunday'

Which I would like to access from twig using form collection field value. If i try

{{ dump(attribute(dayindex, form.vars.value.day)) }}

I get Key "" for array with keys "1, 2, 3, 4, 5, 6, 7" does not exist. even though {{ form.vars.value.day }} prints one of the keys.

The folowing code

{% set day = 1 %}
{{ form.vars.value.day }} - {{ day }}
{{ dump(attribute(dayindex, day)) }}

Prints out:

1 - 1

"Monday"

If I replace day with form.vars.value.day I get the mentioned error.

How to add Fontawesome 5 to Symfony 4 using Webpack Encore

$
0
0

I want to add Font Awesome 5 to my Symfony 4 project, this is what I did :

  • I added font awesome to my project using yarn : yarn add --dev @fortawesome/fontawesome-free
  • I imported font awesome in my main scss file (assets/css/app.scss) : @import '~@fortawesome/fontawesome-free/scss/fontawesome';
  • my webpack encore configuration include my scss and js files : .addEntry('js/app', './assets/js/app.js') .addStyleEntry('css/app', './assets/css/app.scss')
  • I compiled : ./node_modules/.bin/encore dev

Everything seems ok, but when I try to use font awesome in my view I only get a square icon instead. The generated app.css file seems ok as I can see the font awesome icons definitions, for example :

.fa-sign-out-alt:before {
    content: "\F2F5";
}

It just seems that the 'content' part is missing, I guess because the fonts are not loaded... Do I need to add something to load the webfonts? I tried to add the font awesome js in my app.js asset file but it doesn't change anything. I also tried to add custom loaders to my webpack encore configuration (like this https://github.com/shakacode/font-awesome-loader/blob/master/docs/usage-webpack2.md#setup-for-webpack-2) I also tried to clear the cache, same result...

Any idea?

Dynamic Prefix in Symfony4 Controller Route Annotation

$
0
0

I want to achieve this annotation in my controller, but i can not find any documentation or a way to have a wildcard(*) prefix in my annotation inside the controller.

    /**
     * @Route("/project/*/{Alias}", name="front-story-page" )
     */
    public function ShowStoryFront(Story $story)
    {
      ..
    }

I tried a whole bunch of different ways but nothing seems to work!

SF4 autenticator failure in CsrfTokenManager

$
0
0

Working with Symfony 4, and making an User environment (using SymfonyCast tutorials) I wrote a LoginFormAuthenticator :

`class LoginFormAuthenticator extends AbstractFormLoginAuthenticator { use TargetPathTrait;

private $entityManager;
private $urlGenerator;
private $csrfTokenManager;
private $passwordEncoder;

public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)
{
    $this->entityManager = $entityManager;
    $this->urlGenerator = $urlGenerator;
    $this->csrfTokenManager = $csrfTokenManager;
    $this->passwordEncoder = $passwordEncoder;
}

public function supports(Request $request)
{
    return 'login' === $request->attributes->get('_route')
        && $request->isMethod('POST');
}

public function getCredentials(Request $request)
{
    $credentials = [
        'username' => $request->request->get('username'),
        'password' => $request->request->get('password'),
        'csrf_token' => $request->request->get('_csrf_token'),
    ];
    $request->getSession()->set(
        Security::LAST_USERNAME,
        $credentials['username']
    );

    return $credentials;
}

public function getUser($credentials, UserProviderInterface $userProvider)
{
    $token = new CsrfToken('authenticate', $credentials['csrf_token']);
    if (!$this->csrfTokenManager->isTokenValid($token)) {
        throw new InvalidCsrfTokenException();
    }

    $user = $this->entityManager->getRepository(User::class)->findOneBy(['username' => $credentials['username']]);
    if (!$user) {
        // fail authentication with a custom error
        throw new CustomUserMessageAuthenticationException('L\'username ne peut pas être trouvé.');
    }

    return $user;
}

public function checkCredentials($credentials, UserInterface $user)
{
    return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
    if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
        return new RedirectResponse($targetPath);
    }

    return new RedirectResponse($this->urlGenerator->generate('core_home'));
}

protected function getLoginUrl()
{
    return $this->urlGenerator->generate('login');
}

} ` But the issue is in the csrf protection. (after many searches, reducing the area of the issue) : I can't connect with my username, a loop give me always the form, with last username...

From the log :

[2019-11-16 15:27:17] security.DEBUG: Checking support on guard authenticator. {"firewall_key":"main","authenticator":"App\Security\LoginFormAuthenticator"} [] [2019-11-16 15:27:17] security.DEBUG: Guard authenticator does not support the request. {"firewall_key":"main","authenticator":"App\Security\LoginFormAuthenticator"} []

Trying to better understand, I put a dd() in the getUser function :

$token = new CsrfToken('authenticate', $credentials['csrf_token']); dd($token);

and the result is :

LoginFormAuthenticator.php on line 63: CsrfToken^ {#345 ▼ -id: "authenticate" -value: "A11CgM6FtyduixvNmOotNkjqbakFCfYPD-TSXv8_PGE" }

We have a Csrf token. Searching more, I put in CsrfTokenManager (from Symfony/Security/Csrf) two dump() an a dd() in the istokenValid function :

    public function isTokenValid(CsrfToken $token)
{
    dump($token);
    $namespacedId = $this->getNamespace().$token->getId();
    dump($namespacedId);
    if (!$this->storage->hasToken($namespacedId)) {
    dd(!$this->storage->hasToken($namespacedId));
     return false;
    }

    return hash_equals($this->storage->getToken($namespacedId), $token->getValue());
}

and the results are :

CsrfTokenManager.php on line 109:

CsrfToken^ {#345 ▼ -id: "authenticate" -value: "YPZIzpw_8eU5Uy3YvV6PwySz4qz8FIz0EzkIwkBd-OQ" }

CsrfTokenManager.php on line 111:

"authenticate"

CsrfTokenManager.php on line 113:

true

So, if I understand well, we have a cookie, and the function return 'this cookie is not valid'...

What's wrong ?

How can regular expressions be used in Doctrine ODM 2.0.2 and PHP 7.3?

$
0
0

I am using symfony 4.3, PHP 7.3, doctrine/mongodb-odm-bundle 4.0.0, doctrine/mongodb-odm 2.0.2. There was a need to use regular expression in the request. It seems that the communication of Doctrine ODM with the MongoDB driver goes through the "strip" - an intermediate alcaeus/mongo-php-adapter driver that emulates working with the Mongo driver for Doctrine.

When I try to use the \MongoRegex class

$qb->field('files.qualities.path')->equals(new \MongoRegex($regexp));

I get an error

Attempted to load class "MongoRegex" from the global namespace. Did you forget a "use" statement?

Well, that might be logical. When I try to use the MongoDB\BSON\Regex class

use MongoDB\BSON\Regex;

$qb = $this->dm->createQueryBuilder(MediaFile::class);
if ($path = $request->query->get('path', null)) {
    $regexp = '/' . str_replace('/', '\/', $path) . '/';
    $qb->field('files.qualities.path')->equals(new Regex($regexp));
}
return $this->paginator->paginate($qb, $request->query->getInt('page', 1), 30);

the query returns an empty collection (the value of $regexp is "/11.35\\/live0.m3u8/"):

vagrant@homestead$ curl -X GET "http://homestead.test/api/v0/media-files?page=1&path=11.35%2Flive0.m3u8"
[]

At the same time, a direct regular expression query in MongoDB returns the expected result:

> db.MediaFile.find({"files.qualities.path": /11.35\/live0.m3u8/}).pretty()
{
    "_id" : ObjectId("5db6de4dfdce27091222c414"),
    "files" : [
        {
            "main_path" : "/hls/2/11.35/index.m3u8",
            "qualities" : [
                {
                    "path" : "/hls/2/11.35/live0.m3u8",
                    "size" : "1920x1080"
                }
            ]
        }
    ]
}

Non-regex code is guaranteed to work. A curl request without specifying the path parameter in the URL returns the results of the selection. What am I doing wrong? How to get regexp result using Query Builder?

Viewing all 3916 articles
Browse latest View live


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