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

Symfony 4 - EasyAdmin Bundle - default form value

$
0
0

Hello everyone !

I'm using easyadmin for a project and i'm a bit confuse. I have a User entity with roles "ROLE_CUSTOMER" and "ROLE_REPAIRMAN". I can display and add users depend on their roles :

entities.yaml :

easy_admin:
  entities:
    Customer:
      label: 'Customer'
      class: App\Entity\User
      list:
        dql_filter: "entity.roles LIKE '%%ROLE_CUSTOMER%%'"
      form:
        title: "Add Customer"
        fields: &userFormFields
          - { property: 'email' }
          - { property: 'civility' }
          - { property: 'lastname' }
          - { property: 'firstname' }
          - { property: 'phone' }
          - { property: 'mobile' }
    Repairman:
      label: 'Repairman'
      class: App\Entity\User
      controller: App\Controller\Admin\RepairmanController
      list:
        dql_filter: "entity.roles LIKE '%%ROLE_REPAIRMAN%%'"
        fields:
          - id
          - company
          - email
          - civility
          - firstname
          - lastname
          - { property: 'isAdminGroup' }
      form:
        title: "Add Repairman"
        fields:
          - { property: 'email' }
          - { property: 'civility' }
          - { property: 'lastname' }
          - { property: 'firstname' }
          - { property: 'phone' }
          - { property: 'mobile' }
          - { property: 'company' }
          - { property: 'vitrage' }
          - { property: 'kbis' }
          - { property: 'siret' }
          - { property: 'isAdminGroup' }

menu.yaml

easy_admin:
  design:
    menu:
      - label: 'Clients'
        icon: 'users'
        entity: 'Customer'
        children:
          - { label: 'Show', entity: 'Customer', params: { action: 'list' } }
          - { label: 'Add', entity: 'Customer', params: { action: 'new' } }
      - label: 'Repairman'
        icon: 'users'
        entity: 'Repairman'
        children:
          - { label: 'Show', entity: 'Repairman', params: { action: 'list' } }
          - { label: 'Add', entity: 'Repairman', params: { action: 'new' } }

When I click on add a customer, I would like his role to be ROLE_CUSTOMER and when I click on add a repairman, his role to be ROLE_REPAIRMAN

I tried to extend the AdminController, the RepairmanController but I can't get what I want. I also tried to set a default value using :

- { property: 'roles', type: 'hidden', type_options: { empty_data: "['ROLE_REPAIRMAN']" } }

Here I have an error because he needs an array and he interprets the value as a string.

Can someone help me to figure it out please ? Or do you have a better solution ?

Thank you !


How do I suppress the warning "unable to find the application log" after running "symfony serve"?

$
0
0

With Symfony 4.3 and Symfony CLI v4.7.1, when I run:

symfony serve

I see the following warning in the output:

WARNING unable to find the application log

How do I solve the issue that raises this warning? Do I have to install the logger bundle?

Can't Logout user in Symfony4

$
0
0

I'm updating a project built with Symfony2.7 to Symfony4, everything is working fine and have good compatibility, but one thing that should be fine, a built-in resource, the security layer, doesn't work as expected.

The problem I'm facing is that I can't logout users anymore. I followed the steps on the guide but nothing changed.

Below is the security config:

#config/packages/security.yaml
security:
    encoders:
        App\Entity\Clients:
            algorithm: bcrypt

    providers:
        app_user_provider:
            entity:
                class: App\Entity\Clients
    firewalls:    
        app:
            pattern: ^/
            anonymous: ~
            provider: app_user_provider
            remember_me:
                secret: "%kernel.secret%"
            form_login:
                use_referer: true
                login_path: login
                check_path: login_check
                always_use_default_target_path: false
                default_target_path: dashboard
                csrf_token_generator: security.csrf.token_manager
            logout:
                path: logout
                target: home
                invalidate_session: false

The paths I'm using are route names, but also tried the path itself.

I can normally login any user, but when I hit the logout route, I'm just redirected to home route, but the user is still authenticated.

Tried to set a custom handler logout like:

logout:
    handlers: [logout_handler]

It references to a service implementing Symfony\Component\Security\Http\Logout\LogoutHandlerInterface, but it didn't even call the handler.

It would be great if I could only use the default handler, and it's necessary to maintain the "remember_me" behavior, which was also working fine in 2.7.

Could anyone help me with that?

EDIT: My config routes.yaml is empty, 'cause I'm using annotation routes, the config/packages/routing.yaml is as follows:

framework:
    router:
        strict_requirements: ~

Just like when initialized with the composer create-project command. And for the annotations config I have the file config/routes/annotations.yaml:

controllers:
    resource: ../../src/Controller/
    type: annotation

