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

tutoriel grafikart Symfony 4 : Image à la une (10/16) Problème LiipImagineBundle [closed]


circular reference when trying to find entities

$
0
0

It's my first Symfony app. I try to do an intervention manager, so I have created three entities: Intervention, Comment and User.
Users are managed by FOSUserBundle.

Classes:
Intervention

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

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

    /**
     * @ORM\Column(type="smallint")
     */
    private $num_rue;

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

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

    /**
     * @ORM\Column(type="decimal", precision=12, scale=9, nullable=true)
     */
    private $lat;

    /**
     * @ORM\Column(type="decimal", precision=12, scale=9, nullable=true)
     */
    private $longi;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    private $description;

    /**
     * @ORM\Column(type="boolean", options={"default":true})
     */
    private $statut;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Comment", mappedBy="intervention", orphanRemoval=true)
     */
    private $comments;

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



    public function getId(): ?int
    {
        return $this->id;
    }

    public function getNumRue(): ?int
    {
        return $this->num_rue;
    }

    public function setNumRue(int $num_rue): self
    {
        $this->num_rue = $num_rue;

        return $this;
    }

    public function getNomRue(): ?string
    {
        return $this->nom_rue;
    }

    public function setNomRue(string $nom_rue): self
    {
        $this->nom_rue = $nom_rue;

        return $this;
    }

    public function getCp(): ?string
    {
        return $this->cp;
    }

    public function setCp(string $cp): self
    {
        $this->cp = $cp;

        return $this;
    }

    public function getLat()
    {
        return $this->lat;
    }

    public function setLat($lat): self
    {
        $this->lat = $lat;

        return $this;
    }

    public function getLongi()
    {
        return $this->longi;
    }

    public function setLongi($longi): self
    {
        $this->longi = $longi;

        return $this;
    }

    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(?string $description): self
    {
        $this->description = $description;

        return $this;
    }

    public function getStatut(): ?bool
    {
        return $this->statut;
    }

    public function setStatut(bool $statut): self
    {
        $this->statut = $statut;

        return $this;
    }

    /**
     * @return Collection|Comment[]
     */
    public function getComments(): Collection
    {
        return $this->comments;
    }

    public function addComment(Comment $comment): self
    {
        if (!$this->comments->contains($comment)) {
            $this->comments[] = $comment;
            $comment->setIntervention($this);
        }

        return $this;
    }

    public function removeComment(Comment $comment): self
    {
        if ($this->comments->contains($comment)) {
            $this->comments->removeElement($comment);
            // set the owning side to null (unless already changed)
            if ($comment->getIntervention() === $this) {
                $comment->setIntervention(null);
            }
        }

        return $this;
    }


}

Comment

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

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

    /**
     * @ORM\Column(type="text")
     */
    private $text;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Intervention", inversedBy="comments")
     * @ORM\JoinColumn(name="intervention_id", referencedColumnName="id")
     */
    private $intervention;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="comments")
     * @ORM\JoinColumn(name="author_id", referencedColumnName="id")
     */ 
    private $author;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getText(): ?string
    {
        return $this->text;
    }

    public function setText(string $text): self
    {
        $this->text = $text;

        return $this;
    }

    public function getIntervention(): ?Intervention
    {
        return $this->intervention;
    }

    public function setIntervention(?Intervention $intervention): self
    {
        $this->intervention = $intervention;

        return $this;
    }

    public function getAuthor(): ?User
    {
        return $this->author;
    }

    public function setAuthor(?User $author): self
    {
        $this->author = $author;

        return $this;
    }
}

User

<?php
// src/Entity/User.php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;


/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Comment", mappedBy="author")
     */
    private $comments;

    public function __construct()
    {
        parent::__construct();
        $this->comments = new ArrayCollection();

    }

    /**
     * @return Collection|Comment[]
     */
    public function getComments(): Collection
    {
        return $this->comments;
    }

    public function addComment(Comment $comment): self
    {
        if (!$this->comments->contains($comment)) {
            $this->comments[] = $comment;
            $comment->setAuthor($this);
        }

        return $this;
    }

    public function removeComment(Comment $comment): self
    {
        if ($this->comments->contains($comment)) {
            $this->comments->removeElement($comment);
            // set the owning side to null (unless already changed)
            if ($comment->getAuthor() === $this) {
                $comment->setAuthor(null);
            }
        }

        return $this;
    }
}

