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

Is there a way to access Doctrine repositories from stand-alone code?

$
0
0

I have a Symfony 4 app which is complete and working. Any uploaded files are put inside an upload folder outside the doc root and accessed via a separate cdn url.

Inside the upload folder I have a htaccess file that redirects any request, let’s say for example an image, to a php file which then serves the image.

What I want to be able to do is send an auth key along with the image request so that the standalone index.php file can check the user is valid from the database.

This means I need some way of accessing the symfony entity manager from outside of symfony, by including it. The other option would be a curl request to a symfony controller, but I’d rather not add additional network requests if possible. The third option is a separate pdo direct to the database and make sql queries... but again I’d prefer to use the symfony entity manager by including symfony somehow so I can use other features if needed.

I actually tried including the symfony bootstrap in the index.php but that then drags in the need for routing to work which isn’t needed in this case.


why does SonataAdminTreeBundle not show the navbar for filters and viewmodes?

$
0
0

we work on a projekt with symfony 4 and sonata. we are using the SonataAdminTreeBundle to manage our Categories.

basically everything works fine - but the menu from sonata were the datagrid filters are located (aka nabvbar) is not showing up. in that menu you can usually switch the view modes (grid, list, tree) and set up some filters. it worked at the start but once i tried the tree view for the first time, everything was gone and did not show up again.

so what we basically do is:src/Admin/CategoryAdmin:

namespace App\Admin;use RedCode\TreeBundle\Admin\AbstractTreeAdmin;use Sonata\AdminBundle\Datagrid\ListMapper;use Sonata\AdminBundle\Datagrid\DatagridMapper;use Sonata\AdminBundle\Form\FormMapper;use Symfony\Component\Form\Extension\Core\Type\TextType;final class CategoryAdmin extends AbstractTreeAdmin{    protected function configureFormFields(FormMapper $formMapper)    {        $formMapper->add('name', TextType::class);    }    protected function configureDatagridFilters(DatagridMapper $datagridMapper)    {        $datagridMapper->add('name');        $datagridMapper->add('product_id');    }    protected function configureListFields(ListMapper $listMapper)    {        $listMapper->addIdentifier('name');    }}

here is a gif out of the documentation from SonataAdminTreeBundle were you can see that he switches the view modes and also at least sees the datagridfilters in the navbar.

https://camo.githubusercontent.com/e39aa1eccba43ceb7d33e3cb0e908899cbba24ae/687474703a2f2f672e7265636f726469742e636f2f517764627252335039522e676966

over here the navbar does not show up even if the rest is working completely fine.

HWIOAuthBundle and facebook returns no response in Symfony 4.4

$
0
0

I try to implement HWIOAuthBundle without FOSUserBundle. So far, I managed to be redirected to facebook page, but when I return back to the symfony I receive empty response in the url like this (in localhost): http://site.local/#=__. I tried to print the response from loadUserByOAuthUserResponse in my class App\Security\OAuthUserProvider but again nothing is printed (I have a doubt whether it is called or not).I read a similar question here but without any success

I paste below the important sectors in my files:

Security.yaml

security:encoders:    MsgPhp\User\Infrastructure\Security\UserIdentity: 'argon2i'# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providersproviders:    msgphp_user: { id: MsgPhp\User\Infrastructure\Security\UserIdentityProvider }            # used to reload user from session & other features (e.g. switch_user)    app_user_provider:        id: App\Security\OauthUserProvider    users:        entity:            class: App\Entity\Userfirewalls:    dev:        pattern: ^/(_(profiler|wdt)|css|images|js)/        security: false    main:        anonymous: true        provider: msgphp_user        oauth:            resource_owners:                facebook:           "/login/check-facebook"                google:             "/login/check-google"        #         my_custom_provider: "/login/check-custom"        #         my_github:          "/login/check-github"            login_path:        /profile            use_forward:       false            failure_path:      /register            default_target_path: /profile            oauth_user_provider:                service: hwi_oauth.user.provider        # activate different ways to authenticate        # http_basic: true        # https://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate        # https://symfony.com/doc/current/security/form_login_setup.html        form_login:            login_path: /            check_path: /            default_target_path: /profile            username_parameter: email            password_parameter: password        logout:            path: logout# Easy way to control access for large sections of your site# Note: Only the *first* access control that matches will be usedaccess_control:    # - { path: ^/admin, roles: ROLE_ADMIN }    - { path: ^/profile, roles: ROLE_TRAVELER }

hwi_oauth.yaml

hwi_oauth:    # list of names of the firewalls in which this bundle is active, this setting MUST be set    firewall_names: [main]    resource_owners:        facebook:            type:                facebook            client_id:           '%env(FB_ID)%'            client_secret:       '%env(FB_SECRET)%'            scope:               "email"            infos_url:           "https://graph.facebook.com/me?fields=id,name,email,picture.type(square)"            paths:                email:          email                profilepicture: picture.data.url            options:                display: popup                csrf: true

hwi_oauth_routing.yaml

hwi_oauth_redirect:    resource: "@HWIOAuthBundle/Resources/config/routing/redirect.xml"    prefix:   /redirecthwi_oauth_connect:       resource: "@HWIOAuthBundle/Resources/config/routing/connect.xml"       prefix:   /connect    hwi_oauth_login:       resource: "@HWIOAuthBundle/Resources/config/routing/login.xml"       prefix:   /login    facebook_login:        path: /login/check-facebook    google_login:        path: /login/check-google

services.yaml

services:    # default configuration for services in *this* file    _defaults:        autowire: true              autoconfigure: true         public: false     hwi_oauth.user.provider:         class: App\Security\OAuthUserProvider

routes.yaml

# virtual routeslogout:    path: /logout    methods: GETapi_login:    path: /api/login    methods: POSToauth_login_check:    path: /login-check/{resource}

App\Security\OAuthUserProvider