Again, it's the config the recipe created by itself.

Cannot logout with Symfony 4

$
0
0

I cannot logout a user.

I ported custom user management logic over to a Symfony 4 project. It uses recipes for security and guard.

Here is the logout config in my main firewall:

    logout:
        path: /logout
        target: /

Result: - User goes to /logout - User is redirected to / - is_granted("IS_AUTHENTICATED_REMEMBERED") continues to return true in my template (false is expected)

Other Considerations: - The firewall entry is getting triggered because I get errors if I remove it - I have tried adding additional parameters to logout to destroy the session and cookies, however that made no difference - Logging in works fine

Any idea on how to troubleshoot this?

:: edit - added security.yaml as requested ::

security:
    encoders:
        App\Entity\User: bcrypt
    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: ROLE_ADMIN
    providers:
        app_users:
            entity: { class: App\Entity\User, property: email }
        app_oauth:
            id: app.oauth_user_provider
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            provider: app_users
            anonymous: ~
            oauth:
                resource_owners:
                    google: "/login/check-google"
                default_target_path: /
                login_path: /
                failure_path: /login
                oauth_user_provider:
                    service: app.oauth_user_provider
            remember_me:
                secret: "%env(APP_SECRET)%"
                lifetime: 2592000
                path:  /
            guard:
                authenticators:
                    - App\Security\LoginFormAuthenticator
                entry_point: App\Security\LoginFormAuthenticator
            logout:
                path: /logout
                target: /
            switch_user: ~

Symfony 4 - How to display data and form in the same page?

$
0
0

I want to display the form and the data which is from BIN database file. I want to let the user enter the IP address, so they will get the information. However, it only shows the form, can't show the result out.

Here is the code in Controller.php:

class DefaultController extends AbstractController
{
    /**
     * 
     * @Route("/default", name="default")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function index(Request $request)
    {
        $db = new \IP2Location\Database('./Database/IP2LOCATION.BIN', \IP2Location\Database::FILE_IO);

        $form = $this->createFormBuilder()
        ->add('ip', TextType::class, [
            'attr' => [
                'class' => 'form-control'
            ]
        ])
        ->add('submit', SubmitType::class, [
            'attr' => [
                'class' => 'btn btn-primary'
            ]
        ])
        ->getForm();

        $form->handleRequest($request);

        if($form->isSubmitted() && $form->isValid()){

            $db = $form->getData();
            $records = $request->request->get('ip');
            $records = $db->lookup('ip', \IP2Location\Database::ALL);
        }

        return $this->render('default/form.html.twig',[
            'form' => $form->createView(),
            'records' => $db
        ]);
    }

Here is the code in form.html.twig

{% extends 'base.html.twig' %}

{% block body %}
<h3>IP2Location Symfony Demo</h3>
<form action="" method="POST">
    <table>
         <tr>
             <td>IP Address: </td>
             <td>{{form_widget(form.ip)}}</td>
             <td><input type="submit" value="Submit" name="submit"/></td>
        </tr>
    </table>
</form>
{% if form.submit is defined %}
{% for records in records %}

<table class="table table-bordered table-striped">
        <tbody>
            <tr>
                <td>IP Number: </td>
                <td>{{ records.ipNumber }}</td>
            </tr>
            <tr>
                <td>IP Version: </td>
                <td>{{ records.ipVersion }}</td>
            </tr>
            <tr>
                <td>IP Address: </td>
                <td>{{ records.ipAddress }}</td>
            </tr>
        </tbody>
    </table>

{% endfor %}
{% endif %}
{% endblock %}

Does anyone have any advise on how to go about this?

Symfony 4 : get the error message from count constraint applied on collection type

$
0
0

I am using a collection type of symfony 4, and i wish to apply a count constraint to this collection.

I have followed this tutorial : https://symfony.com/doc/current/form/form_collections.html

My idea is to apply the constraint directly on the collection :

$builder
    ->add('tags', CollectionType::class, [
        'entry_type' => Tag::class,
        'entry_options' => ['label' => false],
        'allow_add' => true,
        'by_reference' => false,
        'constraints' => [
            new Assert\Count(['min' => 1, 'max' => 3])
        ]
    ])
;

But this does not work : I do not get any error message...

I have also try to use this constraint directly in the entity Task, without success.

So how can I get the error message from count constraint applied on collection type ?

Correct way to denormalize an object (Doctrine Entity) with relations

$
0
0

I need to denormalize an object (Doctrine Entity) from an array (it comes from POST JSON and decoded into an associated PHP array). The main goal is to save the object and all its relations (which have some relations too).

Base object

class Product
{
    private $id;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\ProductAttribute", mappedBy="product", cascade={"persist"})
     */
    private $attributes;
}