The problem is when I try to access the Intervention with Doctrine, I have a circular reference.

I thought that comments under intervention return user collection which also returns comments...

$repository = $this->getDoctrine()->getRepository(Intervention::class);
$intervention = $repository->findBy(['statut' => 1]);
return $this->json($intervention);

Do you have any suggestion to make my code work please? Thank you.

Solution:

use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

public function getLocations(){
        $encoder = new JsonEncoder();
        $normalizer = new ObjectNormalizer();
        $normalizer->setCircularReferenceHandler(function ($object, string $format = null, array $context = array()) {
            return $object->getId();
        });
        $serializer = new Serializer(array($normalizer), array($encoder));

        $repository = $this->getDoctrine()->getRepository(Intervention::class);
        $intervention = $repository->findBy(['statut' => 1]);



        $response = new Response($serializer->serialize($intervention, 'json'));
        $response->headers->set('Content-Type', 'application/json');
        return $response;

    }

Thanks for your help.


this is just the 1/100 of the dump:

array(3) { [0]=> object(App\Entity\Intervention)#483 (9) { ["id":"App\Entity\Intervention":private]=> int(1) ["num_rue":"App\Entity\Intervention":private]=> int(4) ["nom_rue":"App\Entity\Intervention":private]=> string(14) "rue d’alsace" ["cp":"App\Entity\Intervention":private]=> string(5) "49000" ["lat":"App\Entity\Intervention":private]=> string(12) "47.470484600" ["longi":"App\Entity\Intervention":private]=> string(12) "-0.551233000" ["description":"App\Entity\Intervention":private]=> string(69) "étanchéité toiture

carrelage SB

" ["statut":"App\Entity\Intervention":private]=> bool(true) ["comments":"App\Entity\Intervention":private]=> object(Doctrine\ORM\PersistentCollection)#485 (9) { ["snapshot":"Doctrine\ORM\PersistentCollection":private]=> array(0) { } ["owner":"Doctrine\ORM\PersistentCollection":private]=> *RECURSION* ["association":"Doctrine\ORM\PersistentCollection":private]=> array(15) { ["fieldName"]=> string(8) "comments" ["mappedBy"]=> string(12) "intervention" ["targetEntity"]=> string(18) "App\Entity\Comment" ["cascade"]=> array(0) { } ["orphanRemoval"]=> bool(true) ["fetch"]=> int(2) ["type"]=> int(4) ["inversedBy"]=> NULL ["isOwningSide"]=> bool(false) ["sourceEntity"]=> string(23) "App\Entity\Intervention" ["isCascadeRemove"]=> bool(true) ["isCascadePersist"]=> bool(false) ["isCascadeRefresh"]=> bool(false) ["isCascadeMerge"]=> bool(false) ["isCascadeDetach"]=> bool(false) } ["em":"Doctrine\ORM\PersistentCollection":private]=> object(Doctrine\ORM\EntityManager)#234 (11) { ["config":"Doctrine\ORM\EntityManager":private]=> object(Doctrine\ORM\Configuration)#188 (1) { ["_attributes":protected]=> array(14) { ["entityNamespaces"]=> array(1) { ["App"]=> string(10) "App\Entity" } ["metadataCacheImpl"]=> object(Symfony\Component\Cache\DoctrineProvider)#195 (3) { ["pool":"Symfony\Component\Cache\DoctrineProvider":private]=> object(Symfony\Component\Cache\Adapter\PhpFilesAdapter)#197 (16) { ["createCacheItem":"Symfony\Component\Cache\Adapter\AbstractAdapter":private]=> object(Closure)#199 (2) { ["static"]=> array(1) { ["defaultLifetime"]=> int(0) } ["parameter"]=> array(3) { ["$key"]=> string(10) "" ["$value"]=> string(10) "" ["$isHit"]=> string(10) "" } } ["mergeByLifetime":"Symfony\Component\Cache\Adapter\AbstractAdapter":private]=> object(Closure)#201 (2) { ["static"]=> array(1) { ["getId"]=> object(Closure)#198 (2) { ["this"]=> *RECURSION* ["parameter"]=> array(1) { ["$key"]=> string(10) "" } } } ["parameter"]=> array(3) { ["$deferred"]=> string(10) "" ["$namespace"]=> string(10) "" ["&$expiredIds"]=> string(10) "" } } ["namespace":"Symfony\Component\Cache\Adapter\AbstractAdapter":private]=> string(0) "" ["namespaceVersion":"Symfony\Component\Cache\Adapter\AbstractAdapter":private]=> string(0) "" ["versioningIsEnabled":"Symfony\Component\Cache\Adapter\AbstractAdapter":private]=> bool(false) ["deferred":"Symfony\Component\Cache\Adapter\AbstractAdapter":private]=> array(0) { } ["ids":"Symfony\Component\Cache\Adapter\AbstractAdapter":private]=> array(4) { ["DoctrineNamespaceCacheKey%5B%5D"]=> string(31) "DoctrineNamespaceCacheKey%5B%5D" ["%5BApp%5CEntity%5CUser%24CLASSMETADATA%5D%5B1%5D"]=> string(48) "%5BApp%5CEntity%5CUser%24CLASSMETADATA%5D%5B1%5D" ["%5BApp%5CEntity%5CComment%24CLASSMETADATA%5D%5B1%5D"]=> string(51) "%5BApp%5CEntity%5CComment%24CLASSMETADATA%5D%5B1%5D" ["%5BApp%5CEntity%5CIntervention%24CLASSMETADATA%5D%5B1%5D"]=> string(56) "%5BApp%5CEntity%5CIntervention%24CLASSMETADATA%5D%5B1%5D" } ["maxIdLength":protected]=> NULL ["logger":protected]=> object(Symfony\Bridge\Monolog\Logger)#196 (5) { ["name":protected]=> string(5) "cache" ["handlers":protected]=> array(2) { [0]=> object(Monolog\Handler\FingersCrossedHandler)#94 (11) { ["handler":protected]=> object(Monolog\Handler\StreamHandler)#92 (10) { ["stream":protected]=> NULL ["url":protected]=> string(56) "xxxxxxxxxxxxxxxxxxxxxxxx/var/log/prod.log" ["errorMessage":"Monolog\Handler\StreamHandler":private]=> NULL ["filePermission":protected]=> NULL ["useLocking":protected]=> bool(false) ["dirCreated":"Monolog\Handler\StreamHandler":private]=> NULL ["level":protected]=> int(100) ["bubble":protected]=> bool(true) ["formatter":protected]=> NULL ["processors":protected]=> array(1) { [0]=> object(Monolog\Processor\PsrLogMessageProcessor)#93 (0) { } } } ["activationStrategy":protected]=> object(Symfony\Bridge\Monolog\Handler\FingersCrossed\NotFoundActivationStrategy)#95 (3) { ["blacklist":"Symfony\Bridge\Monolog\Handler\FingersCrossed\NotFoundActivationStrategy":private]=> string(7) "{(^/)}i" ["requestStack":"Symfony\Bridge\Monolog\Handler\FingersCrossed\NotFoundActivationStrategy":private]=> object(Symfony\Component\HttpFoundation\RequestStack)#96 (1) { ["requests":"Symfony\Component\HttpFoundation\RequestStack":private]=> array(1) { [0]=> object(Symfony\Component\HttpFoundation\Request)#4 (23) { ["attributes"]=> object(Symfony\Component\HttpFoundation\ParameterBag)#7 (1) { ["parameters":protected]=> array(5) { ["_route"]=> string(13) "location_list" ["_controller"]=> string(44) "App\Controller\OsimgController::getLocations" ["_route_params"]=> array(0) { } ["_firewall_context"]=> string(34) "security.firewall.map.context.main" ["_security"]=> array(1) { [0]=> object(Sensio\Bundle\FrameworkExtraBundle\Configuration\Security)#407 (3) { ["expression":"Sensio\Bundle\FrameworkExtraBundle\Configuration\Security":private]=> string(21) "has_role('ROLE_USER')" ["statusCode":protected]=> NULL ["message":protected]=> string(14) "Access denied." } } } } ["request"]=> object(Symfony\Component\HttpFoundation\ParameterBag)#5 (1) { ["parameters":protected]=> array(0) { } } ["query"]=> object(Symfony\Component\HttpFoundation\ParameterBag)#6 (1) { ["parameters":protected]=> array(0) { } } ["server"]=> object(Symfony\Component\HttpFoundation\ServerBag)#10 (1) { ["parameters":protected]=> array(66) { ["PATH"]=> string(28) "/usr/local/bin:/usr/bin:/bin" ["TEMP"]=> string(4) "/tmp" ["TMP"]=> string(4) "/tmp" ["TMPDIR"]=> string(4) "/tmp" ["PWD"]=> string(1) "/" ["HTTP_ACCEPT"]=> 

Webpack doesn't compile my javascript file due to Regexp

$
0
0

I'm working on a Symfony 4 project using Webpack Encore. Using yarn encore dev, I get this error :

ERROR  Failed to compile with 2 errors                                 11:45:38

These dependencies were not found:

* core-js/modules/es.regexp.exec in ./assets/js/poteauxskip.js
* core-js/modules/es.string.match in ./assets/js/poteauxskip.js

To install them, you can run: npm install --save core-js/modules/es.regexp.exec core-js/modules/es.string.match

And the Regexp expression doesn't work. I tried to install as they say, but it's the beginning of all sorts of problems. But mainly, it doesn't solves the main problem, which is: why doesn't this work? I see no reason to import anything in my javascript file to use Regexp, I found no mention of this in my whole research for a solution.

poteauxskip.js file :

const $ = require('jquery');

$(".tableau").addClass("d-none");

$(".serie").change(function(){
    updateTableaux();
});

function updateTableaux() {
    var serie1 = $("select#serie1").val() == '?' ? '[0-9A-F]' : $("select#serie1").val();
    var serie2 = $("select#serie2").val() == '?' ? '[0-9A-F]' : $("select#serie2").val();
    var serie3 = $("select#serie3").val() == '?' ? '[0-9A-F]' : $("select#serie3").val();
    var serie4 = $("select#serie4").val() == '?' ? '[0-9A-F]' : $("select#serie4").val();
    var serie5 = $("select#serie5").val() == '?' ? '[0-9A-F]' : $("select#serie5").val();
    var serie6 = $("select#serie6").val() == '?' ? '[0-9A-F]' : $("select#serie6").val();

    var regex = new Regexp("/" + serie1 + serie2 + serie3 + serie4 + serie5 + serie6 + "$/");

    alert("12".match(regex));
}

The alert works if I test it for something else. The other variables also work if I use it without any Regexp. Actually, the new Regexp() or the string.match() are enough to get a compilation error.

package.json :

{
  "devDependencies": {
    "@symfony/webpack-encore": "^0.27.0",
    "bootstrap": "^4.3.1",
    "jquery": "^3.4.1",
    "node-sass": "^4.12.0",
    "popper": "^1.0.1",
    "popper.js": "^1.15.0",
    "sass-loader": "^7.0.1",
    "webpack-notifier": "^1.6.0"
  },
  "name": "hyperbolic-world",
  "version": "2.0.0",
  "description": "Pour favoriser l'immersion dans un espace hyperbolique.",
  "main": "index.js",
  "author": "Julien Busset",
  "license": "CC-BY-4.0",
  "directories": {
    "test": "tests"
  }
}

webpack.config.js :

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

Encore
    // directory where compiled assets will be stored
    .setOutputPath('public/build/')
    // public path used by the web server to access the output path
    .setPublicPath('/build')
    // only needed for CDN's or sub-directory deploy
    //.setManifestKeyPrefix('build/')

    /*
     * ENTRY CONFIG
     *
     * Add 1 entry for each "page" of your app
     * (including one that's included on every page - e.g. "app")
     *
     * Each entry will result in one JavaScript file (e.g. app.js)
     * and one CSS file (e.g. app.css) if you JavaScript imports CSS.
     */
    .addEntry('app', './assets/js/app.js')
    .addEntry('poteauxskip', './assets/js/poteauxskip.js')
    //.addEntry('page1', './assets/js/page1.js')
    //.addEntry('page2', './assets/js/page2.js')

    // When enabled, Webpack "splits" your files into smaller pieces for greater optimization.
    .splitEntryChunks()

    // will require an extra script tag for runtime.js
    // but, you probably want this, unless you're building a single-page app
    .enableSingleRuntimeChunk()

    /*
     * FEATURE CONFIG
     *
     * Enable & configure other features below. For a full
     * list of features, see:
     * https://symfony.com/doc/current/frontend.html#adding-more-features
     */
    .cleanupOutputBeforeBuild()
    .enableBuildNotifications()
    .enableSourceMaps(!Encore.isProduction())
    // enables hashed filenames (e.g. app.abc123.css)
    .enableVersioning(Encore.isProduction())

    // enables @babel/preset-env polyfills
    .configureBabel(() => {}, {
        useBuiltIns: 'usage',
        corejs: 3
    })

    // enables Sass/SCSS support
    .enableSassLoader()
    //.addStyleEntry('global', './assets/scss/global.scss')

    // uncomment if you use TypeScript
    //.enableTypeScriptLoader()

    // uncomment to get integrity="..." attributes on your script & link tags
    // requires WebpackEncoreBundle 1.4 or higher
    //.enableIntegrityHashes()

    // uncomment if you're having problems with a jQuery plugin
    //.autoProvidejQuery()

    // uncomment if you use API Platform Admin (composer req api-admin)
    //.enableReactPreset()
    //.addEntry('admin', './assets/js/admin.js')
;

module.exports = Encore.getWebpackConfig();

webpack encore and jquery ui (dateRangeSlider)

$
0
0

I'm having trouble integrating a jquery-ui plugin with my Symfony app using Webpack Encore. You can see the error (TypeError: t(...).dateRangeSlider is not a function[Learn More]) in the console:

https://date-range-demo.herokuapp.com/en/blog/search

enter image description here

Source code for this is at https://github.com/tacman/range-slider-demo, it's simply the symfony demo with a date range slider on the search page, via the following changes:

add the libraries to package.json from the command line

yarn add jquery-ui jqrangeslider

add to /blog/search.html

<div id="slider">Slider Placeholder</div>

added to assets/js/search.js

import 'jquery-ui'; 
import 'jqrangeslider';

$('#slider').dateRangeSlider();

Assets are build with 'yarn run encore dev', I'm sure it's a simple configuration error but I can't figure out what it is.

Deployment to heroku added a few more things, but are unrelated to the plugin not loading. To see this error locally, simply clone the repo, run composer install && yarn install && yarn run encore dev, then start the server and go to /en/blog/search.

Thanks for any help on this!

Symfony .env security

$
0
0

I would like to secure my symfony project.
And I saw that, in my .env file, the line with the connection to the database:

DATABASE_URL=mysql://username:password@127.0.0.1:3306/my_db  

I think it is not secure because the username and password are in clear.
Could you tell me how to secure my connection to the database and how to hide the connection information or how to securize them ?

Cordially

FOSUserBundle and Symfony 4.4.2 (lts) Problem

$
0
0

I am trying to create clean new project using newest lts version of Symfony and I have this problem installing FOSUserBundle:

https://pastebin.com/bYYdY40E

I don't get it, why this simple config doesn't work? I found tutorials showing the same working, but on Symfony 4.0

Way to reproduce:

composer self-update
symfony new s44_project --full --version=lts
cd s44_project
composer require friendsofsymfony/user-bundle

I'm using PHP 7.4 to run cli commands

Symfony4: Delete issue when OneToMany and OneToOne on the same entity

$
0
0

I have a Trick entity who contains a OneToOne ($mainImage) and OneToMany ($images) association with the same entity. I can't delete a Trick: it tells me there is a foreign key constraint. Of course, because the $mainImage has a FK for Image, and Image has a foreign key for Trick !

If I manually empty the $mainImage and flush before deletion, it works, but it's to tricky, I can't bear such irrespect toward the clineliness of my code!

I think there is a thing to do around "cascade" or "orphanRemoval" attributes of Doctrine but, as you can see below, I've tried them all and I still get the error.

class Trick
{
    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Image", mappedBy="trick", orphanRemoval=true, cascade={"persist", "remove"})
     */
    private $images;

    /**
     * @ORM\OneToOne(targetEntity="App\Entity\Image", cascade={"persist", "remove"}, orphanRemoval=true)
     * @JoinColumn(name="main_image_id", referencedColumnName="id", onDelete="set null")
     */
    private $mainImage;

}

and an Image entity:

class Image
{
    /**
     * @ORM\ManyToOne(targetEntity="Trick", inversedBy="images")
     * @ORM\JoinColumn(nullable=false)
     */
    private $trick;
}

Could someone help me please ? You'll get all my gratitude !

How to change the user locale with Symfony 4?

$
0
0

Happy new year :)

