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

FOSRestBundle's format_listener prevents http_basic challenge

$
0
0

I'm trying to setup my PHP/Symfony4/FOSRestBundle API to accept both JWT and HTTP-Basic authentication but the format_listener appears to be intercepting the UnauthorizedHttpException exception an serializing it thus preventing the auth header from being returned as expected.

I have things configured like so:

security:
    firewalls:
        api:
            pattern:  ^/api/
            stateless: true
            http_basic: ~
            entry_point: app.basic_entry_point
            guard:
                authenticators:
                    - lexik_jwt_authentication.jwt_token_authenticator
    access_control:
        - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/api/,      roles: IS_AUTHENTICATED_FULLY }

fos_rest:
    unauthorized_challenge: 'Basic realm="%env(AUTH_REALM)%"'
    access_denied_listener:
        json: true
    format_listener:
        enabled: true
        rules:
            - { path: '^/api', priorities: ['json'], fallback_format: json }
            - { path: '^/', stop: true }
services:
    app.basic_entry_point:
        class: App\Security\Http\EntryPoint\BasicAuthenticationEntryPoint
        arguments:
            - '%env(AUTH_REALM)%'

The custom version of BasicAuthenticationEntryPoint extends the stock version to return JSON content along with the auth header.

JWT auth is working fine. If I disable the format_listener, without JWT I get the auth header in the response. What's the trick I'm missing to allow me to enable the format_listener and get that auth header in the response?


All entities made by doctrine does not contains properties

$
0
0

good afternoon, I'm trying to use donctrine to make entities. My purpose is to make all the entities to generate the database from doctrine with a simple migration. My issue is that when i made my an entities, doctrine only generate the class names but it doesn't generate any properties... So when i migrate, doctrine builds empty tables.

Thx

This is what a generation made...

<?php

namespace App\Repository;

use App\Entity\Login;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Persistence\ManagerRegistry;

/**
 * @method Login|null find($id, $lockMode = null, $lockVersion = null)
 * @method Login|null findOneBy(array $criteria, array $orderBy = null)
 * @method Login[]    findAll()
 * @method Login[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class LoginRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Login::class);
    }

    // /**
    //  * @return Login[] Returns an array of Login objects
    //  */
    /*
    public function findByExampleField($value)
    {
        return $this->createQueryBuilder('l')
            ->andWhere('l.exampleField = :val')
            ->setParameter('val', $value)
            ->orderBy('l.id', 'ASC')
            ->setMaxResults(10)
            ->getQuery()
            ->getResult()
        ;
    }
    */

    /*
    public function findOneBySomeField($value): ?Login
    {
        return $this->createQueryBuilder('l')
            ->andWhere('l.exampleField = :val')
            ->setParameter('val', $value)
            ->getQuery()
            ->getOneOrNullResult()
        ;
    }
    */
}

Symfony 4 autowiring argument not working

$
0
0

I'm trying to autowire the UrlGeneratorInterface into a DTO to use the generate method in my DTO,

I have this in my DTO:

namespace App\DTO;

use JMS\Serializer\Annotation as Serializer;
use JMS\Serializer\Annotation\ExclusionPolicy;
use JMS\Serializer\Annotation\Expose;
use App\Entity\News;
use App\Application\Sonata\MediaBundle\Entity\Media;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;


/**
 * @ExclusionPolicy("all")
 *
 */
class NewsDTO
{

    /**
     * @var integer|null
     * @Serializer\Groups({"news"})
     * @Expose
     */
    public $id;

    /**
     * @var string|null
     * @Serializer\Groups({"news"})
     * @Expose
     */
    public $title;


    /**
     * @var string|null
     * @Serializer\Groups({"news"})
     * @Expose
     */
    public $text;

    /**
     * @var string|null
     * @Serializer\Groups({"news"})
     * @Expose
     */
    public $cover_image;


    /**
     * @var string|null
     * @Serializer\Groups({"news"})
     * @Expose
     */
    public $description;