Relation object

class ProductAttribute
{
    private $id;
    private $name;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Product", inversedBy="attributes")
     * @ORM\JoinColumn(nullable=false)
     */
    private $product;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\ProductAttributeType", inversedBy="productAttributes")
     * @ORM\JoinColumn(nullable=false)
     */
    private $type;
}

Another one relation object

class ProductAttributeType
{
    private $id;
    private $name;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\ProductAttribute", mappedBy="type")
     */
    private $productAttributes;
}

Arrays looks like this

[
  'id' => 1,
  'attributes' => [
    [
      'id' => 2,
      'name' => 'Name of attribute with ID 2',
      'type' => 2,
    ],
    [
      'id' => 3,
      'name' => 'Changed name of attribute with ID 3',
      'type' => 3
    ]
  ],
]

The main goal is to denormalize an array (at any time ProductAttribute's name can be changed and should be saved, so we need to send name each time) . I've tried two approaches with custom denormalizer (extends from default Symfony Serializer) created:

  • leveraged all the work of filling Doctrine entities to denormalize(), injecting EntityManager directly into denormalizer and use it to find entities

  • not injecting EntityManager and preparing all the models in controller, before calling denormalization and sending them through $context

In any way this ends to a call in denormalizer

$product->setAttributes($attributes)

where $attributes is an array of ProductAttribute objects (as Doctrine Entities).

Which of them is right? Or both of them is wrong?

Symfony 4 change default form name

$
0
0

I create 2 forms not linked to any entity in the same controller. Each form have it owns submitted button. I never goes to the submitted function of the second form. I think it is because the 2 forms have same default name 'form'. The problem is how to change the form name? Below what I did

public function index(Request $request)
{
    $form1 = $this->createFormBuilder()
        ->add('sn', TextType::class, [
            'required' => false,
            ])
        ->add('search', SubmitType::class, ['label' => 'Search'])
        ->getform();
    $form1->handleRequest($request);
    if ($form1->isSubmitted() && $form1->isValid()) {
       //Do something

    }

    $form2 = $this->createFormBuilder();
    $form2->add('Agree', CheckboxType::class, [
                    'label'    => 'Agree',
                    'required' => false,
                ]);
    $form2->add('detail', SubmitType::class, ['label' => 'Detail']);
    $form2 = $form2->getForm();
    $form2->handleRequest($request);
    if ($form2->isSubmitted() && $form2->isValid()) {
        //Do something else
    }

    return $this->render('search/index.html.twig', [
        'form1' => $form1->createView(),
        'form2' => $form2->createView(),
    ]);
}

Symfony join with first match dql

$
0
0

i'm working with Symfony framework (2) that I have two tables in my database

First Table : Caisse

id 1 2 3

Second Table: Caisse_Zone

caisse_id 1 1 2 3 4

I want to join the two table but i need to join only first match on the second table

$queryS = $em->createQueryBuilder();
 $queryS->select-('ca.id')->from('Xx:Caisse', 'ca')

$queryS->join('ca.caisse_id', 'cc')

Symfony 4 - .env Variables Not Available

$
0
0

I'm running in to a brick wall here. Everything so far with Symfony 4 has been sunshine and daisies but now I can't seem to add any environment variables to my project.

In my project root there is the default .env file populated with the usual APP_ENV, APP_SECRET and DATABASE_URL; that's all great. However, adding any custom variable there doesn't seem to actually do anything! If I add in ANOTHER_VAR=hello_world, for example, and then run bin/console debug:container --env-vars, it only dumps the APP_SECRET and DATABASE_URL variables. If I run bin/console about, however, it shows me all of the variables inside .env.

I thought it might be a cached variable issue but if I change the value of APP_SECRET and run the console command again, it dumps the changed value but still not my custom variables.

I suspect that the env vars are not available to the container by default but that doesn't seem right to me (plus it seems somewhat contradictory to what the Symfony docs themselves say).

What do I need to do to register these variables so I can access them inside a Controller, for example?

Can Symfony 4 be configured to ignore code installed in subdirectories?

$
0
0

I'm currently converting an old website to use Symfony 4 and the site uses the LiveZilla live chat app.

LiveZilla lives in a subfolder of the site, and is accessed directly using URLs under somesite.com/livezilla. I can't currently access it of course, because I haven't configured a route for this folder. So Symfony decides that this will be a 404.

LiveZilla is essentially a completely separate app living in its own folder here. It isn't dependent on the website hosting it. Is there a way to tell Symfony to ignore certain paths so that code like this can be executed without interference?

I have a sneaking feeling that I need to adjust the way I am looking at this as I can't find anything obvious in the Symfony docs about this, and the framework is pretty well thought out. The best I have come up with so far is hacking public/.htaccess, but it feels wrong somehow...

My profiler 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?

EDIT 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>

Interface Matcher\RequestMatcherInterface' not found

$
0
0

I am trying to deploy my Symfony app to Webhosting and getting this error

 Fatal error: Interface 'Symfony\Component\Routing\Matcher\RequestMatcherInterface' not found in /data/web/virtuals/201283/virtual/www/subdom/dev/vendor/symfony/routing/Matcher/UrlMatcher.php on line 29

My Webhosting haven't got SSH access, so I copied all folders except var and test. And then .env and composer.json to /subdom/dev (this subdom working with normal HTML index)

Using php 7.3. Composer.json

{
"type": "project",
"license": "proprietary",
"require": {
    "php": "^7.1.3",
    "ext-ctype": "*",
    "ext-iconv": "*",
    "gedmo/doctrine-extensions": "^2.4",
    "knplabs/knp-time-bundle": "^1.9",
    "sensio/framework-extra-bundle": "^5.1",
    "stof/doctrine-extensions-bundle": "^1.3",
    "symfony/apache-pack": "^1.0",
    "symfony/asset": "4.3.*",
    "symfony/console": "4.3.*",
    "symfony/dotenv": "4.3.*",
    "symfony/expression-language": "4.3.*",
    "symfony/flex": "^1.3.1",
    "symfony/form": "4.3.*",
    "symfony/framework-bundle": "4.3.*",
    "symfony/http-client": "4.3.*",
    "symfony/intl": "4.3.*",
    "symfony/monolog-bundle": "^3.1",
    "symfony/orm-pack": "*",
    "symfony/process": "4.3.*",
    "symfony/security-bundle": "4.3.*",
    "symfony/serializer-pack": "*",
    "symfony/swiftmailer-bundle": "^3.1",
    "symfony/translation": "4.3.*",
    "symfony/twig-bundle": "4.3.*",
    "symfony/validator": "4.3.*",
    "symfony/web-link": "4.3.*",
    "symfony/yaml": "4.3.*",
    "vich/uploader-bundle": "^1.10"
},
"require-dev": {
    "symfony/debug-pack": "*",
    "symfony/maker-bundle": "^1.0",
    "symfony/profiler-pack": "*",
    "symfony/test-pack": "*",
    "symfony/web-server-bundle": "4.3.*"
},
"config": {
    "preferred-install": {
        "*": "dist"
    },
    "sort-packages": true
},
"autoload": {
    "psr-4": {
        "App\\": "src/"
    }
},
"autoload-dev": {
    "psr-4": {
        "App\\Tests\\": "tests/"
    }
},
"replace": {
    "paragonie/random_compat": "2.*",
    "symfony/polyfill-ctype": "*",
    "symfony/polyfill-iconv": "*",
    "symfony/polyfill-php71": "*",
    "symfony/polyfill-php70": "*",
    "symfony/polyfill-php56": "*"
},
"scripts": {
    "auto-scripts": {
        "cache:clear": "symfony-cmd",
        "assets:install %PUBLIC_DIR%": "symfony-cmd"
    },
    "post-install-cmd": [
        "@auto-scripts"
    ],
    "post-update-cmd": [
        "@auto-scripts"
    ]
},
"conflict": {
    "symfony/symfony": "*"
},
"extra": {
    "symfony": {
        "allow-contrib": false,
        "require": "4.3.*"
    }
}

}

I don't know what to do. Please help me. With regards P.

Custom UserChecker in HWIOauthBundle

$
0
0

I have a problem with FOSUserBundle and HWIOauthBundle. I use custom UserChecker to check whether user is banned (custom table in database as I need a ban history). When I use Facebook to log-in my CustomChecker is not used. It does work when I'm using login and password as authentication.

Issue on GitHub: https://github.com/hwi/HWIOAuthBundle/issues/1358

Anyone has an idea how to fix that?

Dependency Injections seems to create new doctrine instance, which causes an entity to be detached)

