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

Circular referencing in Symfony forms

$
0
0

I am currently building a Symfony 4.4 API that is capable of adding objects to a database. Since I believe that my problem can be explained and resolved using only theory I won't add my actual code here but I'll provide a more conceptual description.

I have an entity class named Person. This class has a corresponding form, called PersonType. A person could have a user and an employee linked to it. These also have their entities and forms.

A user has a field called createdBy which links to another user and an employee must have a person linked to it.

My problem is that when I try to patch a person using the usual way (createForm() and Doctrine, like here), I get a memory overflow at createForm(). When I remove the references to UserType and EmployeeType from PersonType, there is no memory overflow. My memory size is 1GB, and I believe making it larger will not resolve the issue.

Is there is a way to limit the number of circular references, or to prevent the rendering of the person of the employee of the person, for example.


Symfony 4 - Error 500 thrown instead of 403

$
0
0

I'm running Symfony 4/5, and for all my controllers in order to be able to execute the method I have an EventSubscriber that checks for the right permissions.

If the user is not granted, then it throws an AccessDeniedHttpException.This works fine as the method is binded to a route.But when rendering inside a twig template manually a controller action as :

{{ render( controller('App\\ExampleBundle\\Controller\\ChartsController::renderChart' ) }}

I got a 500 error instead of a 403.

I've debugged the app and checked that the exception as actually thrown, but the browser shows a 500 exception.

Is this a bug, or do I have to handle in another way the exception when it is for manually rendered methods from a twig template ?

Symfony 4, how redirect the user after login (or logout) to the previous page?

$
0
0

By example, the user go to the "about me" page. From this page, he can login or logout via a button in the navbar.

When the user login or logout, he is automatically redirected to the home page. Instead, I want redirect the user to the previous page (the "about me" in this example)

After read the doc I don't find/understand how I can condifure the redirection for my purposes

Someone can explain/show me :? 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?

Implement a custom error controller in Symfony 4.4

$
0
0

What i have done:

I have created this custom controller cause I want to pass to the error pages some extra variables.

#Controller/CustomErrorControler.phpnamespace App\Controller;use App\Controller\Base\BaseController;use Symfony\Component\ErrorHandler\Exception\FlattenException;use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;class CustomErrorController extends BaseController{    public function show(FlattenException $exception, DebugLoggerInterface $logger = null)    {        return $this->getView('bundles/TwigBundle/Exception/error.html.twig', ["code" => $exception->getStatusCode(),"message" =>$exception->getStatusText()        ]);    }}

and the enabled

#config/packages/framework.yamlerror_controller: App\Controller\CustomErrorController::show

I have followed the documentation directly. My problem is that I need, for non-production stages to get the default exception templates provided by the framework.

I have tried to extend Symfony\Component\HttpKernel\Controller\ErrorController but I'm getting errors for autowiring.

Maybe I should use Symfony\Component\ErrorHandler\ErrorRenderer\ErrorRendererInterfaceAny ideas how to implement this?

How to make /login route accessible only for anonymous users in Symfony4?

$
0
0

My access_controll looks like:

- { path: ^/login, role: IS_AUTHENTICATED_ANONYMOUSLY}- { path: ^/, roles: ROLE_USER}

I need to give an access to route /login only to anonymously authenticated users.

Temporarly disabling a doctrine entity listener

$
0
0

I use doctrine entity listeners to send mail whenever an entity is created. I want to be able to disable this event listener when performing certain operations (fixtures are mailbombing me as soon as I try to populate my database with fake entities).

I tried to disable the listener by using the clear method of the EntityListenerResolver class without success.

Here is my listener configuration:

services:    mail_on_create_document_listener:        class: App\EventListener\MailOnCreateDocumentListener        tags:            -                name: 'doctrine.orm.entity_listener'                event: 'postPersist'                entity: 'App\Entity\Document'

I try to disable the listener with this code:

<?phpnamespace App\DataFixtures;use Doctrine\Bundle\FixturesBundle\Fixture;use Doctrine\Common\Persistence\ObjectManager;class DebugFixture extends Fixture implements FixtureGroupInterface{    public function load(ObjectManager $manager)    {        $manager->getConfiguration()->getEntityListenerResolver()->clear(MailOnCreateDocumentListener::class);        dump($manager->getConfiguration()->getEntityListenerResolver());    }}

Here is the resulting dump of the EntityListenerResolver

^ Doctrine\Bundle\DoctrineBundle\Mapping\ContainerEntityListenerResolver^ {#1233  -container: Symfony\Component\DependencyInjection\Argument\ServiceLocator^ {#5278    -factory: Symfony\Component\DependencyInjection\Container::getService($registry, string $id, ?string $method, $load)^ {#283      this: ContainerHYiq7Ex\srcApp_KernelDevDebugContainer {#4404 …}    }    -serviceMap: array:1 ["mail_on_create_document_listener" => array:4 [        0 => "privates"        1 => "mail_on_create_document_listener"        2 => "getMailOnCreateDocumentListenerService.php"        3 => true      ]    ]    -serviceTypes: array:1 ["mail_on_create_document_listener" => "?"    ]    -externalId: null    -container: null    -factories: array:1 ["mail_on_create_document_listener" => array:4 [        0 => "privates"        1 => "mail_on_create_document_listener"        2 => "getMailOnCreateDocumentListenerService.php"        3 => true      ]    ]    -loading: []    -providedTypes: null  }  -instances: []  -serviceIds: array:1 ["App\EventListener\MailOnCreateDocumentListener" => "mail_on_create_document_listener"  ]}

Reading the code, it seems that the clear from EntityListenerResolver affects the instance part, but not the serviceIds.

How does this clear method is supposed to work?Is my service declaration wrong?

How to validate array of arrays in Symfony 4

$
0
0

I want to know how can I validate array of arrays in symfony. My validation rules are:

  1. User - NotBlank
  2. Date - Date and NotBlank
  3. Present - NotBlank

So far I have done this:

$validator = Validation::createValidator();$constraint = new Assert\Collection(array('user' => new Assert\NotBlank(),'date' => new Assert\Date(),'present' => new Assert\NotBlank()));$violations = $validator->validate($request->request->get('absences')[0], $constraint);

But the problem is that it only allows to validate single array eg.
$request->request->get('absences')[0].

Here is how the array looks like:

enter image description here


How to exclude some tables to be purged in DoctrineFixtures in Symfony 4?

$
0
0

How can we exclude some tables (for example, country, city, etc) to be purged via doctrine:fixtures:load? Is there any yaml configuration file or sth else?

How to attach image to the email using symfony mailer?

$
0
0

I need to add image into the email. My images are located inside the public folder. I have defined in my twig.yaml like this:

twig:    globals:        image_dir: '%kernel.project_dir%/public/images/logos'    default_path: '%kernel.project_dir%/templates'    debug: '%kernel.debug%'    strict_variables: '%kernel.debug%'    exception_controller: null

Now in my twig.html file, I am calling image like below.

<img src="{{ image_dir }}/logo.png" alt="pngss" />

But the image is not appearing.

Symfony 4 Doctrine update database

$
0
0

I am working on a web application. So i updated the local database, add some new columns using the following doctrine commands,

php bin/console make:entityphp bin/console make:migrationphp bin/console doctrine:migrations:migrate

Now i want to update the server. So could you please help in this case? What should i run in the server to update my production server database?

Symfony4 and Event Dispatcher issue, the script continues 25 seconds after the event

$
0
0

i have a issue with Event Dispatcher on Symfony4. The script contnues 25 seconds after the event finished . Here the code:

controller (necessary part):

$this->logger->notice("Log Start");$response = new JsonResponse($responseArray, 200);$this->eventDispatcher->dispatch(new FilterUserResponseEvent($user, $request, $response), FOSUserEvents::REGISTRATION_COMPLETED);$this->logger->notice("Log End");

EventSubscriber (necessary part):

$this->logger->notice("REGISTRATION_COMPLETED Start");...$this->logger->notice("REGISTRATION_COMPLETED End");

The results of the logs is:

10:00:00 Log Start10:00:00 REGISTRATION_COMPLETED Start10:00:00 REGISTRATION_COMPLETED End10:00:25 Log End

how is this possible? in my script there is nothing between the end of the event and the other log. maybe it is a symfony core bug? I want to say that it is not systematic, it happens sometimes.

thanks for your help!

How is it that Symfony is adding back a form field that has been removed in a PRE_SUBMIT event handler?

$
0
0

I have a form without a data class that consists of a single collection. I added a PRE_SUBMIT event listener that iterates over the collection and removes collection elements that don't have their checkboxes check and that aren't already persisted.

In my test case, the form is created with an 11 element array of data. After form submission, the form should reduced to 4 elements in the collection rather than the 11.

Here's a snippet of the form:

public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder            ->add('phyTypeItemTypeInstances', CollectionType::class, ['entry_type' => ConfigurePhysicalTypeItemTypeType::class,'entry_options' => ['label' => false],'allow_add' => true,'allow_delete' => true,'prototype' => false,'label' => false]);        $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event)         {            $data = $event->getData();            $form = $event->getForm();            $collection = $form->get('phyTypeItemTypeInstances');            foreach ($collection as $key => $item) {            if ((!array_key_exists('selection', $item)                  || $item['selection'] !== '1') && null === $collection->get($key)->getData()->getId()) {                $form->get('phyTypeItemTypeInstances')->remove($key);            }dump($form); //<------- Debug output shows a collection with 4 elements in the form as expected.        });    }    public function configureOptions(OptionsResolver $resolver)    {        $resolver->setDefaults(['data_class' => null,'allow_extra_fields' => true        ]);    } 

Based on debug output, it appears that the form reverts back to having 11 elements in the collection after handleRequest is called in the controller. Here's the controller excerpt:

        $dataArray = $this->getConfigurationArray($joinEntity, $bid);        $form = $this->createForm(ConfigurationJoinTableType::class, ['phyTypeItemTypeInstances' => $dataArray]);dump($form); //<-- Output shows a collection of 11 as expected        $form->handleRequest($request);dump($form); //<-- Outputs shows a collection of 11 even after the dump from the event listener showed a collection of 4. 

Am I missing something fundamental here? I have other forms where I add and remove fields with no issue. However, I think this is the first time I'm removing elements from a collection.

Correct way of adding wow.js to symfony webpack encore

$
0
0

I'm using Symfony 4.3.3 with webpack-encore-bundle v1.6.2 to develop website. When trying to add wow.js to the front-end, I'm facing with this error:

Uncaught ReferenceError: WOW is not defined

I ran npm install --save wowjs to install this package. Then import the library in the app.js as follow:

import WOW from 'wowjs/dist/wow.min.js';

After using yarn encore dev public files successfully created in output folder of webpack.

new WOW().init(); in main.js file arises the above error.

So, What's the correct way of doing that or basically I must do more stuff to have this working?

Thanks

Symfony Messenger: Send logged messenger errors per email (via swift_mailer)?

$
0
0

I've configured monolog to send errors via email as described in the symfony docs here: https://symfony.com/doc/4.3/logging/monolog_email.html

Works well with all errors happing during a request, as well as console command errors.But it does not send emails for errors which occurred during the handling of a messenger message.

Errors are shown when running the consumer bin/console messenger:consume async -vv and they also show up in prod.log like this:[2020-01-10 12:52:38] messenger.CRITICAL: Error thrown while handling message...

Thanks for any hints on how to set up monolog to get messenger errors emailed too.


Symfony Ldap checkPassword

$
0
0

I'm using Symfony 4.4 and I'm doing my own authenticator. Everything works fine, I just can't figure out how to compare the password entered by the user and the one in Ldap. I would like to do this in the "checkCredentials" method in my LoginFormAuthenticator. Here is my LdapUserProvider:

class LdapUserProvider implements UserProviderInterface, PasswordUpgraderInterface{    private $ldap;    private $baseDn;    private $searchDn;    private $searchPassword;    private $defaultRoles;    private $uidKey;    private $defaultSearch;    private $passwordAttribute;    private $extraFields;    //New    private $em;    public function __construct(Ldap $ldap, string $baseDn, EntityManagerInterface $em , string $searchDn = null, string $searchPassword = null, array $defaultRoles = [], string $uidKey = null, string $filter = null, string $passwordAttribute = null, array $extraFields = [])    {        if (null === $uidKey) {            $uidKey = 'sAMAccountName';        }        if (null === $filter) {            $filter = '({uid_key}={username})';        }        $this->ldap = $ldap;        $this->baseDn = $baseDn;        $this->searchDn = $searchDn;        $this->searchPassword = $searchPassword;        $this->defaultRoles = $defaultRoles;        $this->uidKey = $uidKey;        $this->defaultSearch = str_replace('{uid_key}', $uidKey, $filter);        $this->passwordAttribute = $passwordAttribute;        $this->extraFields = $extraFields;        $this->em = $em;    }    /**     * {@inheritdoc}     */    public function loadUserByUsername($username)    {        try {            $this->ldap->bind($this->searchDn, $this->searchPassword);            $username = $this->ldap->escape($username, '', LdapInterface::ESCAPE_FILTER);            $query = str_replace('{username}', $username, $this->defaultSearch);            $search = $this->ldap->query($this->baseDn, $query);        } catch (ConnectionException $e) {            throw new UsernameNotFoundException(sprintf('User "%s" not found.', $username), 0, $e);        }        $entries = $search->execute();        $count = \count($entries);        if (!$count) {            throw new UsernameNotFoundException(sprintf('User "%s" not found.', $username));        }        if ($count > 1) {            throw new UsernameNotFoundException('More than one user found.');        }        return $this->loadUser($username, $entries[0]);    }    /**     * {@inheritdoc}     */    public function refreshUser(UserInterface $user)    {        if (!$user instanceof LdapUser || !$user instanceof User) {            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', \get_class($user)));        }        //New        $userRepository = $this->em->getRepository("AppBundle:User");        $user = $userRepository->findOneBy(array("username" => $user->getUsername()));        if($user === null){            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));        }        return new LdapUser($user->getEntry(), $user->getUsername(), $user->getPassword(), $user->getRoles(), $user->getExtraFields());    }    /**     * {@inheritdoc}     */    public function upgradePassword(UserInterface $user, string $newEncodedPassword): void    {        if (!$user instanceof LdapUser) {            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', \get_class($user)));        }        if (null === $this->passwordAttribute) {            return;        }        try {            $user->getEntry()->setAttribute($this->passwordAttribute, [$newEncodedPassword]);            $this->ldap->getEntryManager()->update($user->getEntry());            $user->setPassword($newEncodedPassword);        } catch (ExceptionInterface $e) {            // ignore failed password upgrades        }    }    /**     * {@inheritdoc}     */    public function supportsClass($class)    {        return LdapUser::class === $class;    }    /**     * Loads a user from an LDAP entry.     *     * @param $username     * @param Entry $entry     * @return UserInterface     */    protected function loadUser($username, Entry $entry)    {        /*        $password = null;        $extraFields = [];        var_dump($this->passwordAttribute);        if (null !== $this->passwordAttribute) {            var_dump($this->passwordAttribute);            $password = $this->getAttributeValue($entry, $this->passwordAttribute);            var_dump($password);        }        foreach ($this->extraFields as $field) {            $extraFields[$field] = $this->getAttributeValue($entry, $field);        }        exit();        return new LdapUser($entry, $username, $password, $this->defaultRoles, $extraFields);*/        $userRepository = $this->em->getRepository("App:User");        //On récupère les infos de l'utilisateur qui se connecte        $user = $userRepository->findOneBy(array("username" => $username));        //Si l'utilisateur est null, donc pas présent en BDD mais OK niveau LDAP        if ($user === null) {            //Créé un User pour l'ajouter à la BDD une fois qu'on s'est assuré que c'était bien un utilisateur LDAP            //Cas première connexion de l'utilisateur            $user = new User();            $user->setFirstname($entry->getAttribute("givenName")[0]);            $user->setLastname($entry->getAttribute("sn")[0]);            $user->setEmail($entry->getAttribute("mail")[0]);            $user->setUsername($entry->getAttribute("uid")[0]);            $user->setRoles($this->defaultRoles);            $this->em->persist($user);            $this->em->flush();        } else {            $this->em->flush();        }        return $user;    }    public function checkPassword($password){    }    /**     * Fetches the password from an LDAP entry.     *     * @param null|Entry $entry     */    private function getPassword(Entry $entry)    {        if (null === $this->passwordAttribute) {            return;        }        if (!$entry->hasAttribute($this->passwordAttribute)) {            throw new InvalidArgumentException(sprintf('Missing attribute "%s" for user "%s".', $this->passwordAttribute, $entry->getDn()));        }        $values = $entry->getAttribute($this->passwordAttribute);        if (1 !== count($values)) {            throw new InvalidArgumentException(sprintf('Attribute "%s" has multiple values.', $this->passwordAttribute));        }        return $values[0];    }    private function getAttributeValue(Entry $entry, string $attribute)    {        var_dump("getAttributeValue ".$attribute);        if (!$entry->hasAttribute($attribute)) {            throw new InvalidArgumentException(sprintf('Missing attribute "%s" for user "%s".', $attribute, $entry->getDn()));        }        $values = $entry->getAttribute($attribute);        if (1 !== \count($values)) {            throw new InvalidArgumentException(sprintf('Attribute "%s" has multiple values.', $attribute));        }        return $values[0];    }}

I first thought about using the getPassword method but it requires and Entry, and I don't know how to get this Entry. Thanks

AssociationField does not save the entered values

$
0
0

AssociationField does not save the entered values in DB.I select Tag and click save. And does not save.I've tried everything, and I can't figure it out.

I even recorded a video

PostCrudController.php

<?phpnamespace App\Controller\Admin;use App\Entity\Post;Use App\Controller\TagController;use App\Entity\Tag;use App\Form\TagType;use Doctrine\DBAL\Types\TextType;use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;use EasyCorp\Bundle\EasyAdminBundle\Field\CollectionField;use EasyCorp\Bundle\EasyAdminBundle\Field\DateTimeField;use EasyCorp\Bundle\EasyAdminBundle\Field\Field;use EasyCorp\Bundle\EasyAdminBundle\Field\IdField;use EasyCorp\Bundle\EasyAdminBundle\Field\ImageField;use EasyCorp\Bundle\EasyAdminBundle\Field\SlugField;use EasyCorp\Bundle\EasyAdminBundle\Field\TextEditorField;use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;use Symfony\Component\Form\Extension\Core\Type\CollectionType;use Vich\UploaderBundle\Form\Type\VichImageType;use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;class PostCrudController extends AbstractCrudController{    public static function getEntityFqcn(): string    {        return Post::class;    }    public function configureFields(string $pageName): iterable    {        $imageFile = ImageField::new('thumbnailFile')->setFormType(VichImageType::class);        $image = ImageField::new('thumbnails')->setBasePath('/uploads/files');        $fields = [            IdField::new('id')->hideOnForm(),            AssociationField::new('category'),            AssociationField::new('tags'),            TextField::new('title'),            TextEditorField::new('content'),            Field::new('published'),            DateTimeField::new('createdAt')        ];        if ($pageName == Crud::PAGE_INDEX || $pageName == Crud::PAGE_DETAIL) {            $fields[] = $image;         } else {            $fields[] = $imageFile;        }        return $fields;    }}

I do not know what code to add. All the code is on github

Symfony isPasswordValid always return false

$
0
0

I have used following lines of code to create a user.

$newUser = new User();$plainPassword = 'test';$hashPassword = $this->passwordEncoder->encodePassword($newUser, $plainPassword);$newUser->setUserName($filterArray['username']);$newUser->setPassword($hashPassword);$newUser->setCreatedDatetime();$newUser->setStatus('active');$this->entityManager->persist($newUser);$this->entityManager->flush();

Now when I try to login

$this->passwordEncoder->isPasswordValid($user, $credentials->getPassword())

This line is always returning false. Here $user outputs

App\Entity\User {#592  -id: 1  -loginName: "test"  -loginPassword: "$2y$13$S5nEPTFznoemyO1.WsBxl.beyGL4i1YuwteDx7GDtzP"  -createdDatetime: DateTime @1602489653 {#596    date: 2020-10-12 10:00:53.0 Europe/Berlin (+02:00)  }  -status: "active"}

Can anybody help me on this.

Not able to validate the correct username and password in symfony

$
0
0

I have used following lines of code to create a user.

$newUser = new User();$plainPassword = 'test';$hashPassword = $this->passwordEncoder->encodePassword($newUser, $plainPassword);$newUser->setUserName($filterArray['username']);$newUser->setPassword($hashPassword);$newUser->setCreatedDatetime();$newUser->setStatus('active');$this->entityManager->persist($newUser);$this->entityManager->flush();

Now when I try to login

$this->passwordEncoder->isPasswordValid($user, $credentials->getPassword())

This line is always returning false. Here $user outputs

App\Entity\User {#592  -id: 1  -loginName: "test"  -loginPassword: "$2y$13$S5nEPTFznoemyO1.WsBxl.beyGL4i1YuwteDx7GDtzP"  -createdDatetime: DateTime @1602489653 {#596    date: 2020-10-12 10:00:53.0 Europe/Berlin (+02:00)  }  -status: "active"}

Can anybody help me on this.

Disable doctrine cache for unittests

$
0
0

I have a unittests in my Symfony 4 project which show a inconsistent behaviour and I suspect the doctrine caching is responsible for this. So I am looking for a way to disable caching for Unittests.

My current packages/test/doctrine.yaml file for the environment test looks like this:

doctrine:    orm:        auto_generate_proxy_classes: false        metadata_cache_driver:            type: service            id: doctrine.system_cache_provider        query_cache_driver:            type: service            id: doctrine.system_cache_provider        result_cache_driver:            type: service            id: doctrine.result_cache_providerservices:    doctrine.result_cache_provider:        class: Symfony\Component\Cache\DoctrineProvider        public: false        arguments:            - '@doctrine.result_cache_pool'    doctrine.system_cache_provider:        class: Symfony\Component\Cache\DoctrineProvider        public: false        arguments:            - '@doctrine.system_cache_pool'framework:    cache:        pools:            doctrine.result_cache_pool:                adapter: cache.app            doctrine.system_cache_pool:                adapter: cache.system

If I want to disable any caching in doctrine for tests, is there any cache driver, which is a non-caching dummy? If I leave those entries empty I guess my prod settings or the general settings would be used, which means the results would also be cached. Can I explicitly non-cache?

config    \__packages        |        |__ prod        |   \__doctrine.yaml        |        |__ dev        |   \__doctrine.yaml        |        |__ test        |   \__doctrine.yaml        |        \__doctrine.yaml
Viewing all 3924 articles
Browse latest View live


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