I'm trying to change the user locale with Symfony from a field "locale" in the database. I read the Symfony manual (how to sticky a session for example), but nothing works in my application. Translator still gets the default locale... I created listeners, subscribers... to dynamically change the locale, but as they are loaded before the firewall listener, I'm unable to change the current value... I tried to change the priority subscriber, but I lost the user entity... I tried to set locale request in controllers, but I think it's too late. I don't want to add locales in URLS.

Here my subscriber - listener - code:

public function onKernelRequest(RequestEvent $event)
{
   $user = $this->tokenStorage->getToken()->getUser();
   $request = $event->getRequest();
   $request->setLocale($user->getLocale());
}  

In subscribers, I added:

public static function getSubscribedEvents()
{
   return [
     KernelEvents::REQUEST => [['onKernelRequest', 0]],
   ];
}

Thanks all!

Alexander


503 error with Symfony 4 and Debug enabled

$
0
0

I have an issue with my Symfony 4.1 project. My server is on PHP FPM 7.2 and Apache 2.4. When i enable the Debug component in a dev environment, i cannot access my application and i have a 503 error. On the apache server, i can see this error:

AH01067: Failed to read FastCGI header

no error in the fpm container. At first i thought about a memory_limit issue, but the error disappear when i activate XDebug on the fpm container. And XDebug eats quite a lot of memory, so i don't know where is the problem.