$
0
0

I've got two services, those get Doctrine injected via the constructor. When loading an entity in an EventListener and giving it ot service the entity is detached.

When im providing the DoctrineEntityManager from an EventListener to service, the entity is still managed.

class Listener implements EventSubscriberInterface
{
    /** @var EntityManagerInterface */
    private $em;

    /** @var Service */
    private $service;

    /** @var EventDispatcherInterface */
    private $eventDispatcher;

    public function __construct(
        EntityManagerInterface $em,
        Service $service,
        EventDispatcherInterface $eventDispatcher
    ) {
        $this->em = $em;

        $this->eventDispatcher = $eventDispatcher;
        $this->service = $service;
    }


    public function listenerFunction(Event $event)
    {
        $user = $event->getEntity()->getUser();
        var_dump($this->em->contains($user)); // true

        $this->service->func($this->em, $user);
    }
}

class Service
{
    /** @var EventDispatcherInterface */
    private $eventDispatcher;

    public function __construct(EntityManagerInterface $em, EventDispatcherInterface $eventDispatcher)
    {
        $this->em = $em;
        $this->eventDispatcher = $eventDispatcher;
    }

    public function func($em, $user)
    {
        var_dump($this->em->contains($user)); // false 
        var_dump($em->contains($user)); // true
    }
}

