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

How to Migrate users to new password hashing algorithms with fos user in Symfony 4?

$
0
0

I have an old Symfony 2 application with fos user that contains passwords encoded with the sha512 algorithm.

I would like after migrating the table users to the new application symfony 4 with fos user 2.1 to be able to modify the password with the algorithm bcrypt when the user is logging with a listener.

It is possible under Symfony to have several encoders but the problem is that we can not duplicate the same encoder with different algorithm like:

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

or with this code, I have this error message:

Unrecognized option "FOS\UserBundle\Model\UserInterface" under "security.encoders.old"

    encoders:
        old:
            FOS\UserBundle\Model\UserInterface:
            algorithm: sha512
        new:
            FOS\UserBundle\Model\UserInterface:
            algorithm: bcrypt

Custom Validator in Symfony 4

$
0
0

I create an email form and I want to return 3 validations which are FreeEmail, ValidateEmail and DisposableEmail in a field type. For example, If the email entered is disposable, I want it to show the error of disposable, but it cannot work. It only returns the first validation. How do I do ?

<?php

namespace MBV\Validator;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use MailboxValidator\SingleValidation;

class MBVEmailValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {

        $results2 = $mbv->FreeEmail($value);
            if ($results2 === false){
                return;
            }
            else if (trim($results2->error_code) == ''){
                if ($results2->is_free == 'False'){
                    return;
                }
            }
            else if (trim($results2->error_code) != ''){
                return;
            }

            //TODO: implement the validation here
            $this->context->buildViolation($constraint->message2)
            ->setParameter('{{ value }}', $value)
            ->addViolation();

        $results = $mbv->ValidateEmail($value);
            if ($results === false) {
                return;
            } else if (trim($results->error_code) == '') {
                if ($results->status == 'True') {
                    return;
                }
            } else if (trim($results->error_code) != ''){           
                return;
            }

            // TODO: implement the validation here
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $value)
                ->addViolation();

        $results1 = $mbv->DisposableEmail($value);
            if ($results1 === false){
                return;
            }
            else if (trim($results1->error_code) == ''){
                if ($results1->is_disposable == 'False'){
                    return;
                }
            }
            else if (trim($results1->error_code) != ''){
                return;
            }

            //TODO: implement the validation here
            $this->context->buildViolation($constraint->message1)
            ->setParameter('{{ value }}', $value)
            ->addViolation();
        }
}

Symfony Flex does not install on create new full project

$
0
0

Could someone help me resolve the below issue

** The "https://flex.symfony.com/versions.json" file could not be downloaded: SSL operation failed with code 1. OpenSS L Error messages: error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed**

=Curl Also install and Pem file also configure
=Openssl also install and configure
Error-Flex SSL



[symfonyflex][1]
[SymfonyFlex][2]


  [1]: https://i.stack.imgur.com/QKUpi.png
  [2]: https://i.stack.imgur.com/jkuC0.png

How to access the value of one attribute of one table from another table (One-to-One bi-directional relationship) in Symfony 4?

$
0
0

I have two tables (application and employee), which relate with a One-to-One directional relationship.

In my application table I have four attributes:

  • name_app
  • responsible_app
  • responsible_app_backup_1
  • responsible_app_backup_2.

In my employee table I have three attributes:

  • uid_employee
  • first_name
  • last_name.

How can I list out uid, first_name, and last_name for each responsible_app?

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

Symfony 4 + Api platform Cannot validate values of type \"NULL\" automatically. on nativeSQL query

$
0
0

i have been stuck for few hours with this:

Doing a simple query on my Variation base :

$query = "UPDATE variation SET status = 'FALSE' WHERE id IN
('ba21ac3f-0e7f-4bb9-b31f-dbd49053002e','a656e102-0339-4db0-a4b1-16451c2f1d90','64da7d32-2c9f-4478-bc6d-0b7b6c07af8e','8aba2925-7017-4899-bdfa-bf341c0fccec','6d4374cb-3713-4162-be53-2232202b5809','1810057a-6157-45bf-85d5-ade282b7d807','967d7495-6e93-4530-b6d8-d23640b39226','ebdcd88f-1f58-44b6-a14d-d0db9a564671')";

$result = $this->entityManager->getConnection()->prepare($query);

$result->execute();

And using postman it's returning me :