If anybody has any idea, it will be really appreciated.

Thx, JM

How to exclude deprecation messages from logs in Symfony 4?

$
0
0

I have migrated an application from Symfony 3.4 to Symfony 4.4.

Now I have a lot of deprecations for each request/ Sf command (I can't fix that deprecations).

How can I exclude deprecations from the log for this Symfony App?

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)%'

How to convert Serializer annotations to YML or XML configuration?

$
0
0

We've been tasked with converting all the serialization annotations in our classes to dedicated configuration classes.

There are a few dozen classes in this application, with at around 20 of them with custom annotations for the serializer (with the rest being serialized without the need of any custom configuration).

Is there a way to produce configuration files (XML preferred, but YAML acceptable) from the existing serializer configuration?

E.g. starting from this:

namespace Acme;

use Symfony\Component\Serializer\Annotation\Groups;

class MyObj
{
    /**
     * @Groups({"group1", "group2"})
     */
    public $foo;

    /**
     * @Groups("group3")
     */
    public function getBar() 
    {
        return $this->bar;
    }
// rest of the class

}

Generate this:

Acme\MyObj:
    attributes:
        foo:
            groups: ['group1', 'group2']
        bar:
            groups: ['group3']

Or this:

<?xml version="1.0" ?>
<serializer xmlns="http://symfony.com/schema/dic/serializer-mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/serializer-mapping
      https://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd">
   <class name="Acme\MyObj">
       <attribute name="foo">
           <group>group1</group>
           <group>group2</group>
       </attribute>

        <attribute name="bar">
           <group>group3</group>
       </attribute>
   </class>