the services yaml

services:
  _defaults:
    autowire: true
    autoconfigure: true
    public: true

  App\Payment\Command\:
    resource: "%kernel.project_dir%/src/Payment/Command/*"
    tags:
      - { name: console.command }

  App\Payment\Service\:
    resource: "%kernel.project_dir%/src/Payment/Service/*"

  App\Payment\Controller\:
    resource: "%kernel.project_dir%/src/Payment/Controller/*"

  App\Payment\EventSubscriber\:
    resource: "%kernel.project_dir%/src/Payment/EventSubscriber/*"
    tags:
      - { name: kernel.event_subscriber }

The EntityManager in the service should contain the $user entity. Im thinking symfony is creating a second instance of the entitymanagerinterface here, but the says there is only one instance of each item (https://symfony.com/doc/current/service_container/shared.html)


Problem redirect after login when using FOSUser Symfony4

$
0
0

http://blog.test/register and http://blog.test/login works well, so when I access from http://blog.test/admin I am redirected to http://blog.test/login and and when I log in i have this error : Access Denied. enter image description here And when I click on Logs I have:

enter image description here My config is :

<?php

// src/Entity/User.php

namespace App\Entity;

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;

public function __construct()
{
    parent::__construct();
    // your own logic
}

}

config\packages\framework.yaml

framework:    
    templating:
        engines: ['twig', 'php']

config\packages\security.yaml

security:
encoders:
    FOS\UserBundle\Model\UserInterface: bcrypt

role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
    ROLE_SUPER_ADMIN: ROLE_ADMIN
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
    in_memory: { memory: null }
    fos_userbundle:
        id: fos_user.user_provider.username_email
firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    main:
        pattern: ^/
        user_checker: security.user_checker
        form_login:
            provider: fos_userbundle
            csrf_token_generator: security.csrf.token_manager

        logout: true
        anonymous: true

        # activate different ways to authenticate
        # https://symfony.com/doc/current/security.html#firewalls-authentication

        # https://symfony.com/doc/current/security/impersonating_user.html
        # switch_user: true

# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
- { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin, role: ROLE_ADMIN }

config\routes\fos_user.yaml

fos_user:
    resource: "@FOSUserBundle/Resources/config/routing/all.xml"

I searched everywhere and I had no solution, I even tried to remove the templating: engines: ['twig', 'php']

I have this error : enter image description here

I removed the twig and I put only PHP like that : engines: ['php'] [enter image description here]4

I can't found any solution. How can I resolve this problem. Thanks a lot

Command in third-party (vendor) Symfony Bundle is not detected. What is wrong?

$
0
0

as instructed in https://github.com/glennthehuman/encryption-bundle/blob/master/Resources/doc/index.md

I executed: php bin/console jagilpe:encryption:user:generate_keys But I got:

There are no commands defined in the "jagilpe:encryption:user" namespace.

So, I checked this folder structure With the code:

<?php

namespace Jagilpe\EncryptionBundle\Command;

use Doctrine\Common\Util\ClassUtils;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Jagilpe\EncryptionBundle\Entity\PKEncryptionEnabledUserInterface;
use Symfony\Component\Console\Helper\ProgressBar;

class CreateUserKeysCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this->setName('jagilpe:encryption:user:generate_keys')
            ->setDescription('Generates the encryption keys of a user')
            ->addArgument(
                'usename',
                InputArgument::OPTIONAL,
                'The name of the user whose keys we want to create.'
            )
            ->addOption(
                'all',
                null,
                InputOption::VALUE_NONE,
                'If the keys of all users should be generated.'
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Input parameters
        $userName = $input->getArgument('usename');
        $allUsers = $input->getOption('all');

        if (!$userName && !$allUsers) {
            throw new \RuntimeException('Wrong parameters given');
        }

        if ($userName && $allUsers) {
            throw new \RuntimeException('Ambiguous parameters given');
        }

        $users = $this->getUsers($userName);

        $total = count($users);
        $message = "Generating the encryption keys for $total users";
        $output->writeln($message);
        $progress = new ProgressBar($output, $total);
        foreach ($users as $user) {
            $this->generateKeys($user);
            $this->saveUser($user);
            $progress->advance();
        }
        $progress->finish();
        $output->writeln('');
    }

    private function getUsers($userName)
    {
        $container = $this->getContainer();
        $entityManager = $container->get('doctrine')->getManager();
        $encryptionSettings = $container->getParameter('jagilpe_encryption.settings');
        $userClasses = $encryptionSettings['user_classes'];

        $users = array();
        foreach ($userClasses as $userClass) {
            $userRepo = $entityManager->getRepository($userClass);

            if ($userName) {
                $user = $userRepo->findOneBy(array('username' => $userName));
                $users = array($user);
                break;
            }
            else {
                $users = array_merge($users, $userRepo->findAll());
            }
        }

        return $users;
    }

    private function generateKeys(PKEncryptionEnabledUserInterface $user)
    {
        if (!$user->getPublicKey() || !$user->getPrivateKey()) {
            $container = $this->getContainer();
            $keyManager = $container->get('jagilpe_encryption.key_manager');
            $keyManager->generateUserPKIKeys($user);
        }
    }

    private function saveUser(PKEncryptionEnabledUserInterface $user)
    {
        $userClass = ClassUtils::getClass($user);
        $userRepo = $this->getContainer()->get('doctrine')->getManager()->getRepository($userClass);
        $userRepo->save($user);
    }
}

What's wrong with this?

By the way, I was able to install the bundle without any problem. The source codes can be correctly accessed and used in my own codes. I just cannot run the aforementioned command properly. I also created my own command in my own Command directory and they were properly detected and executed.

Trying to deploy our S4 program, we have a fatal error with debug

$
0
0

We wrote an application with SF4. It works fine, even on the remote site, in dev mode.

So we try to get prod mode. In .env, we pass the APP_ENV variable to prod, an we have the message :

Fatal error: Uncaught Symfony\Component\DependencyInjection\Exception\InvalidArgumentException: There is no extension able to load the configuration for "debug" (in /home/olymphys/public_html/config/packages/debug.yml). Looked for namespace "debug", found "framework", "sensio_framework_extra", "doctrine_cache", "doctrine", "doctrine_migrations", "security", "swiftmailer", "twig", "monolog", "easy_admin", "vich_uploader", "webpack_encore" in /home/olymphys/public_html/vendor/symfony/dependency-injection/Loader/YamlFileLoader.php:682 Stack trace: #0 /home/olymphys/public_html/vendor/symfony/dependency-injection/Loader/YamlFileLoader.php(652): Symfony\Component\DependencyInjection\Loader\YamlFileLoader->validate(Array, '/home/olymphys/...') #1 /home/olymphys/public_html/vendor/symfony/dependency-injection/Loader/YamlFileLoader.php(119): Symfony\Component\DependencyInjection\Loader\YamlFileLoader->loadFile('/home/olymphys/...') #2 /home/olymphys/public_html/vendor/symfony/config/Loader/FileLoader.php(151): Symfony\Component\D in /home/olymphys/public_html/vendor/symfony/config/Loader/FileLoader.php on line 166

We tried to use dump_destination in symfony/debug-bundle config and nothing different happen...

Many to many suppliers/articles

$
0
0

I develop under symfony 4 and I block on a relationship ManyToMany, I wish I could have a reference for each articles knowing that one all suppliers can have the same article in common but with a different reference. Here are my 2 entities:

Article:

<?php

namespace App\Entity;

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

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

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

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

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

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

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

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

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

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

    /**
     * @ORM\ManyToMany(targetEntity="Fournisseur", inversedBy="Articles")
     * @ORM\JoinTable(name="articles_fournisseurs")
     */
    private $fournisseurs;

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

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

    /**
     * @return mixed
     */
    public function getIdTactill()
    {
        return $this->id_tactill;
    }

    /**
     * @param mixed $id_tactill
     */
    public function setIdTactill($id_tactill): void
    {
        $this->id_tactill = $id_tactill;
    }

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

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

        return $this;
    }

    public function getPrice(): ?float
    {
        return $this->price;
    }

    public function setPrice(float $price): self
    {
        $this->price = $price;

        return $this;
    }

    public function getReference(): ?string
    {
        return $this->reference;
    }

    public function setReference(string $reference): self
    {
        $this->reference = $reference;

        return $this;
    }

    public function getInStock(): ?bool
    {
        return $this->in_stock;
    }

    public function setInStock(bool $in_stock): self
    {
        $this->in_stock = $in_stock;

        return $this;
    }

    public function getImage(): ?string
    {
        return $this->image;
    }

    public function setImage(string $image): self
    {
        $this->image = $image;

        return $this;
    }

    public function getReferenceSupplier(): ?string
    {
        return $this->reference_supplier;
    }

    public function setReferenceSupplier(string $reference_supplier): self
    {
        $this->reference_supplier = $reference_supplier;

        return $this;
    }

    public function getTaxes()
    {
        return $this->taxes;
    }

    public function setTaxes($taxes): void
    {
        $this->taxes = $taxes;
    }
}