    /**
     * @var string|null
     * @Serializer\Groups({"news"})
     * @Expose
     */
    public $web_url;

    /**
     * @var string|null
     * @Serializer\Groups({"news"})
     * @Expose
     */
    public $link;

    /**
     * @var datetime|null
     * @Serializer\Groups({"news"})
     * @Expose
     */
    private $news_date;

    private $router;

    public function __construct(UrlGeneratorInterface $urlGenerator){
        $this->router = $router;
    }

and my service.yaml:

parameters:
    locale: 'fr'

services:
    # default configuration for services in *this* file
    _defaults:
        autowire: true      # Automatically injects dependencies in your services.
        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Application,Kernel.php}'

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

    dto.news :
        class: App\DTO\NewsDTO
        arguments: 
            $urlGenerator: ['@router.default']

    # add more service definitions when explicit configuration is needed
    # please note that last definitions always *replace* previous ones
    admin.videos:
        class: App\Admin\VideoAdmin
        arguments: [~, App\Entity\Video, ~]
        tags:
            - { name: sonata.admin, manager_type: orm, label: Video }
    admin.news:
        class: App\Admin\NewsAdmin
        arguments: [~, App\Entity\News, ~]
        tags:
            - { name: sonata.admin, manager_type: orm, label: Actualités }
    admin.prerolls:
        class: App\Admin\PrerollAdmin
        arguments: [~, App\Entity\Preroll, ~]
        tags:
            - { name: sonata.admin, manager_type: orm, label: Preroll }

But the error returned is:

"message": "Too few arguments to function App\\DTO\\NewsDTO::__construct(), 0 passed in /data/www/api-dev.chartres.live/www/src/Representation/Actus.php on line 35 and exactly 1 expected"

Loading user locale when logging in automatically with remember_me token in Symfony 4

$
0
0

Using Symfony 4 I managed to have my users save their locale prefs in database and loading these when they "fully" log in (with login form).

But I don't see how to load the user's locale prefs when logging in automatically with remember_me token.

This is my UserLocaleSubscriber:

<?php

namespace App\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;

/**
 * Stores the locale of the user in the session after the
 * login. This can be used by the LocaleSubscriber afterwards.
 */
class UserLocaleSubscriber implements EventSubscriberInterface
{
    private $session;

    public function __construct(SessionInterface $session)
    {
        $this->session = $session;
    }

    public function onInteractiveLogin(InteractiveLoginEvent $event)
    {
        $user = $event->getAuthenticationToken()->getUser();

        $token = get_class ($event->getAuthenticationToken());


        if (null !== $user->getLocale()) {
            $this->session->set('_locale', $user->getLocale());
        }
    }

    public static function getSubscribedEvents()
    {
        return array(
            SecurityEvents::INTERACTIVE_LOGIN => 'onInteractiveLogin',
        );
    }
}

My LocaleSubscriber:

<?php

namespace App\EventSubscriber;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class LocaleSubscriber implements EventSubscriberInterface
{
    private $defaultLocale;

    public function __construct($defaultLocale = 'fr')
    {
        $this->defaultLocale = $defaultLocale;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        if (!$request->hasPreviousSession()) {
            return;
        }

        // try to see if the locale has been set as a _locale routing parameter
        if ($locale = $request->attributes->get('_locale')) {
            $request->getSession()->set('_locale', $locale);
        } else {
            // if no explicit locale has been set on this request, use one from the session
            $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
        }
    }

    public static function getSubscribedEvents()
    {
        return array(
            // must be registered before (i.e. with a higher priority than) the default Locale listener
            KernelEvents::REQUEST => array(array('onKernelRequest', 20)),
        );
    }
}

My services.yaml

    App\EventSubscriber\UserLocaleSubscriber:
    tags:
    - { name: kernel.event_listener, event: security.interactive_login, method: onInteractiveLogin, priority: 15 }

Any ideas on how to achieve this ?