"@context": "/contexts/Error", "@type": "hydra:Error", "hydra:title": "An error occurred", "hydra:description": "Cannot validate values of type \"NULL\" automatically. Please provide a constraint."`

my variation class:

/**
 * @var bool
 *
 * @ORM\Column(type="boolean")
 *
 * @Groups({"variation"})
 */
protected $status;

How comes it try to validate somethings. Ps the query is fully working ( POSTGRES - Symfony 4.2 - PHP72 )

symfony4 how to extend entityRepository with ServiceEntityRepository and SortableRepository

$
0
0

I installed the stof StofDoctrineExtensionsBundle and configured it to use only sortable.

According to te docs to use the sortable function in my controller, I need to extend the sortable entityRepository class with SortableRepository. Like this:

class InfluencerRepository extends SortableRepository {}

This seems to work, now the problem is I also need it to extend ServiceEntityRepository, wich you will mainly use for fetching basic stuff from the DB. So normaly my class looks like this:

class InfluencerRepository extends ServiceEntityRepository {}

How can I make it possible to use both of the subclasses, because you can not extend 2 sub classes?

symfony 4.1 phpunit 6.5 show catched exceptions on console using WebTestCase

$
0
0

I use Symfony 4.1 WebTestCase and phpunit 6.5 for test that an not-existing user can not log using Symfony Authentification against database.

I think phpunit should NOT show any errors, but it writes in console many exceptions, as the output is plenty of non important exceptions as they have been catched correctly.

Also, assertNotEquals throws a compare exception too !!

Please if anybody can explain me how to fix it.I have been for days without any luck.

My code is like this (Sorry, My first question on this web):

//------------------ REQUEST FOR PAGE LOGIN
$crawler = $client->request('GET', $url_login);

//------------------ (SOM NOT IMPORTANT STAFF AND REDIRECTION)
$crawler = $client->submit($form);

//------------------ SENDING INCORRECT LOGIN USER
$form = $crawler->filter('.btn.btn-primary.btn-block')->form();
// set some values
$form['_username'] = 'failed_user';
$form['_password'] = 'failed_password';

//------------------ ALL IS OK SINCE HERE


//------------------ THIS SHOWS 
//UsernameNotFoundException ON CONSOLE BUT EXCEPTION HAS BEEN CATCHED 
//AND FORM RETURNED OK SAYING "This user doesn't exist"

$crawler = $client->submit($form);

//------------------ THIS SHOW 
// SebastianBergmann\Comparator\ComparisonFailure:  Failed asserting that two strings are equal...
//ON CONSOLE !!

$this->assertNotEquals($url_login, $url_resp, 'La página de login no es la esperada al identificarnos correctamente');

And console is like this:

esteban@linux-9j0e:~/workspace_newproject/mywebproject> bin/phpunit 
#!/usr/bin/env php
PHPUnit 6.5.11 by Sebastian Bergmann and contributors.

Testing Project Test Suite
PHP Symfony\Component\Security\Core\Exception\UsernameNotFoundException:  User "esteban_fail" not found. in /home/esteban/workspace_newproject/mywebproject/vendor/symfony/doctrine-bridge/Security/User/EntityUserProvider.php on line 61
PHP Stack trace:
PHP   1. {main}() /home/esteban/workspace_newproject/mywebproject/bin/phpunit:0
PHP   2. require() /home/esteban/workspace_newproject/mywebproject/bin/phpunit:18
PHP   3. include() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/phpunit-bridge/bin/simple-phpunit:260
PHP   4. PHPUnit\TextUI\Command::main() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/phpunit:17
PHP   5. Symfony\Bridge\PhpUnit\Legacy\CommandForV6->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/TextUI/Command.php:148
PHP   6. Symfony\Bridge\PhpUnit\Legacy\TestRunnerForV6->doRun() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/TextUI/Command.php:195
PHP   7. PHPUnit\Framework\TestSuite->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/TextUI/TestRunner.php:546
PHP   8. PHPUnit\Framework\TestSuite->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestSuite.php:755
PHP   9. App\Tests\Controller\Security\Login\LoginControllerTest->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestSuite.php:755
PHP  10. PHPUnit\Framework\TestResult->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:894
PHP  11. App\Tests\Controller\Security\Login\LoginControllerTest->runBare() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestResult.php:698
PHP  12. App\Tests\Controller\Security\Login\LoginControllerTest->runTest() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:939
PHP  13. ReflectionMethod->invokeArgs() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:1071
PHP  14. App\Tests\Controller\Security\Login\LoginControllerTest->testshowLoginFails() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:1071
PHP  15. Symfony\Bundle\FrameworkBundle\Client->submit() /home/esteban/workspace_newproject/mywebproject/tests/Controller/Security/Login/LoginControllerTest.php:96
PHP  16. Symfony\Bundle\FrameworkBundle\Client->request() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/browser-kit/Client.php:298
PHP  17. Symfony\Bundle\FrameworkBundle\Client->doRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/browser-kit/Client.php:351
PHP  18. Symfony\Bundle\FrameworkBundle\Client->doRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/framework-bundle/Client.php:131
PHP  19. App\Kernel->handle() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/http-kernel/Client.php:68
PHP  20. Symfony\Component\HttpKernel\HttpKernel->handle() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/http-kernel/Kernel.php:188
PHP  21. Symfony\Component\HttpKernel\HttpKernel->handleRaw() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/http-kernel/HttpKernel.php:66
PHP  22. Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher->dispatch() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/http-kernel/HttpKernel.php:125
PHP  23. Symfony\Component\EventDispatcher\EventDispatcher->dispatch() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php:141
PHP  24. Symfony\Component\EventDispatcher\EventDispatcher->doDispatch() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/EventDispatcher.php:44
PHP  25. Symfony\Component\EventDispatcher\Debug\WrappedListener->__invoke() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/EventDispatcher.php:212
PHP  26. call_user_func:{/home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/Debug/WrappedListener.php:104}() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/Debug/WrappedListener.php:104
PHP  27. Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener->onKernelRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/Debug/WrappedListener.php:104
PHP  28. Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener->onKernelRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security-bundle/EventListener/FirewallListener.php:48
PHP  29. Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener->handleRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Http/Firewall.php:61
PHP  30. Symfony\Bundle\SecurityBundle\Debug\WrappedListener->handle() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security-bundle/Debug/TraceableFirewallListener.php:35
PHP  31. Symfony\Component\Security\Http\Firewall\UsernamePasswordFormAuthenticationListener->handle() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security-bundle/Debug/WrappedListener.php:46
PHP  32. Symfony\Component\Security\Http\Firewall\UsernamePasswordFormAuthenticationListener->attemptAuthentication() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Http/Firewall/AbstractAuthenticationListener.php:128
PHP  33. Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager->authenticate() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Http/Firewall/UsernamePasswordFormAuthenticationListener.php:100
PHP  34. Symfony\Component\Security\Core\Authentication\Provider\DaoAuthenticationProvider->authenticate() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Core/Authentication/AuthenticationProviderManager.php:76
PHP  35. Symfony\Component\Security\Core\Authentication\Provider\DaoAuthenticationProvider->retrieveUser() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Core/Authentication/Provider/UserAuthenticationProvider.php:64
PHP  36. Symfony\Bridge\Doctrine\Security\User\EntityUserProvider->loadUserByUsername() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Core/Authentication/Provider/DaoAuthenticationProvider.php:74
PHP Symfony\Component\Security\Core\Exception\UsernameNotFoundException:  User "esteban_fail" not found. in /home/esteban/workspace_newproject/mywebproject/vendor/symfony/doctrine-bridge/Security/User/EntityUserProvider.php on line 61
PHP Stack trace:
PHP   1. {main}() /home/esteban/workspace_newproject/mywebproject/bin/phpunit:0
PHP   2. require() /home/esteban/workspace_newproject/mywebproject/bin/phpunit:18
PHP   3. include() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/phpunit-bridge/bin/simple-phpunit:260
PHP   4. PHPUnit\TextUI\Command::main() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/phpunit:17
PHP   5. Symfony\Bridge\PhpUnit\Legacy\CommandForV6->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/TextUI/Command.php:148
PHP   6. Symfony\Bridge\PhpUnit\Legacy\TestRunnerForV6->doRun() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/TextUI/Command.php:195
PHP   7. PHPUnit\Framework\TestSuite->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/TextUI/TestRunner.php:546
PHP   8. PHPUnit\Framework\TestSuite->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestSuite.php:755
PHP   9. App\Tests\Controller\Security\Login\LoginControllerTest->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestSuite.php:755
PHP  10. PHPUnit\Framework\TestResult->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:894
PHP  11. App\Tests\Controller\Security\Login\LoginControllerTest->runBare() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestResult.php:698
PHP  12. App\Tests\Controller\Security\Login\LoginControllerTest->runTest() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:939
PHP  13. ReflectionMethod->invokeArgs() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:1071
PHP  14. App\Tests\Controller\Security\Login\LoginControllerTest->testshowLoginFails() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:1071
PHP  15. Symfony\Bundle\FrameworkBundle\Client->submit() /home/esteban/workspace_newproject/mywebproject/tests/Controller/Security/Login/LoginControllerTest.php:96
PHP  16. Symfony\Bundle\FrameworkBundle\Client->request() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/browser-kit/Client.php:298
PHP  17. Symfony\Bundle\FrameworkBundle\Client->doRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/browser-kit/Client.php:351
PHP  18. Symfony\Bundle\FrameworkBundle\Client->doRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/framework-bundle/Client.php:131
PHP  19. App\Kernel->handle() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/http-kernel/Client.php:68
PHP  20. Symfony\Component\HttpKernel\HttpKernel->handle() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/http-kernel/Kernel.php:188
PHP  21. Symfony\Component\HttpKernel\HttpKernel->handleRaw() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/http-kernel/HttpKernel.php:66
PHP  22. Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher->dispatch() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/http-kernel/HttpKernel.php:125
PHP  23. Symfony\Component\EventDispatcher\EventDispatcher->dispatch() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php:141
PHP  24. Symfony\Component\EventDispatcher\EventDispatcher->doDispatch() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/EventDispatcher.php:44
PHP  25. Symfony\Component\EventDispatcher\Debug\WrappedListener->__invoke() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/EventDispatcher.php:212
PHP  26. call_user_func:{/home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/Debug/WrappedListener.php:104}() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/Debug/WrappedListener.php:104
PHP  27. Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener->onKernelRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/Debug/WrappedListener.php:104
PHP  28. Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener->onKernelRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security-bundle/EventListener/FirewallListener.php:48
PHP  29. Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener->handleRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Http/Firewall.php:61
PHP  30. Symfony\Bundle\SecurityBundle\Debug\WrappedListener->handle() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security-bundle/Debug/TraceableFirewallListener.php:35
PHP  31. Symfony\Component\Security\Http\Firewall\UsernamePasswordFormAuthenticationListener->handle() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security-bundle/Debug/WrappedListener.php:46
PHP  32. Symfony\Component\Security\Http\Firewall\UsernamePasswordFormAuthenticationListener->attemptAuthentication() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Http/Firewall/AbstractAuthenticationListener.php:128
PHP  33. Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager->authenticate() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Http/Firewall/UsernamePasswordFormAuthenticationListener.php:100
PHP  34. Symfony\Component\Security\Core\Authentication\Provider\DaoAuthenticationProvider->authenticate() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Core/Authentication/AuthenticationProviderManager.php:76
PHP  35. Symfony\Component\Security\Core\Authentication\Provider\DaoAuthenticationProvider->retrieveUser() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Core/Authentication/Provider/UserAuthenticationProvider.php:64
PHP Symfony\Component\Security\Core\Exception\BadCredentialsException:  Bad credentials. in /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Core/Authentication/Provider/UserAuthenticationProvider.php on line 67
PHP Stack trace:
PHP   1. {main}() /home/esteban/workspace_newproject/mywebproject/bin/phpunit:0
PHP   2. require() /home/esteban/workspace_newproject/mywebproject/bin/phpunit:18
PHP   3. include() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/phpunit-bridge/bin/simple-phpunit:260
PHP   4. PHPUnit\TextUI\Command::main() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/phpunit:17
PHP   5. Symfony\Bridge\PhpUnit\Legacy\CommandForV6->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/TextUI/Command.php:148
PHP   6. Symfony\Bridge\PhpUnit\Legacy\TestRunnerForV6->doRun() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/TextUI/Command.php:195
PHP   7. PHPUnit\Framework\TestSuite->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/TextUI/TestRunner.php:546
PHP   8. PHPUnit\Framework\TestSuite->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestSuite.php:755
PHP   9. App\Tests\Controller\Security\Login\LoginControllerTest->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestSuite.php:755
PHP  10. PHPUnit\Framework\TestResult->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:894
PHP  11. App\Tests\Controller\Security\Login\LoginControllerTest->runBare() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestResult.php:698
PHP  12. App\Tests\Controller\Security\Login\LoginControllerTest->runTest() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:939
PHP  13. ReflectionMethod->invokeArgs() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:1071
PHP  14. App\Tests\Controller\Security\Login\LoginControllerTest->testshowLoginFails() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:1071
PHP  15. Symfony\Bundle\FrameworkBundle\Client->submit() /home/esteban/workspace_newproject/mywebproject/tests/Controller/Security/Login/LoginControllerTest.php:96
PHP  16. Symfony\Bundle\FrameworkBundle\Client->request() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/browser-kit/Client.php:298
PHP  17. Symfony\Bundle\FrameworkBundle\Client->doRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/browser-kit/Client.php:351
PHP  18. Symfony\Bundle\FrameworkBundle\Client->doRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/framework-bundle/Client.php:131
PHP  19. App\Kernel->handle() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/http-kernel/Client.php:68
PHP  20. Symfony\Component\HttpKernel\HttpKernel->handle() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/http-kernel/Kernel.php:188
PHP  21. Symfony\Component\HttpKernel\HttpKernel->handleRaw() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/http-kernel/HttpKernel.php:66
PHP  22. Symfony\Component\HttpKernel\Debug\TraceableEventDispatcher->dispatch() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/http-kernel/HttpKernel.php:125
PHP  23. Symfony\Component\EventDispatcher\EventDispatcher->dispatch() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/Debug/TraceableEventDispatcher.php:141
PHP  24. Symfony\Component\EventDispatcher\EventDispatcher->doDispatch() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/EventDispatcher.php:44
PHP  25. Symfony\Component\EventDispatcher\Debug\WrappedListener->__invoke() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/EventDispatcher.php:212
PHP  26. call_user_func:{/home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/Debug/WrappedListener.php:104}() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/Debug/WrappedListener.php:104
PHP  27. Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener->onKernelRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/Debug/WrappedListener.php:104
PHP  28. Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener->onKernelRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security-bundle/EventListener/FirewallListener.php:48
PHP  29. Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener->handleRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Http/Firewall.php:61
PHP  30. Symfony\Bundle\SecurityBundle\Debug\WrappedListener->handle() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security-bundle/Debug/TraceableFirewallListener.php:35
PHP  31. Symfony\Component\Security\Http\Firewall\UsernamePasswordFormAuthenticationListener->handle() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security-bundle/Debug/WrappedListener.php:46
PHP  32. Symfony\Component\Security\Http\Firewall\UsernamePasswordFormAuthenticationListener->attemptAuthentication() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Http/Firewall/AbstractAuthenticationListener.php:128
PHP  33. Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager->authenticate() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Http/Firewall/UsernamePasswordFormAuthenticationListener.php:100
PHP  34. Symfony\Component\Security\Core\Authentication\Provider\DaoAuthenticationProvider->authenticate() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Core/Authentication/AuthenticationProviderManager.php:76
PHP Symfony\Component\Security\Core\Exception\BadCredentialsException:  Bad credentials. in /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Core/Authentication/Provider/UserAuthenticationProvider.php on line 67
PHP Stack trace:
PHP   1. {main}() /home/esteban/workspace_newproject/mywebproject/bin/phpunit:0
PHP   2. require() /home/esteban/workspace_newproject/mywebproject/bin/phpunit:18
PHP   3. include() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/phpunit-bridge/bin/simple-phpunit:260
PHP   4. PHPUnit\TextUI\Command::main() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/phpunit:17
PHP   5. Symfony\Bridge\PhpUnit\Legacy\CommandForV6->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/TextUI/Command.php:148
PHP   6. Symfony\Bridge\PhpUnit\Legacy\TestRunnerForV6->doRun() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/TextUI/Command.php:195
PHP   7. PHPUnit\Framework\TestSuite->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/TextUI/TestRunner.php:546
PHP   8. PHPUnit\Framework\TestSuite->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestSuite.php:755
PHP   9. App\Tests\Controller\Security\Login\LoginControllerTest->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestSuite.php:755
PHP  10. PHPUnit\Framework\TestResult->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:894
PHP  11. App\Tests\Controller\Security\Login\LoginControllerTest->runBare() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestResult.php:698
PHP  12. App\Tests\Controller\Security\Login\LoginControllerTest->runTest() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:939
PHP  13. ReflectionMethod->invokeArgs() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:1071
PHP  14. App\Tests\Controller\Security\Login\LoginControllerTest->testshowLoginFails() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:1071
PHP  15. Symfony\Bundle\FrameworkBundle\Client->submit() /home/esteban/workspace_newproject/mywebproject/tests/Controller/Security/Login/LoginControllerTest.php:96
PHP  16. Symfony\Bundle\FrameworkBundle\Client->request() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/browser-kit/Client.php:298
PHP  17. Symfony\Bundle\FrameworkBundle\Client->doRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/browser-kit/Client.php:351
PHP  18. Symfony\Bundle\FrameworkBundle\Client->doRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/framework-bundle/Client.php:131

(...sorry, cut by putting too long text..)

PHP  26. call_user_func:{/home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/Debug/WrappedListener.php:104}() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/Debug/WrappedListener.php:104
PHP  27. Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener->onKernelRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/event-dispatcher/Debug/WrappedListener.php:104
PHP  28. Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener->onKernelRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security-bundle/EventListener/FirewallListener.php:48
PHP  29. Symfony\Bundle\SecurityBundle\Debug\TraceableFirewallListener->handleRequest() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Http/Firewall.php:61
PHP  30. Symfony\Bundle\SecurityBundle\Debug\WrappedListener->handle() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security-bundle/Debug/TraceableFirewallListener.php:35
PHP  31. Symfony\Component\Security\Http\Firewall\UsernamePasswordFormAuthenticationListener->handle() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security-bundle/Debug/WrappedListener.php:46
PHP  32. Symfony\Component\Security\Http\Firewall\UsernamePasswordFormAuthenticationListener->attemptAuthentication() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Http/Firewall/AbstractAuthenticationListener.php:128
PHP  33. Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager->authenticate() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/security/Http/Firewall/UsernamePasswordFormAuthenticationListener.php:100
.PHP SebastianBergmann\Comparator\ComparisonFailure:  Failed asserting that two strings are equal. in /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/vendor/sebastian/comparator/src/ScalarComparator.php on line 67
PHP Stack trace:
PHP   1. {main}() /home/esteban/workspace_newproject/mywebproject/bin/phpunit:0
PHP   2. require() /home/esteban/workspace_newproject/mywebproject/bin/phpunit:18
PHP   3. include() /home/esteban/workspace_newproject/mywebproject/vendor/symfony/phpunit-bridge/bin/simple-phpunit:260
PHP   4. PHPUnit\TextUI\Command::main() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/phpunit:17
PHP   5. Symfony\Bridge\PhpUnit\Legacy\CommandForV6->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/TextUI/Command.php:148
PHP   6. Symfony\Bridge\PhpUnit\Legacy\TestRunnerForV6->doRun() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/TextUI/Command.php:195
PHP   7. PHPUnit\Framework\TestSuite->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/TextUI/TestRunner.php:546
PHP   8. PHPUnit\Framework\TestSuite->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestSuite.php:755
PHP   9. App\Tests\Controller\Admin\Security\Enteprises\AdminEnterprisesControllerTest->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestSuite.php:755
PHP  10. PHPUnit\Framework\TestResult->run() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:894
PHP  11. App\Tests\Controller\Admin\Security\Enteprises\AdminEnterprisesControllerTest->runBare() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestResult.php:698
PHP  12. App\Tests\Controller\Admin\Security\Enteprises\AdminEnterprisesControllerTest->runTest() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:939
PHP  13. ReflectionMethod->invokeArgs() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:1071
PHP  14. App\Tests\Controller\Admin\Security\Enteprises\AdminEnterprisesControllerTest->test_Add_Edit_And_Delete_Grouper() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/TestCase.php:1071
PHP  15. App\Tests\Controller\Security\Login\LoginControllerTest->ht_return_Logged_User_Client() /home/esteban/workspace_newproject/mywebproject/tests/Controller/Admin/Security/Enterprises/AdminEnterprisesControllerTest.php:121
PHP  16. PHPUnit\Framework\Assert::assertNotEquals() /home/esteban/workspace_newproject/mywebproject/tests/Controller/Security/Login/LoginControllerTest.php:52
PHP  17. PHPUnit\Framework\Assert::assertThat() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/Assert.php:592
PHP  18. PHPUnit\Framework\Constraint\LogicalNot->evaluate() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/Assert.php:2116
PHP  19. PHPUnit\Framework\Constraint\IsEqual->evaluate() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/Constraint/LogicalNot.php:116
PHP  20. SebastianBergmann\Comparator\ScalarComparator->assertEquals() /home/esteban/workspace_newproject/mywebproject/bin/.phpunit/phpunit-6.5/src/Framework/Constraint/IsEqual.php:129
.                                                               5 / 5 (100%)

Time: 1.44 seconds, Memory: 34.00MB

OK (5 tests, 70 assertions)

Remaining deprecation notices (1)

1x: Doctrine\Common\ClassLoader is deprecated.
    1x in LoginControllerTest::testshowLoginFails from App\Tests\Controller\Security\Login

doctrine2 entity number in month generation

$
0
0

I've got Invoice entity, in which I'd like to generate subsequent numbers within a given month.
Entity code:

/**
 * Class Invoice
 * @package App\Entity
 * @ORM\Entity()
 * @ORM\HasLifecycleCallbacks()
 */
class Invoice
{
(...)
   /**
     * @var int
     * @ORM\Column(type="integer")
     */
    private $year;

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

    /**
     * @var int
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="CUSTOM")
     * @ORM\CustomIdGenerator(class="App\Helper\InvoiceNumberGenerator")
     */
    private $counter;
(...)
    /**
     * @ORM\PrePersist
     * @ORM\PreUpdate
     */
    public function numberGenerator()
    {
        if ($this->getYear() === null) {
            $this->setYear(date('Y'));
            $this->setMonth(date('m'));
        }
    }

And App\Helper\InvoiceNumberGenerator code is:

<?php

namespace App\Helper;


use App\Entity\Invoice;
use Doctrine\Common\Persistence\ObjectRepository;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Id\AbstractIdGenerator;
use Exception;

class InvoiceNumberGenerator extends AbstractIdGenerator
{

    /**
     * Generates an invoice number
     *
     * @param EntityManager $em
     * @param Invoice $entity
     * @return mixed
     * @throws Exception
     */
    public function generate(EntityManager $em, $entity)
    {
        if (!$entity instanceof Invoice) {
            throw new Exception('Generator służy tylko do generowania numerów faktur.');
        }
        /** @var ObjectRepository | EntityRepository $invoiceRepository */
        $invoiceRepository = $em->getRepository(Invoice::class);

        /** @var Invoice $lastInvoice */
        $lastInvoice = $invoiceRepository->findOneBy(
            array(
                'year' => $entity->getYear(),
                'month' => $entity->getMonth()
            ),
            array(
                'counter' => 'desc'
            )
        );

        if (empty($lastInvoice)) {
            return 1;
        }

        return $lastInvoice->getCounter() + 1;
    }
}

When I dump $lastInvoice, it shows:

Invoice {#5522 ▼
  -id: 1
  -generated: false
  -fileName: "example"
  -year: 2019
  -month: 11
  -counter: 1
  -name: "AG"
  -company: "Gall"
  -address: "Street 1"
  -address2: "Gliwice"
  -nip: "6314567890"
  -reservation: Reservation {#5855 ▶}
  -date: null
}

So it looks like the generator gets to selecting last one correctly, but nevertheless I got error when trying to create new Invoice:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'counter' cannot be null

Any advise on what I'm doing wrong?

How to save a 1-N-1 relation buildForm SF4

$
0
0

I have many-to-many relationships. Treining -> TrainingStudents -> User. Training can have many students. I connected it with the trainingStudents table. I didn't use ManytoMany mapping because the entity TrainingStudents has additional fields besides id_training and id_student. I would like to save students in the training edit form and I don't know how to do it in buildForm to display students in select and save them from this level

/**
 * @ORM\Entity(repositoryClass="App\Repository\TrainingRepository")
 * @ORM\Table(name="trainings")
 * @ORM\HasLifecycleCallbacks
 */
class Training
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;  

    /**
     * @ORM\OneToMany(
     *     targetEntity="TrainingStudents",
     *     mappedBy="trainings",
     *     fetch="EXTRA_LAZY"
     * )
     */
    private $trainingStudents;
}

/**
 * @ORM\Entity(repositoryClass="App\Repository\TrainingStudentsRepository")
 * @ORM\Table(name="training_students")
 */
class TrainingStudents
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Training", inversedBy="trainingStudents")
     * @ORM\JoinColumn(nullable=false)
     *
     * @Assert\NotBlank
     */
    private $trainings;

    /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="trainings")
     * @ORM\JoinColumn(nullable=false)
     */
    private $student;

    /**
     * @ORM\Column(name="present", type="boolean", nullable=true)
     */
    private $present;
}





class TrainingType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array                $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder            
            ->add('trainingStudents', EntityType::class, [
                'required' => false,
                'multiple' => true,
                'query_builder' => function (EntityRepository $er) {
                    return $er->createQueryBuilder('user')
                        ->andWhere('user.roles LIKE :roles ')
                        ->setParameter('roles', '%"ROLE_STUDENT"%');
                },
                'choice_label' => function ($student) {
                    return $student->getName().''.$student->getSurname().
                        ' ('.(((new \DateTime())->diff($student->getBirthday() ?? new \DateTime()))->y).'lat)'.
                        ' (tel.: '.$student->getPhone().')';
                },
                'choice_value' => 'student.uid',
                'class' => User::class,
                'attr' => [
                    'multiple' => 'multiple',
                ],
            ])

Paginator with ApiPlatform on custom repository

$
0
0

I would like to have the hydra:totalItems and hydra:view in my response, so I followed the doc https://api-platform.com/docs/core/pagination/#custom-controller-action but I have this error "The controller must return a "Symfony\Component\HttpFoundation\Response" object but it returned an object of type ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator."

<?php

namespace App\Controller;

use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;
use App\Repository\ProductRepository;
use App\Repository\TermRelationshipsRepository;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;

class FakeAction extends AbstractController
{
    private $termRelationshipsRepository;

    public function __construct(TermRelationshipsRepository $termRelationshipsRepository)
    {
        $this->termRelationshipsRepository = $termRelationshipsRepository;
    }

    /**
     * @Route(
     *     name="api_fake_action",
     *     path="/api/fake"
     * )
     */
    public function __invoke(): Paginator
    {
        return $this->termRelationshipsRepository->findAllProductsIdsByTerm_id(126);
    }
}

<?php

namespace App\Repository;

use App\Entity\TermRelationships;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\Tools\Pagination\Paginator as DoctrinePaginator;
use ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator;
use Symfony\Bridge\Doctrine\RegistryInterface;

/**
 * @method TermRelationships|null find($id, $lockMode = null, $lockVersion = null)
 * @method TermRelationships|null findOneBy(array $criteria, array $orderBy = null)
 * @method TermRelationships[]    findAll()
 * @method TermRelationships[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class TermRelationshipsRepository extends ServiceEntityRepository
{
    const ITEMS_PER_PAGE = 5;

    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, TermRelationships::class);
    }

    public function findAllProductsIdsByTerm_id($term_id, $array_result = false, $offset = 1, $nb_result = 23) : Paginator
    {
        $firstResult = (1 - $offset) * self::ITEMS_PER_PAGE;

        $queryBuilder = $this->createQueryBuilder('p');
        $queryBuilder
            ->andWhere('p.termTaxonomyId = :termTaxonomyId')
            ->setParameter('termTaxonomyId', $term_id)
        ;

        $criteria = Criteria::create()
            ->setFirstResult($firstResult)
            ->setMaxResults(self::ITEMS_PER_PAGE);
        $queryBuilder->addCriteria($criteria);

        $doctrinePaginator = new DoctrinePaginator($queryBuilder);
        $paginator = new Paginator($doctrinePaginator);

        return $paginator;
    }
}

FatalError with RequestContext constructor

$
0
0

I have a problem with an update of a Symfony 4 project, I get a fatal error:

"Argument 1 passed to Symfony\Component\Routing\RequestContext::__construct() must be of the type string, null given, called in var/cache/dev/ContainerHuVphBe/srcApp_KernelDevDebugContainer.php on line 1569"

Has anyone ever had a similar problem? It's impossible for me to find where this configuration error came from.

thank you in advance for your help

symfony form always valid despite of constraints

$
0
0

I can't get Symfony constraints to work.
I have this simple form inside an action:

   /**
     * @Route("reservation/{hash}/invoice", name="reservation-invoice")
     * @param Request $request
     * @param TranslatorInterface $translator
     * @param Reservation $reservation
     * @return JsonResponse|Response
     */
    public function invoiceAction(Request $request, TranslatorInterface $translator, Reservation $reservation)
    {
        if (empty($reservation->getInvoice())) {
            $invoice = new Invoice();
            $invoice->setReservation($reservation);
        } else {
            $invoice = $reservation->getInvoice();
        }

        $form = $this->createFormBuilder($invoice)
            ->add(
                'name',
                TextType::class,
                array(
                    'label' => $translator->trans('invoice.name'),
                    'required' => true,
                    'attr' => array(
                        'placeholder' => $translator->trans('invoice.name_placeholder'),
                        'class' => 'form-control',
                    ),
                    'constraints' => array(
                        new Length(array('min' => 3, 'max' => 50))
                    )
                )
            )
            ->add(
                'company',
                TextType::class,
                array(
                    'label' => $translator->trans('invoice.company'),
                    'required' => true,
                    'attr' => array(
                        'placeholder' => $translator->trans('invoice.company_placeholder'),
                        'class' => 'form-control',
                    ),
                    'constraints' => array(
                        new Length(array('min' => 3, 'max' => 50))
                    )
                )
            )
            ->add(
                'address',
                TextType::class,
                array(
                    'label' => $translator->trans('invoice.address1'),
                    'required' => true,
                    'attr' => array(
                        'placeholder' => $translator->trans('invoice.address1_placeholder'),
                        'class' => 'form-control',
                    ),
                    'constraints' => array(
                        new Length(array('min' => 3, 'max' => 100))
                    )
                )
            )
            ->add(
                'address2',
                TextType::class,
                array(
                    'label' => $translator->trans('invoice.address2'),
                    'required' => true,
                    'attr' => array(
                        'placeholder' => $translator->trans('invoice.address2_placeholder'),
                        'class' => 'form-control',
                    ),
                    'constraints' => array(
                        new Length(array('min' => 3, 'max' => 100))
                    )
                )
            )
            ->add(
                'nip',
                TextType::class,
                array(
                    'label' => $translator->trans('invoice.nip'),
                    'required' => true,
                    'attr' => array(
                        'placeholder' => $translator->trans('invoice.nip_placeholder'),
                        'class' => 'form-control',
                    ),
                    'constraints' => array(
                        new Length(array('min' => 3, 'max' => 10))
                    )
                )
            )
            ->setAction($this->generateUrl('reservation-invoice', array('hash' => $reservation->getHash())))
            ->setMethod('POST')
            ->getForm();

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $invoice = $form->getData();
            $this->db()->persist($invoice);
            $this->db()->flush();
            $this->addFlash('success', $translator->trans('invoice.data_changed'));
            return new JsonResponse(array(
                'redirect' => $this->generateUrl('reservation', array('hash' => $reservation->getHash()),
                    UrlGeneratorInterface::ABSOLUTE_URL)
            ));
        }

        return $this->response(
            array(
                'form' => $form->createView()
            )
        );
}

In config I have:

framework:
    validation:
        enabled: true

And form display is really simple:

{{ form_start(form) }}
    <div class="form-group">
        {{ form_label(form.name) }}
        {{ form_widget(form.name) }}
        {{ form_errors(form.name) }}
    </div>
    <div class="form-group">
        {{ form_label(form.company) }}
        {{ form_widget(form.company) }}
        {{ form_errors(form.company) }}
    </div>
    <div class="form-group">
        {{ form_label(form.address) }}
        {{ form_widget(form.address) }}
        {{ form_errors(form.address) }}
    </div>
    <div class="form-group">
        {{ form_label(form.address2) }}
        {{ form_widget(form.address2) }}
        {{ form_errors(form.address2) }}
    </div>
    <div class="form-group">
        {{ form_label(form.nip) }}
        {{ form_widget(form.nip) }}
        {{ form_errors(form.nip) }}
    </div>
{{ form_end(form) }}

When I submit the form with empty inputs, the $form->isValid() returns true and I get database error as these fields cannot be empty.
I suspect there is something I missed, but according to Symfony docs that's all you have to do.


EDIT:
I managed to do assertions in Entity class annotations, like:

/**
 * @var string
 * @ORM\Column(type="string", length=50)
 * @Assert\NotBlank()
 * @Assert\Length(min=3, max=50)
 */
private $name;

What seems strange to me is that leaving controller intact, 'required' => true doesn't matter at all. When I post empty field, I get 1 error, but when I post 1 letter I get 2 errors: one from contraints array and one from annotation.

How can I use a class constant as the tag for binded parameter service?

$
0
0

I have tagged a group of services that implement the same interface like this in my configuration:

// services.yml
services:
  _instanceof:
     App\SomeInterface:
       tags: [ !php/const App\SomeInterface::TAG ]

(Where the value for App\SomeInterface::TAG is very_unique_identifier)

I would like to reuse this value to bind this parameter like this:

// services.yaml
 services:
  _defaults:
    autowire: true      
    autoconfigure: true 
    public: false
    bind:
      $fooStrategies: !tagged !php/const App\SomeInterface::TAG 

But when I do it like this, I get an empty RewindableGenerator.

Instead I can do it like this, using the literal value for the constant:

bind:
      $fooStrategies: !tagged 'very_unique_identifier'

... and it works as expected, and the RewindableGenerator has all the necessary services inside.

How can I use the PHP constant in both places, so I do not have to repeat the value in different places? Obviously, not a huge deal, but I'd like to avoid it if possible.

symfony4 how to override a repository from 3th party bundle

$
0
0

I installed the stof StofDoctrineExtensionsBundle and configured it to use only sortable.

According to te docs to use the sortable function in my controller, I need to extend the sortable entityRepository class with SortableRepository. Like this:

class InfluencerRepository extends SortableRepository {}

This seems to work, now the problem is I also need it to extend ServiceEntityRepository, wich you will mainly use for fetching basic stuff from the DB. So normaly my class looks like this:

class InfluencerRepository extends ServiceEntityRepository {}

I figured out I can edit the original sortableRepository by extending it with ServiceEntityRepository instead of just EntityRepository. Now editing code from a 3th party bundle is bad practice, but i can't figure out how to override this repository.


Symfony demo app install fails - pdo_sqlite missing

$
0
0

I am trying to use the Symfony 4 demo application https://github.com/symfony/demo but when I install it with composer I get the error described below. I am using Ubuntu 16.04 and php 7.1 installed via phpbrew.

My steps are as follows:

$ cd /var/www/html
$ phpbrew use php-7.1.13
$ sudo php composer.phar create-project symfony/symfony-demo

which yields this error:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
- The requested PHP extension ext-pdo_sqlite * is missing from your system. Install or enable PHP's pdo_sqlite extension.

if I check which extensions are loaded:

$ phpbrew extension

I get

Loaded extensions:
...
[*] pdo_sqlite

so it appears that extension is loaded.

What am I doing wrong please?

EntityType - Can not use query_builder

$
0
0

I have a problem with my FormType in Symfony. I have a field that allows me to check one or more checkboxs whose values represent objects from another entity. (In this case, types of holidays).

Except that I do not want to display them all, so I use a query_builder. And I have this:

->add('typesConges', EntityType::class, [
                'class' => TypeConge::class,
                'choice_label' => 'nom',
                'expanded' => true,
                'multiple' => true,
                'query_builder' => function (TypeCongeRepository $repoTypes) {
                    return $repoTypes->getTypesNotNull();
                }
            ])

But I've this error :

The name "Heures supp" contains illegal characters. Names should start with a letter, digit or underscore and only contain letters, digits, numbers, underscores ("_"), hyphens ("-") and colons (":").

However, if I remove the "query_builder", I've all my "TypeConge" ( the "Heures supp" too).

GestionSoldes.php

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;

class GestionSoldes
{

    /**
     * Types de congés
     *
     * @var Collection|TypeConge[]
     */
    private $typesConges;

    /**
     * All types
     *
     * @var boolean
     */
    private $allTypes;

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

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

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

    public function addTypesConge(TypeConge $typesConge): self
    {
        if (!$this->typesConges->contains($typesConge)) {
            $this->typesConges[] = $typesConge;
        }

        return $this;
    }

    public function removeTypesConge(TypeConge $typesConge): self
    {
        if ($this->typesConges->contains($typesConge)) {
            $this->typesConges->removeElement($typesConge);
        }

        return $this;
    }

    public function getAllTypes(): ?bool
    {
        return $this->allTypes;
    }

    public function setAllTypes(bool $allTypes): self
    {
        $this->allTypes = $allTypes;

        return $this;
    }
}

Form:

<?php

namespace App\Form;

use App\Entity\TypeConge;
use App\Entity\GestionSoldes;
use App\Repository\TypeCongeRepository;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;

class GestionSoldesType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('typesConges', EntityType::class, [
                'class' => TypeConge::class,
                'choice_label' => 'nom',
                'expanded' => true,
                'multiple' => true,
                'query_builder' => function (TypeCongeRepository $repoTypes) {
                    return $repoTypes->getTypesNotNull();
                }
            ])
            ->add('allTypes', CheckboxType::class, [
                'required' => false,
                'label' => 'Tous les types de congés',
                'label_attr' => [
                    'class' => 'custom-control-label',
                    'for' => 'allTypes'
                ],
                'attr' => [
                    'class' => 'custom-control-input',
                    'id' => 'allTypes'
                ]
            ])
        ;
    }

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

}

My repo function:

/**
 * Retourne les types de congés qui ont un solde initial différent de null ( pour form EntityType )
 *
 * @return void
 */
public function getTypesNotNull()
{
    return $this->createQueryBuilder('t')
        ->where('t.soldeInitial is not null')
        ->orderBy('t.nom', 'ASC');
}

Add a new page requested via ajax with Framework7

$
0
0

I'm developing a new project with Framework7(v5.1.3) and Symfony(4).
My problem is that I dont want to use Framework7 routing but only the Symfony one. So I need to know how to add a new page after I requested a content. Here's my code:

app.request.get('/users/5/profile', function (data) {
    console.log(data);
});

Symfony4 405 method not allowed cors

$
0
0

I am making simple todo app, with Symfony4 backend and vue.js for frontend, I encountered 405 error status for unknow reason since few other endpoints are working correctly.

here is part of my listController:

/**
 * @return \FOS\RestBundle\View\View
 */
public function getListsAction()
{
    $data = $this->taskListRepository->findAll();
    return $this->view($data, Response::HTTP_OK);
}


/**
 * @Rest\RequestParam(name="title", description="Title of the list", nullable=false)
 * @param ParamFetcher $paramFetcher
 * @return \FOS\RestBundle\View\View
 */
public function postListsAction(ParamFetcher $paramFetcher)
{
    $title = $paramFetcher->get('title');
    if ($title) {
        $list = new TaskList();
        $preferences = new Preference();
        $preferences->setList($list);
        $list->setPreferences($preferences);
        $list->setTitle($title);
        $this->entityManager->persist($list);
        $this->entityManager->flush();
        return $this->view($list, Response::HTTP_CREATED);
    }
    return $this->view(['title' => 'This cannot be null'], Response::HTTP_BAD_REQUEST);
}

the get action is working correctly here it allows me to get all lists from db

and nelmio_cors.yaml file:

nelmio_cors:
    defaults:
        origin_regex: true
        allow_credentials: true
        allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
        allow_methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']
        allow_headers: ['Content-Type', 'Authorization', 'origin', 'Accept', 'bearer', 'Allow']
        expose_headers: ['Link']
        max_age: 3600
    paths:
        '^/': ~

as you can see POST method is allowed.

debug:router log : enter image description here

as shown the method occurs under expected method and endpoint, register and login_check, where method is not specified working correctly with using POST

network error:

enter image description here

and in console I am getting cors error.

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?

Viewing all 3916 articles
Browse latest View live


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