Supplier:

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Doctrine\ORM\Mapping as ORM;

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

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

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

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

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

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

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

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

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

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

    /**
     * @ORM\Column(type="integer", length=5)
     *
     * @var integer
     */
    private $zipcode;

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

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

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

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

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

    /**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     *
     * @Vich\UploadableField(mapping="fournisseur_image", fileNameProperty="imageName", size="imageSize")
     *
     * @var File
     */
    private $imageFile;

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

    /**
     * @ORM\Column(type="integer")
     *
     * @var integer
     */
    private $imageSize;

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

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

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

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

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

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

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

    /**
     * @ORM\ManyToMany(targetEntity="Article", mappedBy="fournisseurs")
     */
    private $articles;

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

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

    /**
     * @return string
     */
    public function getCategory(): ?string
    {
        return $this->category;
    }

    /**
     * @param string $category
     */
    public function setCategory(string $category): void
    {
        $this->category = $category;
    }

    /**
     * @return string
     */
    public function getCivility(): ?string
    {
        return $this->civility;
    }

    /**
     * @param string $civility
     */
    public function setCivility(string $civility): void
    {
        $this->civility = $civility;
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param mixed $name
     */
    public function setName($name): void
    {
        $this->name = $name;
    }

    /**
     * @return string
     */
    public function getCompany(): ?string
    {
        return $this->company;
    }

    /**
     * @param string $company
     */
    public function setCompany(string $company): void
    {
        $this->company = $company;
    }

    /**
     * @return string
     */
    public function getNamed(): ?string
    {
        return $this->named;
    }

    /**
     * @param string $named
     */
    public function setNamed(string $named): void
    {
        $this->named = $named;
    }

    /**
     * @return string
     */
    public function getSurname(): ?string
    {
        return $this->surname;
    }

    /**
     * @param string $surname
     */
    public function setSurname(string $surname): void
    {
        $this->surname = $surname;
    }

    /**
     * @return string
     */
    public function getBuilding(): ?string
    {
        return $this->building;
    }

    /**
     * @param string $building
     */
    public function setBuilding(string $building): void
    {
        $this->building = $building;
    }

    /**
     * @return string
     */
    public function getStreet(): ?string
    {
        return $this->street;
    }

    /**
     * @param string $street
     */
    public function setStreet(string $street): void
    {
        $this->street = $street;
    }

    /**
     * @return string
     */
    public function getOther(): ?string
    {
        return $this->other;
    }

    /**
     * @param string $other
     */
    public function setOther(string $other): void
    {
        $this->other = $other;
    }

    /**
     * @return int
     */
    public function getZipcode(): ?int
    {
        return $this->zipcode;
    }

    /**
     * @param int $zipcode
     */
    public function setZipcode(int $zipcode): void
    {
        $this->zipcode = $zipcode;
    }

    /**
     * @return string
     */
    public function getCity(): ?string
    {
        return $this->city;
    }

    /**
     * @param string $city
     */
    public function setCity(string $city): void
    {
        $this->city = $city;
    }

    /**
     * @return string
     */
    public function getCountry(): ?string
    {
        return $this->country;
    }

    /**
     * @param string $country
     */
    public function setCountry(string $country): void
    {
        $this->country = $country;
    }

    /**
     * @return string
     */
    public function getUrl(): ?string
    {
        return $this->url;
    }

    /**
     * @param string $url
     */
    public function setUrl(string $url): void
    {
        $this->url = $url;
    }

    /**
     * @return string
     */
    public function getLogin(): ?string
    {
        return $this->login;
    }

    /**
     * @param string $login
     */
    public function setLogin(string $login): void
    {
        $this->login = $login;
    }

    /**
     * @return string
     */
    public function getPasswordSite(): ?string
    {
        return $this->passwordSite;
    }

    /**
     * @param string $passwordSite
     */
    public function setPasswordSite(string $passwordSite): void
    {
        $this->passwordSite = $passwordSite;
    }

    /**
     * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $imageFile
     */
    public function setImageFile(?File $imageFile = null): void
    {
        $this->imageFile = $imageFile;
    }

    public function getImageFile(): ?File
    {
        return $this->imageFile;
    }

    public function setImageName(?string $imageName): void
    {
        $this->imageName = $imageName;
    }

    public function getImageName(): ?string
    {
        return $this->imageName;
    }

    public function setImageSize(?int $imageSize): void
    {
        $this->imageSize = $imageSize;
    }

    public function getImageSize(): ?int
    {
        return $this->imageSize;
    }

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): self
    {
        $this->title = $title;

        return $this;
    }

    public function getType(): ?string
    {
        return $this->type;
    }

    public function setType(string $type): self
    {
        $this->type = $type;

        return $this;
    }

    public function getPhone1(): ?string
    {
        return $this->phone1;
    }

    public function setPhone1(string $phone1): self
    {
        $this->phone1 = $phone1;

        return $this;
    }

    public function getPhone2(): ?string
    {
        return $this->phone2;
    }

    public function setPhone2(string $phone2): self
    {
        $this->phone2 = $phone2;

        return $this;
    }

    public function getFax(): ?string
    {
        return $this->fax;
    }

    public function setFax(string $fax): self
    {
        $this->fax = $fax;

        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    public function getNote(): ?string
    {
        return $this->note;
    }

    public function setNote(string $note): self
    {
        $this->note = $note;

        return $this;
    }
}