Couldn't use listen to remember_me in Symfony2 as classes from example were deprecated.

Login dans symfony4.3.6 [closed]

$
0
0

Good evening or hello depending on the time you read this post! I have a big problem on symfony4.3.6 since already 2 days. in fact my login form does not pass every time I try to connect to my site this one always redirects me on the login page. When I look at the logs, I am told that the password is not the good one, but I have understood it correctly. I have already tried with several users in vain. If someone has already encountered the same problem I am a taker. Thank you !

Symfony 4 Service Injection Too Few Arguments

$
0
0

In my Symfony 4 project I've created a HelloBlock class in the /src/Blocks/Hello/HelloBlock.php file.

Here's its constructor...

public function __construct(EntityManagerInterface $entityManager)
{
    $this->em = $entityManager;
}

And then in my services.yaml I've added this...

    App\Blocks\:
        resource: '../src/Blocks'
        tags: ['controller.service_arguments']

When running my code (dev environment, cache cleared, etc) I'm getting the "Too few arguments" error. It's not injecting the dependency.

Can anyone help? I thought this is what the Symfony DI is supposed to do.

Thanks!

Doctrine\DBAL\DBALException: Platform mssql does not support offset values in limit queries

$
0
0

The error is pretty straight forward. I use Symfony 4 and MSSQL Server as a database server with below configuration:

driver: 'sqlsrv'
url: 'mssql://username:password@host:1433/db'

The error happens when I use setFirstResult()

$entityManager->createQueryBuilder()->select('u')->from(UserEntity::class, 'u')
        ->setFirstResult(20)->setMaxResults(20)
        ->getQuery()->getArrayResult();

Error message:

In AbstractPlatform.php line 3359:
[Doctrine\DBAL\DBALException]                                    
Platform mssql does not support offset values in limit queries.

Trace:

 () at /var/www/html/ple-studio/vendor/doctrine/dbal/lib/Doctrine/DBAL/Platforms/AbstractPlatform.php:3359
 Doctrine\DBAL\Platforms\AbstractPlatform->modifyLimitQuery() at /var/www/html/ple-studio/vendor/doctrine/orm/lib/Doctrine/ORM/Query/SqlWalker.php:545
 Doctrine\ORM\Query\SqlWalker->walkSelectStatement() at /var/www/html/ple-studio/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Exec/SingleSelectExecutor.php:42
 Doctrine\ORM\Query\Exec\SingleSelectExecutor->__construct() at /var/www/html/ple-studio/vendor/doctrine/orm/lib/Doctrine/ORM/Query/SqlWalker.php:278
 Doctrine\ORM\Query\SqlWalker->getExecutor() at /var/www/html/ple-studio/vendor/doctrine/orm/lib/Doctrine/ORM/Query/Parser.php:398
 Doctrine\ORM\Query\Parser->parse() at /var/www/html/ple-studio/vendor/doctrine/orm/lib/Doctrine/ORM/Query.php:283
 Doctrine\ORM\Query->_parse() at /var/www/html/ple-studio/vendor/doctrine/orm/lib/Doctrine/ORM/Query.php:295
 Doctrine\ORM\Query->_doExecute() at /var/www/html/ple-studio/vendor/doctrine/orm/lib/Doctrine/ORM/AbstractQuery.php:967

The solution that works for me is to manually use raw query:

$sql .= ' OFFSET ' . $offset . ' ROWS FETCH NEXT ' . $itemPerPage . ' ROWS ONLY';

But this solution will kill the purpose of using ORM and it will not work if I switch to MySQL.

What is the proper way to solve the error above?

how to use form builder to make form from entity relation of entity in symfony4

$
0
0

TL;TR:How to make form fields from formbuilder with relation column

Here is my Level Entity

<?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\LevelRepository")
 */