</serializer>

Symfony CSRF token

$
0
0

I work under Symfony 4.3.1. In the config/packages/framework.yaml file I deleted the following line:

cookie_lifetime: 2592000

Since then, on each form submission my clients have the error:

The CSRF Token is invalid. Please try to resubmit the form.

Is there a way to avoid this error after each modification of cookies?

By clearing browser cookies, the problem is resolved, but it is very annoying to ask customers to delete cookies.

How to list all defined serializer groups, and related settings?

$
0
0

How can I retrieve a list of all defined Serializer groups (and related settings, like "serialized_name" or "max_depth")?

These can be defined via annotations, XML, or YAML; but it's rather clumsy having to check all the different files; I'd like to produce a listing of all configured settings.

SerializerInterface nor NormalizerInterface have any method that looks helpful.

How can I achieve this?

Symfony routing resource and Bundle name

$
0
0

I an trying to include a file into the Symfony 4 routes, and can't figure out what would be the correct way to put in the Bundle name. My routes.yml:

icatcher_builder:
    # loads routes from the given routing file stored in some bundle
    resource: '@ICatcher/Builder/Resources/config/routes.yaml'

My bundles.php:

App\ICatcher\Builder\Builder::class => ['dev' => true, 'test' => true],

And I get this error:

An exception has been thrown during the rendering of a template ("Bundle "ICatcher" does not exist or it is not enabled. Maybe you forgot to add it in the registerBundles() method of your App\Kernel.php file? in @ICatcher/Builder/Resources/config/routes.yaml (which is being imported from "[PATH]\config/routes.yaml"). Make sure the "ICatcher/Builder/Resources/config/routes.yaml" bundle is correctly registered and loaded in the application kernel class. If the bundle is registered, make sure the bundle path "@ICatcher/Builder/Resources/config/routes.yaml" is not empty.").