I need to associate a different product reference depending on the supplier.

Thank you for help.

Symfony + Forms, by_reference = true and allow_add in CollectionType fields

$
0
0

I'm relatively new to Symfony, so I might grossly misunderstand something. I'm confused about when I'd want to set by_reference = true on a CollectionType form field with allow_add = true.

For context: I got myself into this mess when I was trying to use a doctrine event listener to listen to preRemove on an entity that is removed by removing it from a CollectionType form field with allow_delete => true in order to trigger an update on the parent entity. With by_reference => false on the form class, I cannot access the parent entity inside the preRemove handler but the parent's removeEntity() method gets called. With by_reference => true, I can access the parent from the to-be-deleted entity, but its removeEntity() method does not get called. That makes sense to me, my trouble is with adding child entities with a form.

Simplified, I have two entities:

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

    /**
    * @ORM\OneToMany(targetEntity="App\Entity\ChildEntity", mappedBy="parent", orphanRemoval=true, cascade={"persist", "remove"})
    */
    private $childEntities;

    public function addChildEntity(ChildEntity $childEntity): self
    {
        if (!$this->childEntities->contains($childEntity)) {
            $this->childEntities[] = $childEntity;
            $childEntity->setParent($this);
        }

        return $this;
    }

    // other getter, adder, remover methods as autogenerated, left out for brevity
}

And

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

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

    /**
    * @ORM\ManyToOne(targetEntity="App\Entity\SimpleParent", inversedBy="childEntities")
    * @ORM\JoinColumn(nullable=false)
    */
    private $parent;

    // getter, adder, remover methods as autogenerated, left out for brevity
}

With two very simple form classes:

class SimpleParentType extends AbstractType
{

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

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('childEntities', NiceRepeaterType::class, [
            "entry_type" => ChildEntityType::class,
            "allow_delete" => true,
            "by_reference" => true,
            "allow_add" => true,
        ]);
    }
}

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

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        $builder->add("name", TextType::class, ["required" => false]);

    }
}

and a very simple code in the controller (for simplicity's sake, I'm just flushing the entityManager here)

$form = $this->createForm(SimpleParentType::class, $simpleParent);
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
    $simpleParent = $form->getData();
    $this->entityManager->flush();
}

Classes are used correctly, just left out for brevity. Using the prototype, I add a new row. However, submitting the form throws an exception:

An exception occurred while executing 'INSERT INTO child_entity (name, parent_id) VALUES (?, ?)' with params ["aaa", null]: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'parent_id' cannot be null

If I make the join column on the ChildEntity nullable, the ChildEntity gets inserted but has no connection to the SimpleParent because parent_id is set to null. Needless to say that these inserted ChildEntity rows don't show up in the form in the Collection. This makes sense because the parent's adder never gets called and so it never does setParent($this) on the new ChildEntity.

With by_reference => false, it works flawlessly as expected, the ChildEntity is created and is passed to SimpleParent::addChildEntity which sets the ChildEntity's parent. When the entity manager is flushed, the ChildEntity row is inserted with the parent_id set to the id of SimpleParent.

My question is: why would I ever have by_reference => true on a CollectionType if I also want allow_add => true? I've noticed that the object I get from $form->getData() in the controller contains the Collection including the ChildEntity that is currently without a parent. I could do that manually with

$simpleParent = $form->getData();
foreach($simpleParent->getChildEntities() as $child) {
    $child->setParent($simpleParent);
}

But what reason is there for this approach? I feel like I'm missing something obvious. Any advice is appreciated.

Viewing all 3916 articles
Browse latest View live


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