class Level
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

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

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Area", mappedBy="levelid", orphanRemoval=true)
     */
    private $areas;

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

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

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

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

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

        return $this;
    }

    /**
     * @return Collection|Area[]
     */
    public function getAreas(): Collection
    {
        return $this->areas;
    }

    public function addArea(Area $area): self
    {
        if (!$this->areas->contains($area)) {
            $this->areas[] = $area;
            $area->setLevelid($this);
        }

        return $this;
    }

    public function removeArea(Area $area): self
    {
        if ($this->areas->contains($area)) {
            $this->areas->removeElement($area);
            // set the owning side to null (unless already changed)
            if ($area->getLevelid() === $this) {
                $area->setLevelid(null);
            }
        }

        return $this;
    }
}

and this is my Area Entity

<?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\AreaRepository")
 */
class Area
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Property", mappedBy="area")
     */
    private $property;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Level", inversedBy="areas")
     * @ORM\JoinColumn(nullable=false)
     */
    private $levelid;

    public function __construct()
    {
        $this->property = new ArrayCollection();
        $this->projects = new ArrayCollection();

    }

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

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

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

    public function addProperty(property $property): self
    {
        if (!$this->property->contains($property)) {
            $this->property[] = $property;
            $property->setArea($this);
        }

        return $this;
    }

    public function removeProperty(property $property): self
    {
        if ($this->property->contains($property)) {
            $this->property->removeElement($property);
            // set the owning side to null (unless already changed)
            if ($property->getArea() === $this) {
                $property->setArea(null);
            }
        }

        return $this;
    }

    public function getLevelid(): ?Level
    {
        return $this->levelid;
    }

    public function setLevelid(?Level $levelid): self
    {
        $this->levelid = $levelid;

        return $this;
    }

   }

Area connected to Level

And this is Area Form builder

<?php

namespace App\Form;

use App\Entity\Area;
// use App\Entity\District;
use App\Entity\Level;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;

class AreaType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('Level', EntityType::class, array(
                // looks for choices from this entity
                'class' => Level::class,
                'label' => 'Level',
                // uses the User.username property as the visible option string
                'choice_label' => 'name',
            ))
        ;
    }

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

And the error is

Neither the property "Level" nor one of the methods "getLevel()", "level()", "isLevel()", "hasLevel()", "__get()" exist and have public access in class "App\Entity\Area".


Warning fsockopen() in Symfony 4

$
0
0