If I just copy the routes into the main route.yml file instead of including an external resource - all works fine.


One form for multiple twig views - Symfony4

$
0
0

:) How can I pass one form to multiple twig views? I have a search bar that I want to pass to every view I created form and it's controller and then I have tried to paste this into base template:

{{ render(controller('App\\Controller\\SearchbarController::searchAction')) }}

but got error

Maximum function nesting level of '1024' reached, aborting!

My action in controller:

public function searchAction(Request $request): Response
{
    $form = $this->createForm(searchbarFormType::class);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $name = $form['name']->getData();
        return $this->redirectToRoute('search_result', [
            'name' => $name,
        ]);
    }

    return $this->render('partials/searchbar.html.twig', [
      'searchbarFormType'  => $form->createView(),
    ]);
}

Do you know how could I solve my problem? or you know better solution?

Getting form into another form without displaying data but having to input data

$
0
0

I have a form called new_appointment_type and a form called new_customer_type and they have to be 1 form basically.

the new_appointment_type form looks like:

use App\Entity\Appointment;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class new_appointmentType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('barber_id')
            ->add('treatment_id')
            ->add('date')
            ->add('time')
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Appointment::class,
        ]);
    }
}

And the new_customer_type looks like this:

use App\Entity\Customer;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class new_customerType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('phone')
            ->add('email')
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Customer::class,
        ]);
    }
}