namespace App\Security;use Symfony\Component\Security\Core\Exception\UnsupportedUserException;use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;use Symfony\Component\Security\Core\User\UserInterface;use Symfony\Component\Security\Core\User\UserProviderInterface;use Doctrine\ORM\EntityManagerInterface;use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthAwareUserProviderInterface;use App\Entity\User;class OauthUserProvider implements UserProviderInterface, OAuthAwareUserProviderInterface{    private $em;    private $property = 'email';        /**     * @return UserInterface     */    public function loadUserByOAuthUserResponse(UserResponseInterface $response)    {        print_r($response);        return $this->loadUserByUsername($response->getEmail());    }

Escaping is not applied in included template with Twig Bundle & Symfony 4.2

$
0
0

I am working on a Symfony 4.2.12 project with Twig bundle installed. Twig escaping strategy is the default 'html' one: I did not change anything about that.

I realized escaping filters |e('html'), |e('html_attr') ... are not applied in a Twig included template whereas in parent template it works normally. Perhaps i have missed something like 'context' as concerns escaping, but this creates a big issue like unwanted xss vulnerability.

Maybe this comes from a loop which calls the included template for each iteration... and escaped variables are not kept in memory, or a kind of that!

For instance, to make filters work in included template i have to declare them as follows by escaping twice: |e|e('html_attr'), etc...

Included template

<!-- Strangely default filter does not work in included template, i have also to use it by escaping twice! -->{{ myVar1|e|e('html') }} <!-- This is not 'html' escaped as it should be! -->{{ myVar1 }} <!-- Please note the necessary double escaping!? --><img src="..." alt="{{ myVar2|e|e('html_attr') }}">

Parent template loop

...<!-- This is correctly 'html' escaped as expected! -->{{ myVar }}<!-- This is correctly 'html_attr' escaped as expected! --><a href="{{ myVar|e('html_attr') }}" ...></a>{% for object in parentObject.objects %}    ....    {% include 'my_include.html.twig' with {'myVar1': myValue1,'myVar2': myValue2,'myVar3': myValue3|e('html_attr'), {# Here, any of these are also correctly escaped obviously with all filters! #}        ...    } only %}    ....{% endfor %}....

I wonder if this is a well known issue, bug (for this Twig bundle version) or a simple personal misunderstanding...

Thank you for your feedbacks!

Symfony 4 "code": 401, "message": "Invalid credentials." jwt authentication error

$
0
0

I'm trying to make a jwt authentication with Symfony 4

I configured my project as follow

// security.yaml security:    encoders:        App\Entity\User:            algorithm: auto    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers    providers:        # used to reload user from session & other features (e.g. switch_user)        app_user_provider:            entity:                class: App\Entity\User                property: username    firewalls:        dev:            pattern: ^/(_(profiler|wdt)|css|images|js)/            security: false        login:            pattern:  ^/api/login            stateless: true            anonymous: true            json_login:                check_path:               /api/login_check                success_handler:          lexik_jwt_authentication.handler.authentication_success                failure_handler:          lexik_jwt_authentication.handler.authentication_failure        api:                pattern:   ^/api                stateless: true                guard:                    authenticators:                        - lexik_jwt_authentication.jwt_token_authenticator        main:            anonymous: true            provider: app_user_provider            # 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: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }        - { path: ^/api,       roles: IS_AUTHENTICATED_FULLY }
// routes.yamlapi_login_check:    path: /api/login_check
// .env###> nelmio/cors-bundle ###CORS_ALLOW_ORIGIN=^https?://(localhost|127\.0\.0\.1)(:[0-9]+)?$###< nelmio/cors-bundle ######> lexik/jwt-authentication-bundle ###JWT_SECRET_KEY=%kernel.project_dir%/config/jwt/private.pemJWT_PUBLIC_KEY=%kernel.project_dir%/config/jwt/public.pemJWT_PASSPHRASE=d96058cb8b34d7061148465f3d286ae4###< lexik/jwt-authentication-bundle ###
//lexik_jwt_authentication.yamllexik_jwt_authentication:    secret_key:       '%kernel.project_dir%/config/jwt/private.pem' # required for token creation    public_key:       '%kernel.project_dir%/config/jwt/public.pem'  # required for token verification    pass_phrase:      'd96058cb8b34d7061148465f3d286ae4'    token_ttl:        3600
//UserRepository.phpclass UserRepository extends ServiceEntityRepository{    public function __construct(ManagerRegistry $registry)    {        parent::__construct($registry, User::class);    }    // /**    //  * @return User[] Returns an array of User objects    //  */    /*    public function findByExampleField($value)    {        return $this->createQueryBuilder('u')            ->andWhere('u.exampleField = :val')            ->setParameter('val', $value)            ->orderBy('u.id', 'ASC')            ->setMaxResults(10)            ->getQuery()            ->getResult()        ;    }    */    /*    public function findOneBySomeField($value): ?User    {        return $this->createQueryBuilder('u')            ->andWhere('u.exampleField = :val')            ->setParameter('val', $value)            ->getQuery()            ->getOneOrNullResult()        ;    }    */

and I generated 2 keys (private and public) in a folder named Jwt inside the config folder.

Now according to a documentation that I followed if I run:

curl -X POST -H "Content-Type: application/json" http://localhost/api/login_check -d '{"username":"johndoe","password":"test"}'

I'll be able to get a token like that in return

{"token" : "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXUyJ9.eyJleHAiOjE0MzQ3Mjc1MzYsInVzZXJuYW1lIjoia29ybGVvbiIsImlhdCI6IjE0MzQ2NDExMzYifQ.nh0L_wuJy6ZKIQWh6OrW5hdLkviTs1_bau2GqYdDCB0Yqy_RplkFghsuqMpsFls8zKEErdX5TYCOR7muX0aQvQxGQ4mpBkvMDhJ4-pE4ct2obeMTr_s4X8nC00rBYPofrOONUOR4utbzvbd4d2xT_tj4TdR_0tsr91Y7VskCRFnoXAnNT-qQb7ci7HIBTbutb9zVStOFejrb4aLbr7Fl4byeIEYgp2Gd7gY"}

but instead I got this error:

{"error":{"code":400,"message":"Bad Request","exception":[{"message":"Invalid JSON.","class":"Symfony\\Component\\HttpKernel\\Exception\\B [...]

and when I used postman and send

{"username": "test","password": "test"}`url : `http://localhost:8000/api/login_check`method : `POST`

I got this error{"code": 401,"message": "Invalid credentials."}

could you please tell me why i got this error and how to fix it Postman

Deserialize datetime with value null with Serializer Component Symfony4.4

$
0
0

I received an error when I deserialize an object which contains an attribute of type datetime but its value is null.the error message:The data is either an empty string or null, you should pass a string that can be parsed with the passed format or a valid DateTime string.

Symfony 4 login Guard authenticator errors

$
0
0

On login page I get this in dev.log:

Guard authenticator does not support the request. {"firewall_key":"main","authenticator":"App\Security\LoginFormAuthenticator"} []

Plus on the register page, after submitting I get

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

And in dev.log:

Guard authentication failed. {"exception":"[object] (Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException(code: 0):

The same code is working on my colleague's machine cannot get where can be the problem.

security.yaml

        firewalls:        static_pages:            pattern:    ^/static            security:   false        oauth_token:            pattern:    ^/oauth/token            security:   false        oauth_authorize:            pattern:    ^/oauth/auth            security:   false            # Add your favorite authentication process here        dev:            pattern: ^/(_(profiler|wdt)|css|images|js)/            security: false        main:            pattern: ^/            user_checker: security.user_checker            form_login:                provider: app_user                csrf_token_generator: security.csrf.token_manager                default_target_path: app_homepage            logout:       true            anonymous:    true            guard:                provider: app_user                entry_point: App\Security\LoginFormAuthenticator                authenticators:                    - App\Security\GoogleAuthenticator                    - App\Security\FacebookAuthenticator                    - App\Security\LoginFormAuthenticator

SecurityController.php

<?phpnamespace App\Controller\Identity;use App\Controller\BaseController;use App\Entity\User;use App\Security\AuthenticationManager;use App\Util\UserManager;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\HttpFoundation\Session\Session;use Symfony\Component\Security\Core\Encoder\EncoderFactory;use Symfony\Component\Security\Core\Encoder\NativePasswordEncoder;use Symfony\Component\Security\Core\Exception\AuthenticationException;use Symfony\Component\Security\Core\Security;use Symfony\Component\Routing\Annotation\Route;use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;/** * Class SecurityController */class SecurityController extends BaseController{    /**     * @Route("/login", name="app_login")     *     * @param AuthenticationUtils $authenticationUtils     *     * @return Response     */    public function login(AuthenticationUtils $authenticationUtils): Response    {        $error = $authenticationUtils->getLastAuthenticationError();        $lastUsername = $authenticationUtils->getLastUsername();        return $this->render('Security/login.html.twig', ['last_username' => $lastUsername,'error' => $error        ]);    }    /**     * @Route("/admin-login", name="app_security_admin_login", methods={"POST", "GET"})     *     * @param Request $request     *     * @return Response     */    public function adminLogin(Request $request)    {        /** @var $session Session */        $session = $request->getSession();        $authErrorKey = Security::AUTHENTICATION_ERROR;        $lastUsernameKey = Security::LAST_USERNAME;        // get the error if any (works with forward and redirect -- see below)        if ($request->attributes->has($authErrorKey)) {            $error = $request->attributes->get($authErrorKey);        } elseif (null !== $session && $session->has($authErrorKey)) {            $error = $session->get($authErrorKey);            $session->remove($authErrorKey);        } elseif ($request->query->has('error')) {            $error = $request->query->get('error');        } else {            $error = null;        }        if (!$error instanceof AuthenticationException) {            $error = null; // The value does not come from the security component.        }        // last username entered by the user        $lastUsername = (is_null($session)) ? '' : $session->get($lastUsernameKey);        $tokenManager = $this->getToken();        $csrfToken = $tokenManager            ? $tokenManager->getToken('authenticate')->getValue()            : null;        return $this->render('Security/admin_login.html.twig', ['last_username' => $lastUsername,'error' => $error,'csrf_token' => $csrfToken,        ]);    }    /**     * @Route("/admin-login-check", name="app_security_admin_login_check", methods={"POST", "GET"})     *     * @param Request     $request     * @param UserManager $userManager     *     * @return Response     */    public function adminLoginCheck(Request $request, UserManager $userManager)    {        $username = $request->request->get('_username');        $password = $request->request->get('_password');        $encoders = new NativePasswordEncoder(13);        $factory = new EncoderFactory([$encoders]);        /** @var User $user */        $user = $userManager->findUserByUsername($username);        if(!$user){            return $this->redirectToRoute('app_security_admin_login',                ['error' => 'Username doesnt exists']            );        }        $encoder = $factory->getEncoder(User::class);        $salt = $user->getSalt();        if(!$encoder->isPasswordValid($user->getPassword(), $password, $salt)) {            return $this->render("Security/admin_login.html.twig", ['error' => 'Username or Password not valid'            ]);        }        $token = $this->get(AuthenticationManager::class)->authenticate($user);        return $this->redirectToRoute("admin_homepage");    }    /**     * @Route("/login", name="app_security_login", methods={"POST", "GET"})     *     * @param Request $request     *     * @return Response     */    public function loginAction(Request $request)    {        /** @var $session Session */        $session = $request->getSession();        $authErrorKey = Security::AUTHENTICATION_ERROR;        $lastUsernameKey = Security::LAST_USERNAME;        /** get the error if any (works with forward and redirect -- see below) */        if ($request->attributes->has($authErrorKey)) {            $error = $request->attributes->get($authErrorKey);        } elseif (null !== $session && $session->has($authErrorKey)) {            $error = $session->get($authErrorKey);            $session->remove($authErrorKey);        } else {            $error = null;        }        if (!$error instanceof AuthenticationException) {            $error = null; // The value does not come from the security component.        }        /** last username entered by the user */        $lastUsername = (is_null($session)) ? '' : $session->get($lastUsernameKey);        $tokenManager = $this->getToken();        $csrfToken = $tokenManager            ? $tokenManager->getToken('authenticate')->getValue()            : null;        return $this->render('Security/login.html.twig',['last_username' => $lastUsername,'error' => $error,'csrf_token' => $csrfToken,        ]);    }    /**     * @Route("/login_check", name="app_security_check", methods={"POST"})     */    public function checkAction()    {        throw new \RuntimeException('You must configure the check path to be handled by the firewall using form_login in your security firewall configuration.');    }    /**     * @Route("/logout", name="app_security_logout", methods={"GET"})     */    public function logoutAction()    {        throw new \RuntimeException('You must activate the logout in your security firewall configuration.');    }    protected function getToken()    {        return $this->get("security.csrf.token_manager");    }}

I could provide other files if needed.Thank you.

How to get form validation groups defined as closure function which were used by handleRequest method?

$
0
0

Based on example presented in doc

$resolver->setDefaults(['validation_groups' => function (FormInterface $form) {            $data = $form->getData();            if (Client::TYPE_PERSON == $data->getType()) {                return ['person'];            }                        return ['company'];        },    ]);

In my controller I would like to get an array of groups which were used by $form->handleRequest($request);

I can get the closure by $form->getConfig()->getOption('validation_groups') and maybe somehow then execute it by myself. But I only want to get a simple array like ['person'] as handleRequest has already determined which groups should be used.

How to get that information from FormInterface or how to execute closure returned from config?


Symfony 4 Bundle: AuthenticationUtils but no such service exists

$
0
0

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

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

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

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

In the Bundle:

SecurityController.php

<?phpnamespace App\Aroban\Bundle\UtilisateurBundle\Controller;use App\Aroban\Bundle\UtilisateurBundle\Entity\Utilisateur;use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\Routing\Generator\UrlGeneratorInterface;use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;use Swift_Mailer;class SecurityController extends AbstractController{    public function login(AuthenticationUtils $authenticationUtils): Response    {        $error = $authenticationUtils->getLastAuthenticationError();        $lastUsername = $authenticationUtils->getLastUsername();        return $this->render('@Utilisateur/security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);    }.......}

Configuration.php

<?phpnamespace App\Aroban\Bundle\UtilisateurBundle\DependencyInjection;use Symfony\Component\Config\Definition\Builder\TreeBuilder;use Symfony\Component\Config\Definition\ConfigurationInterface;class Configuration implements ConfigurationInterface{    public function getConfigTreeBuilder()    {        $treeBuilder = new TreeBuilder('utilisateur');        $rootNode = $treeBuilder->getRootNode();        return $treeBuilder;    }}

UtilisateurExtension.php

<?phpnamespace App\Aroban\Bundle\UtilisateurBundle\DependencyInjection;use Symfony\Component\DependencyInjection\ContainerBuilder;use Symfony\Component\DependencyInjection\Extension\Extension;use Symfony\Component\Config\FileLocator;use Symfony\Component\DependencyInjection\Loader;class UtilisateurExtension extends Extension{    /**     * {@inheritdoc}     */    public function load(array $configs, ContainerBuilder $container): void    {        $configuration = new Configuration();        $config = $this->processConfiguration($configuration, $configs);        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));        $loader->load('services.yaml');    }}

services.yaml (bundle)

services:  _defaults:    autowire: true      # Automatically injects dependencies in your services.    autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.    public: false       # Allows optimizing the container by removing unused services; this also means  App\Aroban\Bundle\UtilisateurBundle\:    resource: '../../*'    exclude: '../../{Entity,Migrations,Tests,Kernel.php}'  App\Aroban\Bundle\UtilisateurBundle\Controller\:    resource: '../../Controller/*'    tags: ['controller.service_arguments']

When I execute the command

php bin/console debug:container | grep security

I do not see the service ...

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

Thanks for your help!

Symfony4 - sharing cache pool between two entity managers, is it a bad idea or do I encounter a bug?

$
0
0

it is going to be lengthy post, I encountering weird behavior where I see in profiler that one entity managers is said to map entity that it does not map. It looks like this:bottom of doctrine section in profilerHere is doctrine.yaml:

doctrine:    dbal:        default_connection: default        connections:            default:                driver:   "pdo_mysql"                host:     "127.0.0.1"                port:     "3306"                dbname:   "example"                user:     "root"                password: ""                charset:  utf8mb4                server_version: "mariadb-10.4.10"            logs:                driver:   "pdo_mysql"                host:     "127.0.0.1"                port:     "3306"                dbname:   "example_logs"                user:     "root"                password: ""                charset:  utf8mb4                server_version: "mariadb-10.4.10"    orm:        auto_generate_proxy_classes: true        default_entity_manager: default        entity_managers:            default:                query_cache_driver:                    type: pool                    pool: apcu.default.cache.pool                metadata_cache_driver:                    type: pool                    pool: apcu.default.cache.pool                result_cache_driver:                    type: pool                    pool: apcu.default.cache.pool                connection: default                naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware                mappings:                    App:                        is_bundle: false                        type: annotation                        dir: '%kernel.project_dir%/src/Entity/Main'                        prefix: 'App\Entity\Main'                        alias: App            logs:                query_cache_driver:                    type: pool                    pool: apcu.default.cache.pool                metadata_cache_driver:                    type: pool                    pool: apcu.default.cache.pool                result_cache_driver:                    type: pool                    pool: apcu.default.cache.pool                connection: logs                naming_strategy: doctrine.orm.naming_strategy.underscore_number_aware                mappings:                    LogBundle:                        is_bundle: false                        type: annotation                        dir: '%kernel.project_dir%/src/Entity/Logs'                        prefix: 'App\Entity\Logs'                        alias: App

And here is framework.yaml with cache pool configuration:

framework:    secret: '%env(APP_SECRET)%'    session:        handler_id: null        cookie_secure: auto        cookie_samesite: lax    php_errors:        log: true    cache:        pools:            apcu.default.cache.pool:                adapter: cache.adapter.apcu            apcu.logs.cache.pool:                adapter: cache.adapter.apcu

If I remove metadata_cache_driver configuration from logs entity_manager configuration, or change it to use different cache pool (apcu.logs.cache.pool) than default entity manager then profiler reports correct mappings (Example entity in default em and logs em is empty).

The issue occurs only when entity is feed trough form and $form->handleRequest() handles it, creating or modifying entity without forms does not cause such issue. Here is my controller:

<?phpnamespace App\Controller;use App\Entity\Main\Example;use App\Form\Type\ExampleType;use Doctrine\ORM\EntityManagerInterface;use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\Routing\Annotation\Route;class ExampleController extends AbstractController {    /**     * @Route("/example1")     * @Template     */    public function example1(EntityManagerInterface $em){        $example = new Example();        $example->setValue('example value');        try {            $em->persist($example);            $em->flush();        } catch(\Exception $e){            return new Response('An error has occurred. '.$e->getMessage());        }        return [];    }    /**     * @Route("/example2")     * @Template     */    public function example2(EntityManagerInterface $em){        $example = $em->getRepository(Example::class)->find(1);        if(!$example){            return new Response('No example found.');        }        $example->setValue(mt_rand(0, mt_getrandmax()));        try {            $em->flush();        } catch(\Exception $e){            return new Response('An error has occurred. '.$e->getMessage());        }        return [];    }    /**     * @Route("/example3")     * @Template     */    public function example3(Request $request, EntityManagerInterface $em){        $example = $em->getRepository(Example::class)->find(1);        if(!$example){            return new Response('No example found.');        }        $form = $this->createForm(ExampleType::class, $example);        $form->handleRequest($request);        if($form->isSubmitted() && $form->isValid()){            $em->flush();        }        return ['form' => $form->createView()];    }}

example1 and example2 routes DOES NOT cause issue, only example3 does and only when the form is submitted, so only when I enter example3 url, then click submit form only then when enter profiler for this request I can see the issue.

My minimal reproduction example was to create new symfony LTS project symfony new example-site --version=lts --full

Then these are files that I have changed since:

file changes

Databases are created by symfony console doctrine:database:create --connection=default and symfony console doctrine:database:create --connection=logs then tables are created by symfony console doctrine:migrations:diff --em=default and symfony console doctrine:migrations:migrate --em=default

Here is code for other files I haven't yet included in post:

<?php//src/Entity/Main/Example.phpnamespace App\Entity\Main;use Doctrine\ORM\Mapping as ORM;/** * @ORM\Entity */class Example {    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="string")     */    private $value;    public function getId(){        return $this->id;    }    public function getValue(){        return $this->value;    }    public function setValue(string $value){        $this->value = $value;    }}
<?php//src/Form/Type/ExampleType.phpnamespace App\Form\Type;use App\Entity\Main\Example;use Symfony\Component\Form\AbstractType;use Symfony\Component\Form\Extension\Core\Type\SubmitType;use Symfony\Component\Form\Extension\Core\Type\TextType;use Symfony\Component\Form\FormBuilderInterface;use Symfony\Component\OptionsResolver\OptionsResolver;class ExampleType extends AbstractType {    public function buildForm(FormBuilderInterface $builder, array $options){        $builder->add('value', TextType::class);        $builder->add('submit', SubmitType::class);    }    public function configureOptions(OptionsResolver $resolver){        $resolver->setDefaults(['data_class' => Example::class,        ]);    }}
<!-- template/s/example/example1.html.twig --><!doctype html><html lang="en"><head><meta charset="utf-8"><title>Example</title></head><body>    Example1</body></html>
<!-- template/s/example/example2.html.twig --><!doctype html><html lang="en"><head><meta charset="utf-8"><title>Example</title></head><body>    Example2</body></html>
<!-- template/s/example/example3.html.twig --><!doctype html><html lang="en"><head><meta charset="utf-8"><title>Example</title></head><body>{{ form(form) }}</body></html>

Last thing I want to add is that in other project this issue is more visible, because when entity has reference to other entity an error is reported (on non-owning side in One-to-Many self-referencing association):other example with an error reportedIn this case Item entity is the one feed trough form.For those who are curious here is Item.php:But I don't know how would it matter as it is not managed by logs entity manager and should not appear under. default entity manager who is managing the entity is not reporting any issues with it.

<?phpnamespace App\Entity;use Doctrine\ORM\Mapping as ORM;use Symfony\Component\HttpFoundation\File\UploadedFile;use Symfony\Component\Validator\Constraints as Assert;/** * @ORM\Entity(repositoryClass="App\Repository\ItemRepository") * @ORM\Table(indexes={ *          @ORM\Index(name="item_image", columns={"image"}) *     }) */class Item {    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="string", length=32)     * @Assert\NotBlank()     * @Assert\Length(min=3, max=32)     */    private $name;    /**     * @ORM\Column(type="string")     */    private $description = '';    /**     * @ORM\Column(type="string", length=25, nullable=true)     */    private $image;    /**     * @ORM\OneToMany(targetEntity="App\Entity\Item", mappedBy="container")     */    private $items;    /**     * @ORM\ManyToOne(targetEntity="App\Entity\Item", inversedBy="items")     * @ORM\JoinColumn(name="container", referencedColumnName="id")     * @var $container Item     */    private $container;    /**     * @ORM\OneToMany(targetEntity="App\Entity\TagItem", mappedBy="item")     * @var $tags TagItem[]     */    private $tags;    /**     * @Assert\Image(mimeTypes="image/jpeg")     * @var $imageFile null|UploadedFile     */    private $imageFile;    public function __construct() {        $this->items = new \Doctrine\Common\Collections\ArrayCollection();        $this->tags = new \Doctrine\Common\Collections\ArrayCollection();    }    public function getId(){        return $this->id;    }    public function getName(){        return $this->name;    }    public function setName(string $name){        $this->name = $name;    }    public function getDescription(){        return $this->description;    }    public function setDescription($description){        $this->description = $description;    }    public function hasImage(){        return isset($this->image);    }    public function getImage(){        return $this->image;    }    public function setImage($image){        $this->image = $image;    }    public function hasImageFile(){        return isset($this->imageFile);    }    public function getImageFile(){        return $this->imageFile;    }    public function setImageFile($imageFile){        $this->imageFile = $imageFile;    }    public function getItems(){        return $this->items;    }    public function hasContainer(){        return isset($this->container);    }    public function getContainer(){        return $this->container;    }    public function setContainer(?Item $container){        return $this->container = $container;    }    public function getTags(){        return $this->tags;    }    public function setTags($tags){        $this->tags = $tags;    }}

PHP version is 7.3.12 and hosted with symfony serve

Escaping is not applied in included template using Twig Bundle & Symfony 4.2

$
0
0

I am working on a Symfony 4.2.12 project with Twig bundle installed. Twig escaping strategy is the default 'html' one: I did not change anything about that.

I realized escaping filters |e('html'), |e('html_attr') ... are not applied in a Twig included template whereas in parent template it works normally. Perhaps i have missed something like 'context' as concerns escaping, but this creates a big issue like unwanted xss vulnerability.

Maybe this comes from a loop which calls the included template for each iteration... and escaped variables are not kept in memory, or a kind of that!

Not tested (maybe useless): i'm not sure dynamic variable names for each include could be a way to resolve the issue...

First, i observe html autoescape is not directly functional: a double escaping is also necessary on data.

For instance, to make filters work in included template i have to declare them as follows by escaping twice: |e|e('html_attr'), etc...

Included template

<!-- Strangely default filter does not work in included template, i have also to use it by escaping twice! -->{{ myVar1|e|e('html') }} <!-- This is not 'html' escaped as it should be! -->{{ myVar1 }} <!-- Please note the necessary double escaping!? --><img src="..." alt="{{ myVar2|e|e('html_attr') }}">

Parent template loop

...<!-- This is correctly 'html' escaped as expected! -->{{ myVar }}<!-- This is correctly 'html_attr' escaped as expected! --><a href="{{ myVar|e('html_attr') }}" ...></a>{% for object in parentObject.objects %}    ....{# Obviously, here, any of these passed vars are also correctly escaped with all filters! #}    {% include 'my_include.html.twig' with {'myVar1': myValue1,'myVar2': myValue2,'myVar3': myValue3|e('html_attr'),        ...    } only %}    ....{% endfor %}....

I wonder if this is a well known issue, bug (for this Twig bundle version) or a simple personal misunderstanding...

Thank you for your feedbacks!

Symfony 4 EntityType database not updated

$
0
0

I have an issue with EntityType form field.

Entity "Freelancer" is in relation ManyToMany with entity "Sapsubdomain".In Form on FreelancerType I added "sapsubdomains" as EntityType.

When I save my form all fields are saved correctly to database exepting "sapsubdomains".

I expect to have relation table between "Freelancer" and "Sapsubdomain" updated but nothing happen. I have no error message ...

Thanks for your help !

"Freelancer" Entity:

<?phpnamespace App\Entity;/** * @ORM\Entity(repositoryClass="App\Repository\FreelancerRepository") */class Freelancer{    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="text", nullable=true)     */    private $about;    /**     * @ORM\OneToOne(targetEntity="App\Entity\User", cascade={"persist", "remove"})     */    private $Userid;    /**     * @ORM\ManyToMany(targetEntity="App\Entity\Sapsubdomain", mappedBy="freelancer")     */    private $sapsubdomains;    public function __construct()  {    $this->sapsubdomains = new ArrayCollection();  }    /**     * @return Collection|Sapsubdomain[]     */    public function getSapsubdomains(): Collection    {        return $this->sapsubdomains;    }    public function addSapsubdomain(Sapsubdomain $sapsubdomain): self    {        if (!$this->sapsubdomains->contains($sapsubdomain)) {            $this->sapsubdomains[] = $sapsubdomain;            $sapsubdomain->addFreelancer($this);        }        return $this;    }    public function removeSapsubdomain(Sapsubdomain $sapsubdomain): self    {        if ($this->sapsubdomains->contains($sapsubdomain)) {            $this->sapsubdomains->removeElement($sapsubdomain);            $sapsubdomain->removeFreelancer($this);        }        return $this;    }}

"Sapsubdomain" Entity:

<?phpnamespace App\Entity;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Doctrine\ORM\Mapping as ORM;/** * @ORM\Entity(repositoryClass="App\Repository\SapsubdomainRepository") */class Sapsubdomain{    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="string", length=255, nullable=true)     */    private $subdomain;    /**     * @ORM\ManyToOne(targetEntity="App\Entity\Sapdomain", inversedBy="sapsubdomains")     * @ORM\JoinColumn(nullable=false)     */    private $domain;    /**     * @ORM\ManyToMany(targetEntity="App\Entity\freelancer", inversedBy="sapsubdomains")     */    private $freelancer;    public function __construct()    {        $this->freelancer = new ArrayCollection();    }    public function getId(): ?int    {        return $this->id;    }    public function getSubdomain(): ?string    {        return $this->subdomain;    }    public function setSubdomain(?string $subdomain): self    {        $this->subdomain = $subdomain;        return $this;    }    public function getDomain(): ?sapdomain    {        return $this->domain;    }    public function setDomain(?sapdomain $domain): self    {        $this->domain = $domain;        return $this;    }    /**     * @return Collection|freelancer[]     */    public function getFreelancer(): Collection    {        return $this->freelancer;    }    public function addFreelancer(freelancer $freelancer): self    {        if (!$this->freelancer->contains($freelancer)) {            $this->freelancer[] = $freelancer;        }        return $this;    }    public function removeFreelancer(freelancer $freelancer): self    {        if ($this->freelancer->contains($freelancer)) {            $this->freelancer->removeElement($freelancer);        }        return $this;    }}

Form FreelancerType:

<?phpnamespace App\Form;use Doctrine\ORM\EntityRepository;use Symfony\Bridge\Doctrine\Form\Type\EntityType;class FreelancerType extends AbstractType{    public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder            ->add('sapsubdomains', EntityType::class, array('class' => Sapsubdomain::class,'choice_label' => 'subdomain','required' => false,'multiple' => true,                 ))

FreelancerController:

<?phpnamespace App\Controller;/*** @Route("/freelancer", name="freelancer")* @Security("is_granted('ROLE_FREELANCER')")*/class FreelancerController extends AbstractController{    /**    * @Route("/settings/", name="freelancer_settings")    */    public function modifyfreelancesettings(Request $request, FileUploader $fileUploader)    {        //On récupére l'utilisateur        $user = $this->getUser();        //On recherche le profil freelance du user        $freelancer = $this->getDoctrine()        ->getRepository(Freelancer::class)        ->findOneBy(array('Userid'=>$user));        // Si le profil freelance n'existe pas pour le user on appel la fonction de création du profil        if (!$freelancer) {            $this->createfreelancesettings($request);        }        //Sinon on met à jour le profil du freelance        $form = $this->createForm(FreelancerType::class, $freelancer);        $form->handleRequest($request);        //On des données du freelance pour éventuellement les envoyer à TWIG        $tjm = $form->get('dailyrate')->getData();        $curr = $form->get('ratecurrency')->getData();        // On vérifie que le formulaire est soumis        if ($form->isSubmitted() && $form->isValid()) {            $freelancer->setUpdateDate(new \DateTime('now'));            /** @var UploadedFile $pictureFile */            $pictureFile  = $form['picture']->getData();                if ($pictureFile ) {                    $pictureFileName  = $fileUploader->upload($pictureFile);                    $freelancer->setProfilePicture($pictureFileName);                }            //Mise à jour des relations            $sapsubdomains  = $form['sapsubdomains']->getData();                $em = $this->getDoctrine()->getManager();            $em -> flush();            $this->addFlash('notice','Your SAP Profile has been saved !'                        );                            return $this->redirect($request->getUri());        }        return $this->render('freelancer/settings.html.twig', array('picture' => $freelancer,'curr' => $curr,'freelancer'=> $form->createView(),        ));    }

In the template for this field I have only:

{{ form_widget(freelancer.sapsubdomains) }}

symfony4 / sylius: site not deploying correctly in production

$
0
0

I've developed a sylius based site on a local server. I want to deploy it in production on my OVH server.

In the Sylius Sylius Cookbook, I did not find any particular procedure. So I followed the normal procedure.

  • Upload my code to the production server with a "git clone" of my git repository

  • Install my vendor dependencies "php composer install"But this step does not work because it never ends. At the end, I always have something like this:

Executing script cache:clear [Symfony\Component\Process\Exception\ProcessTimedOutException]  The process "'/usr/local/php7.3/bin/php''--php-ini=/usr/local/php7.3/etc/php.ini''./bin/console' --ansi cache:clear" exceeded the timeout of 20000 seconds.

I even tried "composer clearcache" before. It hasn't changed anything.

I am now trying "COMPOSER_PROCESS_TIMEOUT = 50,000". The "composer install" was sent 12 hours ago and is still not finished ...

If I copy my vendor directory from the local to the vendor directory on the server. Could that be a solution?Has anyone ever had this problem or know how to find a solution?Is there a special step to do when working with sylius?Because I really don't know what to do.

How to auto fetch data and save into db from other api in api-platform

$
0
0

I'm beginner php, but in my project require fetch data from jira api. I'm using api-platform and I want to systeme can auto fetch and auto save data from jira api into entiy after a specified period of time. I hope everyone can help me. My entity is here:

/** * @ApiResource() * @ORM\Entity(repositoryClass="App\Repository\JiraRepository") */class Jira{    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="string", length=255)     */    private $key;    /**     * @ORM\Column(type="string", length=255)     */    private $name;    /**     * @ORM\Column(type="string", length=255)     */    private $projectTypeKey;    /**     * @ORM\Column(type="string", length=255)     */    private $avartarUrl;

I want to auto save into that. How to create an automatic action in symfony? Help me. Thank you very much

Doctrine 3 Way Mapping

$
0
0

I need some help getting my head around a 3 way mapping.

I have an entity Student and an entity Parent, obviously one parent can have many students and vice versa, but i need additional information between each parent and student that will be different for each one.

Perhaps we have the following data:

Student A - Parent A (no responsibility) , Parent B (has responsibility) - even though one parent holds legal responsibility and the other doesn't, they are both still parents of the same student.

Student B - Parent A (has responsibility), Parent B (has responsibility) - in this case another student has the same parents but this time they both have legal responsibility.

To start basic entities i would have:

class Student{    // normally would have a ManyToMany here to link parents, but i need the 3rd entity    // to hold whether this student's parent has legal responsibility or not}class Parent{    // normally again would have ManyToMany here to link students to the parent}class ParentStudent{    /**    * @var boolean    * @ORM\Column(type="boolean", options={"default":true})    */    private $responsibility = true;    // it's this part where i link student to parent and vice versa that's becoming confusing}

Redirect http to https in .htaccess (Symfony 4)

$
0
0

I'm trying to host my symfony 4 website in a shared hosting (Cpanel), and i want to redirect http to https automatically.

I found on many questions here is that i should change mu .htaccess, here is my current .htaccess content :

DirectoryIndex index.phpAddType application/x-lsphp72 .php<IfModule mime_module>  AddType application/x-httpd-ea-php72 .php .php7 .phtml</IfModule><IfModule mod_rewrite.c>    Options -MultiViews    RewriteEngine On    RewriteCond %{REQUEST_FILENAME} !-f    RewriteRule ^ %{ENV:BASE}/index.php [L]</IfModule><IfModule !mod_rewrite.c><IfModule mod_alias.c>        RedirectMatch 302 ^/$ /index.php/</IfModule></IfModule><IfModule php7_module>   php_flag display_errors On   php_value max_execution_time 30   php_value max_input_time 60   php_value max_input_vars 1000   php_value memory_limit 128M   php_value post_max_size 8M   php_value session.gc_maxlifetime 1440   php_value session.save_path "/var/cpanel/php/sessions/ea-php72"   php_value upload_max_filesize 10M   php_flag zlib.output_compression Off</IfModule><IfModule lsapi_module>   php_flag display_errors On   php_value max_execution_time 30   php_value max_input_time 60   php_value max_input_vars 1000   php_value memory_limit 128M   php_value post_max_size 8M   php_value session.gc_maxlifetime 1440   php_value session.save_path "/var/cpanel/php/sessions/ea-php72"   php_value upload_max_filesize 10M   php_flag zlib.output_compression Off</IfModule><IfModule mime_module>  AddHandler application/x-httpd-ea-php72 .php .php7 .phtml</IfModule>

I found on this question Redirect HTTP to HTTPS that i should add :

RewriteCond %{SERVER_PORT} 80RewriteRule ^(.*)$ https://website.com/$1 [R=301,L]

but i got ERR_TOO_MANY_REDIRECT error.

Any of you guys got the same thing as me ?

Thanks for helping.

Symfony Form value not Flush with Selectpicker class

$
0
0

In Symfony 4 form I have a form field declared with EntityType:

public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder            ->add('tags', EntityType::class, array('class' => Saptag::class,'choice_label' => 'descr','required' => false,'multiple' => true,                //'attr' => ['class' => 'selectpicker'],                 ))

When form is submited my database is well updated. If I activate class 'selectpicker' then my field has the rendering I need in the template but field value do not update database when this class is used. No error occurs...

Any idea of how to handle that ?

doctrine:database:import Syntax error while mysql works fine

$
0
0

I'm trying to sync my local mysql database with the server by dumping with mysqldump and then importing with doctrine:database:import from Symfony console. It works fine local -> server, but when trying server -> local I'm getting the following error:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that     corresponds to your MySQL server version for the right syntax to use near 'SET @OLD_CHARACTER_SET_RESULTS=@@CHARAC    TER_SET_RESULTS */;                                                                                                    /*!40101 SET @OLD_COL' at line 8

It also works fine if I import the same file by just using mysql or Sequel Pro. What's the problem with Doctrine?

Local setup (MAMP):

  • mysql Ver 14.14 Distrib 5.7.26, for osx10.10 (x86_64) using EditLine wrapper
  • PHP 7.2.22
  • Symfony 4.4.7

Server:

  • mysql Ver 14.14 Distrib 5.7.28, for Linux (x86_64) using EditLine wrapper

Both connections are defined in Symfony:

doctrine:    dbal:        default_connection: default        connections:            default:                driver: pdo_mysql                url: '%env(DATABASE_URL)%'                charset: utf8mb4                default_table_options:                    charset: utf8mb4                    collate: utf8mb4_unicode_ci                    engine: InnoDB                    row_format: DYNAMIC                options:                    1013: false            remote:                url: '%env(DATABASE_REMOTE_URL)%'                driver: pdo_mysql                charset: utf8mb4                default_table_options:                    charset: utf8mb4                    collate: utf8mb4_unicode_ci                    engine: InnoDB                    row_format: DYNAMIC

This is what the head of the SQL dump file looks like:

-- MySQL dump 10.13  Distrib 5.7.26, for osx10.10 (x86_64)---- Host: host.some-server.com    Database: some-database-name-- -------------------------------------------------------- Server version   5.7.28-nmm1-log/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;/*!40101 SET NAMES utf8 */;/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;/*!40103 SET TIME_ZONE='+00:00' */;/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

Doctrine QueryBuilder leftJoin + MEMBER OF fails to work

$
0
0

This piece of code failse to produce the correct results:

$queryBuilder            ->leftJoin(sprintf('%s.building', $rootAlias), 'building')            ->andWhere(':user MEMBER OF building.owners OR :user MEMBER OF building.managers')            ->setParameter('user', $user);

whereas this returns a correct result:

$queryBuilder            ->leftJoin(sprintf('%s.building', $rootAlias), 'building')            ->andWhere('building.id = :id')            ->setParameter('id', 1);

$user is properly defined and member of building.managers.

Symfony - Api Platform : Edit object if statement on POST request

$
0
0

I use API platform with Symfony5, and I created a service to verify a statement if it is correct.

This statement if is correct, I want to change an existing object instead of adding on a POST request.

So, on POST request I created an event with PRE_WRITE events priorities, and this event calls a service who verifies if the statement is correct if is true, I edit an existing object.

All that work correctly without any problem, but the POST request is always for adding a new object, so, I get a new line on the database table.

Is there any solution, to return 200 responses on the edit object?

Viewing all 3925 articles
Browse latest View live


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