(sorry for my english ... i'm french)

I'm using Symfony 4 and PHP 7.2.1 (the one in MAMP) and MySQL. My computer is an iMac with mac OS X HighSierra. The error message in var/log/dev.log is the following one :

php.DEBUG: Warning: fsockopen(): unable to connect to 127.0.0.1:8000 (Connection refused) ...

In my PHP.ini i have the option "allow_url_fopen = On"

How can i found an issue to correct this warning ? Thank you for helping.

How to enable cache in dev mode?

$
0
0

I'm working on a heavy-load Symfony optimization, trying out template cache, doctrine cache, etc. But unless I'm wrong, those caches are disabled in dev, so it's hard to evaluate the effect of those optimizations.

Is there a way to enable caching in dev mode, so I can the application optimization results while keeping the debug bar?

Symfony4 - Refresh user roles on every request

$
0
0

I've faced with problem trying to implement simple autorization system in SF4.

class User implements UserInterface {
     // some properties...

     /**
     * @var RoleGroup|null
     * @ORM\ManyToOne(targetEntity="App\Entity\RoleGroup")
     * @ORM\JoinColumn(nullable=true)
     */
     private $roleGroup;

    /** method imposed by built-in UserInterface (SF4) **/
    public function getRoles(): array {
        if(null === $this->roleGroup) return ['ROLE_DEFAULT'];

        /** returns an array of role names **/
        return $this->roleGroup->getRoles();
    }
}

UserProvider:

class UserProvider implements UserProvider 
{   
    public function refreshUser(UserInterface $user)
    {
        $qb = $this->createQueryBuilder('u');
        $qb->select('u, r');
        $qb->leftJoin('u.roleGroup', 'r');
        $qb->where($qb->expr()->eq('u.id', $user->getId()));


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

Steps symfony follows:

  1. Authentication: after success: The user object is serialized to session (whole, by default), roles are stored separately enter image description here
  2. Refresh user: Security component triggers UserProviderInterface::refreshUser(UserInterface $user) method, coompares them and if objects are not equal it de-authenticates the user (according to documentation)

It's clear and easy to understand, but:

  1. Why is the result of an UserInterface::getRoles() separated?
  2. Why doesn't SF4 get roles from the serialized User object?
  3. Why roles are placed into the session ONCE (after successful authentication)?
  4. Why aren't the roles refreshed if an UserProvider refreshes an user every request (by default)?
  5. Why doesn't always_authenticate_before_granting => true refresh the user's roles?

Problem: I would like to refresh the user's roles on every request. I am aware I can get rid of the problem via a listener that will refresh token every request, but is there any diffrent solotion?

Symfony 4 Bundle: AuthenticationUtils but no such service exists

$
0
0

I'm trying to make a Bundle (Symfony 4) for managing users of all our projects and I'm having a problem.

Cannot autowire argument $authenticationUtils of "App\Aroban\Bundle\UtilisateurBundle\Controller\SecurityController::login()": it references class "Symfony\Component\Security\Http\Authentication\AuthenticationUtils" but no such service exists.

I do not understand why the service is not injected...

In the composer.json of the project, there is "symfony/security-bundle": "4.3.*"

In the Bundle:

SecurityController.php

<?php

namespace App\Aroban\Bundle\UtilisateurBundle\Controller;

use App\Aroban\Bundle\UtilisateurBundle\Entity\Utilisateur;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Swift_Mailer;

class SecurityController extends AbstractController
{
    public function login(AuthenticationUtils $authenticationUtils): Response
    {
        $error = $authenticationUtils->getLastAuthenticationError();
        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render('@Utilisateur/security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
    }

.......
}

Configuration.php

<?php

namespace App\Aroban\Bundle\UtilisateurBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('utilisateur');
        $rootNode = $treeBuilder->getRootNode();

        return $treeBuilder;
    }
}

UtilisateurExtension.php

<?php

namespace App\Aroban\Bundle\UtilisateurBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Loader;

class UtilisateurExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container): void
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('services.yaml');
    }
}

services.yaml (bundle)

services:
  _defaults:
    autowire: true      # Automatically injects dependencies in your services.
    autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.
    public: false       # Allows optimizing the container by removing unused services; this also means

  App\Aroban\Bundle\UtilisateurBundle\:
    resource: '../../*'
    exclude: '../../{Entity,Migrations,Tests,Kernel.php}'

  App\Aroban\Bundle\UtilisateurBundle\Controller\:
    resource: '../../Controller/*'
    tags: ['controller.service_arguments']

When I execute the command

php bin/console debug:container | grep security

I do not see the service ...

Symfony\Component\Security\Csrf\CsrfTokenManagerInterface alias for "security.csrf.token_manager"
Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface alias for "security.csrf.token_generator"
Symfony\Component\Security\Csrf\TokenStorage\TokenStorageInterface alias for "security.csrf.token_storage"
doctrine.orm.security.user.provider Symfony\Bridge\Doctrine\Security\User\EntityUserProvider
maker.security_config_updater Symfony\Bundle\MakerBundle\Security\SecurityConfigUpdater
security.csrf.token_generator Symfony\Component\Security\Csrf\TokenGenerator\UriSafeTokenGenerator
security.csrf.token_manager Symfony\Component\Security\Csrf\CsrfTokenManager
security.csrf.token_storage Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage
twig.extension.security_csrf Symfony\Bridge\Twig\Extension\CsrfExtension
twig.runtime.security_csrf Symfony\Bridge\Twig\Extension\CsrfRuntime
// To search for a specific service, re-run this command with a search term. (e.g. debug:container
// log)