How would i get the name,phone and email entities to be in the new_appointment_type? And it shouldn't display the data but as an input as such:
enter image description here

I tried looking at the embed collection of forms on the symfony docs but it didn't really help me out. (https://symfony.com/doc/current/form/form_collections.html)

Thanks in advance, all the help is appreciated.

Cannot resolve parameter in boolean node in Symfony config files

$
0
0

I have a (private) bundle that expects boolean parameter:

$rootNode
    ->addDefaultsIfNotSet()
    ->children()
        ->booleanNode('property_cache_enabled')->defaultTrue()->end()
    ->end()

When I want it to resolve to kernel.debug it throws the exception:

Invalid type for path "rvlt_digital_symfony_api.property_cache_enabled". Expected boolean, but got string.

This is the relevant part of configuration:

rvlt_digital_symfony_api:
  property_cache_enabled: '%kernel.debug%'

How can this be solved? When I searched for this issue I only found stuff related to environment variables casting; which didn't help as this is not an environment variable.

Issue programmatically authenticating Users for PhpUnit functional test - Unmanaged by Doctrine - Symfony 4.3

$
0
0

I'm trying to get a simple "200 Response" test to work for a part of a website requiring an authenticated user. I think I've got the creation of the Session working, as during debugging the Controller function is called and a User is retrieved (using $this->getUser()).

However, afterwards the function fails with the following message:

1) App\Tests\Controller\SecretControllerTest::testIndex200Response
expected other status code for 'http://localhost/secret_url/':
error:
    Multiple non-persisted new entities were found through the given association graph:

 * A new entity was found through the relationship 'App\Entity\User#role' that was not configured to cascade persist operations for entity: ROLE_FOR_USER. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade
persist this association in the mapping for example @ManyToOne(..,cascade={"persist"}).
 * A new entity was found through the relationship 'App\Entity\User#secret_property' that was not configured to cascade persist operations for entity: test123. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade pe
rsist this association in the mapping for example @ManyToOne(..,cascade={"persist"}). (500 Internal Server Error)

Failed asserting that 500 matches expected 200.

This would make sense if this was not already stored in the (MySQL) database and retrieved with Doctrine. The records are created using Fixtures on each run/for each test. This is why in the Controller $this->getUser() functions as expected.

The test I'm wanting to work:

public function testIndex200Response(): void
{
    $client = $this->getAuthenticatedSecretUserClient();

    $this->checkPageLoadResponse($client, 'http://localhost/secret_url/');
}

Get a user:

protected function getAuthenticatedSecretUserClient(): HttpKernelBrowser
{
    $this->loadFixtures(
        [
            RoleFixture::class,
            SecretUserFixture::class,
        ]
    );

    /** @var User $user */
    $user = $this->entityManager->getRepository(User::class)->findOneBy(['username' => 'secret_user']);

    $client = self::createClient(
        [],
        [
            'PHP_AUTH_USER' => $user->getUsername(),
            'PHP_AUTH_PW'   => $user->getPlainPassword(),
        ]
    );

    $this->createClientSession($user, $client);

    return $client;
}

Create a session:

// Based on https://symfony.com/doc/current/testing/http_authentication.html#using-a-faster-authentication-mechanism-only-for-tests
protected function createClientSession(User $user, HttpKernelBrowser $client): void
{
    $authenticatedGuardToken = new PostAuthenticationGuardToken($user, 'chain_provider', $user->getRoles());
    $tokenStorage            = new TokenStorage();
    $tokenStorage->setToken($authenticatedGuardToken);

    $session = self::$container->get('session');
    $session->set('_security_<security_context>', serialize($authenticatedGuardToken));
    $session->save();

    $cookie = new Cookie($session->getName(), $session->getId());
    $client->getCookieJar()->set($cookie);

    self::$container->set('security.token_storage', $tokenStorage);
}

This works for the creating of the client, session and cookie.

When the Request is executed to the $url in the first function, it gets into the endpoint, confirming the User is indeed authenticated.

According to the documentation here a User should be "refreshed" from via the configured provider (using Doctrine in this case) to check if a given object matches a stored object.

[..] At the beginning of the next request, it's deserialized and then passed to your user provider to "refresh" it (e.g. Doctrine queries for a fresh user).

I would expect this would also ensure that the session User is replaced with a Doctrine managed User object to prevent the error above.

How can I go about solving that the User in the session becomes a managed User during PhpUnit testing?

(Note: the production code works without any issue, this problem only arises during testing (legacy code now starting to get tests))

Symfony Always Include Route Default Values

$
0
0

So basically I am trying to achieve this: New in Symfony 4.3: Always Include Route Default Values

I have a task entity, which has multiple states like new, open& closed.

For this reason I am trying to generate a route /tasks/new/tasks/open/tasks/closed. However, if there is no option set in my route, I want it to use new as default and also add it to the url.

My controller:

/**
 * @Route("/tasks/{!status?new}", name="app_tasks")
 */
public function tasks(TaskRepository $taskRepository, string $status)
{
    $tasks = $taskRepository->findBy(['status' => $status]);
    return $this->render('tasks/index.html.twig', ['tasks' => $tasks]);
}

However this results into not a single matching route.

/tasks/new  => no route found  => should work
/tasks/open => no route found  => should work
/tasks      => no route found  => should work & route should be /tasks/new
etc.

The main issue seems to be the ! before status. If I remove it entirely, everything works as expected, except that the route for new tasks looks like /tasks and not like /tasks/new - what I actually want.

I already tried to clear my cache - not working though. Symfony version is 4.4.2.

Viewing all 3919 articles
Browse latest View live


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