Thanks for your help!

Put environment in prod and remove the profiler Symfony 4

$
0
0

I am putting my website in production, but I have a problem with the environment.As you can see in the screenshot below, the site remains in "dev" mode

enter image description here

However, I already modify my .env file as follows:

APP_ENV=prod
APP_DEBUG=0
APP_SECRET=secretthings
#TRUSTED_PROXIES=127.0.0.1,127.0.0.2
#TRUSTED_HOSTS=localhost,example.com
###< symfony/framework-bundle ###

should I change another file or do something else so that my site is finally operational?

Thank you for your answers

Saml 2.0 Identity Provider with Symfony 4

$
0
0

I'am trying to implement an saml 2.0 identity provider with symfony, but can't decide which bundle to use, lightsaml seems to be used for Service providers, others like samplesamlphp or oneloginsaml are either with native php or symfony 2, can you please recommend a tutorial or a bundle i can use to implement this identity provider

I tried this tutorial but can't see it working

Encore webpack or assets generating wrong path to image in symfony 4

$
0
0

I am trying to learn to use encore webpack. Well, following this guideEncore + webpack + bootstrap sass and this guide Symfony 4+ enconre + Bootstrap 4 I got symfony to use the scss and js assets I use. But the problem is when I insert an image in my scss code (for a bg) the relative url I see in the browser is wrongly generated.

Webpack is generating the image here:

public\build\images\2.f26e9a05.jpg

But the url in the browser ends up like this:

/public/build/build/images/2.f26e9a05.jpg

(if I delete the second "build/" the image loads like it should) this is my folder estructure:

assets:
   css:
     app.scss
   js:
     app.js
public:
   images:
     2.jpg

app.scss:

@import '~bootstrap/scss/bootstrap';
...
.parallax {
background-image: url("images/2.jpg");
}

Webpack.config.js:

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

Encore
// the project directory where compiled assets will be stored
.setOutputPath('public/build/')
// the public path used by the web server to access the previous directory
.setPublicPath('build')
// the public path you will use in Symfony's asset() function - e.g. asset('build/some_file.js')
.setManifestKeyPrefix('build/')

.cleanupOutputBeforeBuild()
.enableSourceMaps(!Encore.isProduction())

// the following line enables hashed filenames (e.g. app.abc123.css)
//.enableVersioning(Encore.isProduction())

// uncomment to define the assets of the project
.addEntry('app', './assets/js/app.js')
//.addStyleEntry('css/app', './assets/css/app.scss')

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

// uncomment if you use Sass/SCSS files
.enableSassLoader()

// uncomment for legacy applications that require $/jQuery as a global variable
.autoProvidejQuery()
;

module.exports = Encore.getWebpackConfig();

index.html.twig:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{% block title %}100Monos{% endblock %}</title>
    {% block stylesheets %}
    <link rel="stylesheet" href="{{ asset('build/app.css') }}">
    {% endblock %}
</head>
<body>

    <div class="container">
    {% block body %}
    <div id="Nosotros" class="pantalla d-flex align-items-center parallax">
        <div class="contenido">
            <h1>100Monos</h1>
            <h3>Nuestra Web es mala porque pasamos todo el tiempo haciendo la suya</h3>
            <img src="{{ asset('images/1.jpg') }}">             
        </div>
    </div>

    {% endblock %}
    {% block javascripts %}
      <script src="{{ asset('build/app.js') }}"></script>
    {% endblock %}
    </div>
</body>
</html>

Assets not install in symfony 4

$
0
0

I read symfony documentation for Web Assets and create /assets directory in root of my project then run command php bin/console assets:install but get:

[OK] No assets were provided by any bundle.

I store one CSS file in assets directory but didn't install in /public

how should I do?

Symfony 4, Doctrine and AWS RDS read replica usage

$
0
0

I'm about to embark on using RDS with a master read/write and slave read-only setup.

I've read about the Doctrine MasterSlaveConnection type.

However, there will be some endpoints I create that I would like to use the read-only replica (most of my GET endpoints) and some will need to write data (PUT, PATCH, DELETE endpoints).

I'm also using API Platform.

What is the best way of achieving this in Symfony 4 and Doctrine 2?

I use vichUploaderBundle the error i get is Expected argument of type "string", "NULL" given at property path "imageName"

$
0
0

I have a product entity each product is related to a multiple images when i add a product with multiple images it work but if i remove a product i have a error

in the delete function i have this code :

public function delete(Request $req,Products $product){

     if($this->isCsrfTokenValid('delete'. $product->getId(),$req->get('_token'))){

            foreach ($product->getImages() as $image) {


               $product->removeImage($image);
               $this->em->remove($image);
                $this->em->persist($image);

            }
        $this->em->remove($product);
        $this->em->flush();


        $this->addFlash('success',"product deleted");

          }
         return $this->redirectToRoute("admin.index");

     }

in the edit I have

  public function edit(Products $product ,Request $req):Response{

    $originalImages = array();
    if($product){

    foreach ($product->getImages() as $image) {
        $originalImages[] = $image;
    }

    $editForm = $this->createForm(ProductsTypeForm::class,$product);

           $editForm->handleRequest($req);
         if($editForm->isSubmitted()&&$editForm->isValid()){
            foreach ($product->getImages() as $image) {
                foreach ($originalImages as $key => $toDel) {
                    if ($toDel->getId() === $image->getId()) {
                        unset($originalImages[$key]);
                    }
                }
            }

            // remove the relationship between the image and the Product
            foreach ($originalImages as $image) {

                $product->removeImage($image);
                $this->em->remove($image);
                $this->em->persist($image);

            }
            $this->em->persist($product);
            $this->em->flush();

             $this->addFlash('success',"changed");
             return $this->redirectToRoute('admin.index');
    }
}

    return $this->render('pages/admin/edit.html.twig',[
        'item'=>$product,
        'form'=>$editForm->createView()
    ]);
}

in the Images entity I have a bidirectional many-to-one relationship. the relationship is removed correctly but the image related to the product did not anyone can help me

symfony 4.0 failed to install assetic-bundle

$
0
0

I'm trying this new symfony 4.0, so I failed to install assetic-bundle, the command I use

composer require assetic-bundle

I got a set of problems :

Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.
Problem 1
- symfony/assetic-bundle v2.8.2 requires symfony/framework-bundle ~2.3|~3.0
-> satisfiable by symfony/framework-bundle[2.3.x-dev, 2.4.x-dev,/....../  v3.4.0-RC2]
but these conflict with your requirements or minimum-stability.

I got four problems like this (I just took the important part of the first because they are very long) my requirements in the json file:

"require": {
    "php": "^7.1.3",
    "sensio/framework-extra-bundle": "^5.1",
    "sensiolabs/security-checker": "^4.1",
    "symfony/asset": "^4.0",
    "symfony/console": "^4.0",
    "symfony/flex": "^1.0",
    "symfony/framework-bundle": "^4.0",
    "symfony/lts": "^4@dev",
    "symfony/profiler-pack": "^1.0",
    "symfony/twig-bundle": "^4.0",
    "symfony/web-server-bundle": "^4.0",
    "symfony/yaml": "^4.0"
},
"require-dev": {
    "symfony/dotenv": "^4.0"
},

hearing from you, thanks ^_^

Symfony 4 and webpack encore, looking for good practice when adding a CSS third library

$
0
0

I'm on a Symfony 4 new project.

Via yarn, I installed (by example) the CSS library animate.css

yarn install animate.css

From the webpack.config.js file, I added the animate.css file like that :

.addStyleEntry('animate', './node_modules/animate.css/animate.css')

My question is : is it a good way to add a CSS library like that ? I'm not sure if use directly the node_module path is a good practice..

Is there a better way ?

Viewing all 3925 articles
Browse latest View live


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