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

How to replace spaces (%20) by "-" in Symfony routes

$
0
0

I want to replace spaces (%20) by "-" in Symfony 4.4 routes and delete first capital letter of my {slug}.

E.g:

RecipeController.php

 /** * @Route("/receta/{title}", name="recipe_show", methods={"GET"}) */public function show(Recipe $recipe): Response{    return $this->render('recipe/show/show.html.twig', ['recipe' => $recipe,    ]);}

Now my route shows it.

https://localhost:8000/receta/Pollo%20agridulce%20chino

But I would like to show

https://localhost:8000/receta/pollo-agridulce-chino

In my BD I save "Pollo agridulce chino"

How can I do it?


There are no configured encoders for the "security" extension

$
0
0

When I launch this command

php bin/console security:encode-password

I am getting this error

There are no configured encoders for the "security" extension. 

Do anyone has an idea about this error, I am using Symfony 4In bundles.php I have security bundle activated

Symfony\Bundle\SecurityBundle\SecurityBundle::class => ['all' => true],

Do anyone has an idea? thanks in advance

symfony - getting logged out at form->handleRequest

$
0
0

I have a problem regarding my Symfony4 App.

What is happening?

I want to build a "Change Password" function for the currently logged in user. So far everything is fine imo. When I submit the form everything seems to have worked fine (redirect to correct page, page is displayed, .. ). But when I want to navigate to another page I get redirected to my login page due to no authentication. There I found out, that the password was not changed either.

I am very thankful for any kind of help!

EDIT

The log out is happening any time the form is submitted, regardles of errors or not.

Controller

/** * @Route("/user/change-password", name="_user_change_password", methods={"GET","POST"}) * @Template("admin/change_password.html.twig") */public function changePasswordAction(Request $request, UserPasswordEncoderInterface $encoder){    /**     * @var $user User     */    $user = $this->getUser();    $form = $this->createForm(ChangeOwnPasswordFormType::class, $user);    $form->handleRequest($request);    if ($form->isSubmitted() && $form->isValid()) {        $oldPassword = $form->get("oldPassword")->getData();        $checkPass = $encoder->isPasswordValid($user, $oldPassword);        if(!$checkPass) {            $this->addFlash("error", "user.wrong_old_password");            return array("form" => $form->createView()            );        }        $entityManager = $this->getDoctrine()->getManager();        $newPassword = $form->get("password")->getData();        $user->setPassword($encoder->encodePassword($user, $newPassword));        $user->setUpdatedAt(new \DateTime());        $entityManager->flush();        $this->addFlash("success", "user.password_changed");        return $this->redirectToRoute("_user_change_password");    }    return array("form" => $form->createView()    );}

Form Type

class ChangeOwnPasswordFormType extends AbstractType{    public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder            ->add('oldPassword', PasswordType::class, array('label' => 'user.old_password','mapped' => false,'attr' => array('autocomplete' => 'current-password',                ),            ))            ->add('password', RepeatedType::class, array('type' => PasswordType::class,'first_options' => array('constraints' => array(                        new NotBlank(['message' => 'password_reset.password.blank',                        ]),                        new Length(['min' => 6,'minMessage' => 'password_reset.password.short','max' => 4096,'maxMessage' => 'password_reset.password.short',                        ]),                    ),'label' => 'user.password'                ),'second_options' => array('label' => 'user.password_confirmation'),'invalid_message' => 'user.password_mismatch','options' => array('attr' => array('autocomplete' => 'new-password',                    ),                )            ))        ;    }    public function configureOptions(OptionsResolver $resolver)    {        $resolver->setDefaults(array('data_class' => User::class,'validation_groups' => array("Create")        ));    }}

Twig

{% extends "base.html.twig" %}{% block body %}<h1>{{ ("user.change_password.title")|trans }}</h1>    {{ form_start(form) }}    {{ form_widget(form) }}<button type="submit" class="btn btn-success">        {{ ("button.save")|trans }}</button>    {{ form_end(form) }}{% endblock %}

LANG variable isn't overriden in testing environment

$
0
0

I'm working on a Symfony 4.4 project. The project has been created from scratch (it's not an update from a 3.4 codebase or something like that). I'm adding automated tests to my codebase, but I'm having problems with environment variables.

In my .env, .env.local, .env.test and .env.test.local I have defined a LANG variable, to set the application language. To correctly test translations when I'm developing, in the dev environment (.env.local file) I've set LANG=es, and it's working correctly. In production it's also working correctly, but in test, in the .env.test.local file I've set LANG=ca but neither PHPUnit nor bin/console debug:container --env-vars --env=test show the correct value for this variable, it's value it's just es_ES.UTF-8, the value of the $LANG variable in my Ubuntu system.

I have other environment variables defined in the .env.test.local file, and these are correctly (like the DATABASE_URL). I've also tried to add the LANG in the phpunit.xml.dist file (<env name="LANG" value="ca" />), but it the value doesn't change, it's still es_ES.UTF-8.

I've also deleted the var/cache/test directory, but it still doesn't work.

What I'm doing wrong? What can I do to change the language in the testing environment?

Symfony 4.4 - Custom Error Templates Not Working

$
0
0

I've got an issue when it comes to using Custom Error Templates in Symfony 4.4 Flex. Everything has been set properly according to the guide from https://symfony.com/doc/4.4/controller/error_pages.html

I can access the Custom Error Templates via /_error/{errorCode} when I run the application with APP_ENV=dev - but if I change APP_ENV to prod (with APP_DEBUG set to false/0 of course), I get the default Symfony "500 Internal Server Error" page. I even tested it after deploying the application on the remote host, and it's the same issue when I try to access /random-unexisting-page (already got the error404.html.twig template set and it works on 'dev' via /_error/404).

I want to know, does it have anything to do with other configuration within /config/ ? Have you got any idea what the issue could be ?

There is no user provider for user App Entity User Shouldn't the supportsClass() method of your user provider return true for this classname?

$
0
0

I created an Email/Password Login form & have a great disappointing problem :(

First of all, This is what I got (I'm using Symfony 4.4.18):enter image description here

& these are my codes:

This is the User Entity (supportsClass() method added)App\Entity\User:

<?phpnamespace App\Entity;use App\Repository\UserRepository;use Doctrine\ORM\Mapping as ORM;use Symfony\Component\Validator\Constraints as Assert;use Symfony\Component\Security\Core\User\UserInterface;/** * @ORM\Entity(repositoryClass=UserRepository::class) */class User implements UserInterface, \Serializable{    /**     * @ORM\Id     * @ORM\GeneratedValue     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="string", length=255, unique=true)     */    private $first_name;    /**     * @ORM\Column(type="string", length=255)     */    private $last_name;    /**     * @ORM\Column(type="string", length=255, unique=true)     * @Assert\Regex(pattern="/^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/", message="Enter Valid Email")     */    private $email;    /**     * @ORM\Column(type="string", length=11)     */    private $phone_number;    /**     * @ORM\Column(type="string", length=255)     * @Assert\NotBlank(message="New password can not be blank.")     * @Assert\Regex(pattern="/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/", message="Minimum eight characters, at least one uppercase letter, one lowercase letter, one number and one special character")     */    private $password;    public function getId(): ?int    {        return $this->id;    }    public function getFirstName(): ?string    {        return $this->first_name;    }    public function setFirstName(string $first_name): self    {        $this->first_name = $first_name;        return $this;    }    public function getLastName(): ?string    {        return $this->last_name;    }    public function setLastName(string $last_name): self    {        $this->last_name = $last_name;        return $this;    }    public function getEmail(): ?string    {        return $this->email;    }    public function setEmail(string $email): self    {        $this->email = $email;        return $this;    }    public function getPhoneNumber(): ?string    {        return $this->phone_number;    }    public function setPhoneNumber(string $phone_number): self    {        $this->phone_number = $phone_number;        return $this;    }    public function getPassword(): ?string    {        return $this->password;    }    public function setPassword(string $password): self    {        $this->password = $password;        return $this;    }    public function getRoles(): array    {        return ['ROLE_USER'        ];    }    /**     * @inheritDoc     */    public function getSalt()    {        // TODO: Implement getSalt() method.    }    /**     * @inheritDoc     */    public function getUsername()    {        // TODO: Implement getUsername() method.    }    /**     * @inheritDoc     */    public function eraseCredentials()    {        // TODO: Implement eraseCredentials() method.    }    /**     * @inheritDoc     */    public function serialize()    {        return serialize([            $this->id,            $this->first_name,            $this->last_name,            $this->email,            $this->phone_number,            $this->password,        ]);    }    /**     * @inheritDoc     */    public function unserialize($serialized)    {        list(            $this->id,            $this->first_name,            $this->last_name,            $this->email,            $this->phone_number,            $this->password,            ) = unserialize($serialized, ['allowed_classes' => false]);    }    public function supportsClass($class)    {        return $class === User::class;    }}

The Login Form Authenticator App\Security\LoginFormAuthenticator(didn't use bin/console make:auth):

<?phpnamespace App\Security;use App\Entity\User;use Doctrine\ORM\EntityManagerInterface;use Symfony\Component\HttpFoundation\RedirectResponse;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\Routing\Generator\UrlGeneratorInterface;use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;use Symfony\Component\Security\Core\Security;use Symfony\Component\Security\Core\User\UserInterface;use Symfony\Component\Security\Core\User\UserProviderInterface;use Symfony\Component\Security\Csrf\CsrfToken;use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;use Symfony\Component\Security\Http\Util\TargetPathTrait;class LoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface{    use TargetPathTrait;    public const LOGIN_ROUTE = 'login';    private $entityManager;    private $urlGenerator;    private $csrfTokenManager;    private $passwordEncoder;    public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)    {        $this->entityManager = $entityManager;        $this->urlGenerator = $urlGenerator;        $this->csrfTokenManager = $csrfTokenManager;        $this->passwordEncoder = $passwordEncoder;    }    public function supports(Request $request)    {        return self::LOGIN_ROUTE === $request->attributes->get('_route')&& $request->isMethod('POST');    }    public function getCredentials(Request $request)    {        $credentials = ['email' => $request->request->get('email'),'password' =>$request->request->get('password'),'csrf_token' =>$request->request->get('_csrf_token'),        ];        $request->getSession()->set(            Security::LAST_USERNAME,            $credentials['email']        );        return $credentials;    }    public function getUser($credentials, UserProviderInterface $userProvider)    {        $token = new CsrfToken('authenticate', $credentials['csrf_token']);        if (!$this->csrfTokenManager->isTokenValid($token)) {            throw new InvalidCsrfTokenException();        }        $user = $this->entityManager->getRepository(User::class)->findOneBy(['email' => $credentials['email']]);        if (!$user) {            throw new CustomUserMessageAuthenticationException("Email Not Found!");        }        return $user;    }    public function checkCredentials($credentials, UserInterface $user)    {        return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);    }    public function getPassword($credentials): ?string    {        return $credentials['password'];    }    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)    {        if (!$targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {            return new RedirectResponse($targetPath);        }        return new RedirectResponse($this->urlGenerator->generate('dashboard'));    }    protected function getLoginUrl()    {        return $this->urlGenerator->generate(self::LOGIN_ROUTE);    }}

the Login Controller App\Controller\LoginController:

<?phpnamespace App\Controller;use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\Routing\Annotation\Route;use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;class LoginController extends AbstractController{    /**     * @Route("/login", name="login")     * @Method({"POST"})     * @param Request $request     * @param AuthenticationUtils $utils     * @return Response     */    public function login(Request $request, AuthenticationUtils $utils): Response    {        $error = $utils->getLastAuthenticationError();        $lastEmail = $utils->getLastUsername();        return $this->render('login/login.html.twig', ['error' => $error,'email' => $lastEmail,        ]);    }    /**     * @Route("/logout", name="logout")     */    public function logout()    {    }}

login.html.twig:

{% extends 'base.html.twig' %}{% block title %}LoginController!{% endblock %}{% block body %}<style>        .error {color: red;}</style><h1 class="page-title">Login</h1><div class="page-title">        {% if error %}<span class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</span>        {% endif %}        {% if app.user %}<div class="mb-3">                You are logged in as {{ app.user.firstName }}, <a href="{{ path('logout') }}">Logout</a></div>        {% endif %}<form method="post"><label for="email">Email: </label><input type="email" name="email" value="{{ email }}" placeholder="Email here ..."><label for="password">Password: </label><input type="password" name="password" placeholder="Password here ..."><input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}"><button type="submit">Login</button></form></div>{% endblock %}

security.yaml config:

security:    encoders:        App\Entity\User:            algorithm: bcrypt    providers:        user_provider:            entity:                class: APP\Entity\User                property: email    firewalls:        dev:            pattern: ^/(_(profiler|wdt)|css|images|js)/            security: false        main:            anonymous: true            provider: user_provider            guard:                authenticators:                    - App\Security\LoginFormAuthenticator            logout:                path: logout    access_control:        - { path: ^/login$, roles: IS_AUTHENTICATED_ANONYMOUSLY }        - { path: ^/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }        - { path: ^/, roles: ROLE_USER }        - { path: ^/admin, roles: ROLE_ADMIN }

I don't have any idea about supportsClass().& tried User Repository for custom user provider before but they didn't work

How to control Symfony's RepeatedType validation sequence

$
0
0

I am using Symfony's RepeatedType for an email address on a registration form.

$builder->add('email',    RepeatedType::class,    ['invalid_message' => 'Confirm your email address',    ]);

I am also adding constraints to the property declaration itself:

/** * @var string|null * * @Assert\NotBlank * @Assert\Email(message="You must enter a valid email address") */private ?string $email = null; 

The problem is that Symfony runs the RepeatedType validation before it runs the property specific ones.

In other words, if you enter an incorrect email address it will first ensure that you entered that incorrect email address twice before telling you it's wrong.

Same applies to my password by the way - it asserts that you re-entered it correctly before telling you password strength requirements weren't met.

I know that I can control the sequence of validation groups but since RepeatedType isn't applied to the model itself I am unsure how to achieve this.

Custom voter does not work as expected after migrating from Symfony 3.4 to Symfony 4.4

$
0
0

I'm migrating an app from Symfony 3.4 to Symfony 4.4. This app gives admin users the possibility to edit the role needed to access each route, so all the roles and routes are stored in the database.

To check if the user has access to a route, a voter is called on each request, and is configured in the services.yaml file.

In Symfony 3.4, the voter was called on each request, without adding any more code. In the web profiler, i can see the list of voters, and the decision from the AccessDecisionManager ("Granted" or "Denied").

Screenshot of the Web Profiler for Symfony 3.4

In Symfony 4.4 however, the voters don't seem to be called at all. In the web profiler, my custom voter is still in the list (two times ??), but there is no decision from the AccessDecisionManager.

Screenshot of the Web Profiler for Symfony 4.4

If I check user access directly from the controller by adding this line $this->denyAccessUnlessGranted("", $request);, the voters are called and work as expected.

If someone could explain to me why I have to call the denyAccessUnlessGranted() method manually in Symfony 4.4 when it was not needed in Symfony 3.4 ? Was I using voters the wrong way in 3.4 ?

Thank you.

My custom voter class :

namespace App\Security;use Doctrine\ORM\EntityManager;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\Security\Core\User\UserInterface;use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;class DynamicAccessVoter implements VoterInterface{    // Routes everyone has access to    const PUBLIC_ROUTES = ["login"    ];    // Routes everyone who's connected has access to    const PRIVATE_ROUTES = ["homepage","fos_js_routing","fos_js_routing_js"    ];    // Routes everyone has access to only in dev mode    const DEV_ROUTES = ["_wdt","_profiler","_profiler_home","_profiler_search","_profiler_search_bar","_profiler_phpinfo","_profiler_search_results","_profiler_open_file","_profiler_router","_profiler_exception","_profiler_exception_css","_twig_error_test"    ];    private $env;    /**     * Constructor     *      * @param string $env - App environment (dev or prod)     */    public function __construct(String $env = "") {        $this->env = $env;    }    /**     * Custom voter     *      * @param TokenInterface $token     * @param Request $subject     * @param array $env     */    public function vote($token, $subject, $attributes) {        // Verifie si $subject est une instance de Request        if(!$subject instanceof Request) {            return self::ACCESS_ABSTAIN;        }        $route = $subject->attributes->get("_route");        // Verifie si la route est une route publique (accessible par tout le monde)        if(in_array($route, DynamicAccessVoter::PUBLIC_ROUTES)) {            return self::ACCESS_GRANTED;        }        // Verifie si l'application est en développement et la route nécéssaire pour le debug        if($this->env == "dev" && in_array($route, DynamicAccessVoter::DEV_ROUTES)) {            return self::ACCESS_GRANTED;        }        // Verifie si $utilisateur est une instance de UserInterface        if(!$token->getUser() instanceof UserInterface) {            return self::ACCESS_ABSTAIN;        }        // Verifie si la route est une route accéssible par tout utilisateur connecté        if(in_array($route, DynamicAccessVoter::PRIVATE_ROUTES)) {            return self::ACCESS_GRANTED;        }        // Verifie si l'utilisateur connectéà le droit d'accéder à cette route        if($token->getUser()->hasAccessTo($route)) {            return self::ACCESS_GRANTED;        }        return self::ACCESS_DENIED;    }}

My custom voter configured as a service in the services.yaml file :

app.dynamic_access_voter:    class: App\Security\DynamicAccessVoter    arguments: ["%kernel.environment%"]    tags:        - { name: security.voter }

My security.yaml file, if that can help :

security:    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers    encoders:        App\Entity\Utilisateur:            algorithm: bcrypt    providers:        main:            entity:                class: App\Entity\Utilisateur                property: email          firewalls:        main:            anonymous: true            provider: main            pattern: ^/            form_login:                login_path: login                check_path: login                always_use_default_target_path: true                default_target_path: homepage            logout:                path: /logout                target: /login            user_checker: App\Security\EnabledUserChecker    access_control:        - { path: ^/ }

How to start local server with symfony 5 or downgrade version to 4.4?

$
0
0

I started a new project in new Symfony 5 and i can't open my local server.

On Symfony 4.4 the command PHP bin/console server:run is OK,

But with Symfony 5 the command appears not to be defined...

C:\Users\Chris\Code\api-test> php bin/console server:runCommand "server:run" is not defined.Do you want to run "server:dump" instead?  (yes/no) [no]:

So how to downgrade or start the local server?

symfony 4.4 + FOSCKEditor + helios-agElfinder not working

$
0
0

Using Symfony 4.4 +"friendsofsymfony/ckeditor-bundle": "^2.2" +"helios-ag/fm-elfinder-bundle": "dev-master" after composer install (but also tried composer require helios-ag/fm-elfinder-bundle from the docs page) gives me

Executing script cache:clear [KO] [KO]Script cache:clear returned with error code 1!!  !!  In RegisterControllerArgumentLocatorsPass.php line 173:!!                                                                                 !!    Cannot determine controller argument for "FM\ElfinderBundle\Controller\ElFi  !!    nderController::load()": the $eventDispatcher argument is type-hinted with   !!    the non-existent class or interface: "Psr\EventDispatcher\EventDispatcherIn  !!    terface".                                                                    !!                                                                                 !!  !!  Script @auto-scripts was called via post-install-cmd

route is imported, config files set...

BTW: include_assets is not recognized in fm_elfinder.yml (commented it out)

I have absolutly no idea. Can anyone of you guys give me a clue?

PS: worked fine with symfony 4.1

Symfony Validator: validate by comparing the old value from the DB

$
0
0

I'm working with Symfony 4.4,

For security reason, when submitting OrderProduct entity that embedd Product entity, I have to control some values of OrderProduct taken from Product.

So, it's an Symfony API, I receive an orderProduct in a JSON format:

{"product" : { "id" : 82 },"price" : 9.7,"quantity": 3,   //...}

I have to get the product from the database, to test if the price is correct.

Redirect to "/" route in symfony

$
0
0

I'm trying to redirect to the "/" route (same page) after a form submission:

/** * @Route("/") */

My approach:

return $this->redirectToRoute('/');

Gives me the following error:

Unable to generate a URL for the named route "/" as such route does not exist.

Where is correct place to authenticate users from multiple places?

$
0
0

In my first Symfony 4.4 project, I need to authenticate users from database. Unfortunately, before user sign-in I need to check user status in remote API service. If user is active in this service and credentials are same as in my database, I can authenticate user in my app.

Where is best place to check that user is active before authentication in my app? I need to create custom guard? Custom user provider?

I use Lexik JWT authentication, there is my /config/packages/security.yaml

security:    providers:        app_user_provider:            entity:                class: App\Entity\User                property: email    firewalls:        dev:            pattern: ^/(_(profiler|wdt)|css|images|js)/            security: false        authorization:            pattern:  ^/api/v1/auth/            stateless: true            anonymous: true            json_login:                check_path: /api/v1/auth/sign-in/                success_handler: lexik_jwt_authentication.handler.authentication_success                failure_handler: lexik_jwt_authentication.handler.authentication_failure                username_path: email        api:            pattern: ^/api/v1/(user|req)/            stateless: true            anonymous: false            provider: app_user_provider            guard:                authenticators:                    - lexik_jwt_authentication.jwt_token_authenticator

No mapping found for field xy on class xy

$
0
0

Specifications

Symfony > 4.4.2 (Not working)Symfony 4.4.1 (Working)

I got a problem with my Translations because on every action that includes translations, symfony is throwing a error like "no mapping field 'sprache_id' was found on class 'AnredeTranslation'"

This makes no sense for me, because the field is there and was working until I go to symfony 4.4 - What the heck did they change from 4.3 to 4.4 that this error is shown constantly? Every Entity with Translation is included in this problem, so my whole project is broken except this entities, which has no translations.

Btw - Anrede is the entity, which throws at $form->handleRequest other entities throw error on createForm.

Did someone get this problem too or are i'm alone with it?

UPDATE:

I can update to Symfony 4.4.1 - from Symfony 4.4.2 this error (no mapping for field sprache_id ...) will be thrown on create/mod entities with translations and i dont know why. Only the error confuses me, because form/request handler search for sprache_id field but the field is only sprache.

EXAMPLE

I'll publish here now an entity (shortest one) to show my definitions

Anrede Entity

<?phpnamespace App\Entity\Core\Kontakt;use App\Entity\Entity;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Doctrine\ORM\Mapping as ORM;use Symfony\Component\Validator\Constraints as Assert;/** * @ORM\Entity(repositoryClass="App\Repository\Core\Benutzer\AnredeRepository") */class Anrede extends Entity{    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="boolean")     */    private $aktiv;    /**     * @ORM\OneToMany(targetEntity="App\Entity\Core\Kontakt\AnredeTranslation", mappedBy="anrede", orphanRemoval=true, cascade={"persist","remove","merge"}, fetch="EAGER", indexBy="sprache_id")     * @ORM\OrderBy({"sprache" = "ASC"})     * @Assert\Valid()     */    private $translations;    /**     * @ORM\Column(type="boolean", options={"default":0})     */    private $standard;    public function __construct()    {        $this->translations = new ArrayCollection();    }    public function getId(): ?int    {        return $this->id;    }    public function getAktiv(): ?bool    {        return $this->aktiv;    }    public function setAktiv(bool $aktiv): self    {        $this->aktiv = $aktiv;        return $this;    }    /**     * @return Collection|AnredeTranslation[]     */    public function getTranslations(): Collection    {        return $this->translations;    }    public function addTranslation(AnredeTranslation $translation): self    {        if (!$this->translations->contains($translation)) {            $this->translations[] = $translation;            $translation->setAnrede($this);        }        return $this;    }    public function removeTranslation(AnredeTranslation $translation): self    {        if ($this->translations->contains($translation)) {            $this->translations->removeElement($translation);            // set the owning side to null (unless already changed)            if ($translation->getAnrede() === $this) {                $translation->setAnrede(null);            }        }        return $this;    }    public function getStandard(): ?bool    {        return $this->standard;    }    public function setStandard(bool $standard): self    {        $this->standard = $standard;        return $this;    }}

AnredeTranslation Entity

<?phpnamespace App\Entity\Core\Kontakt;use App\Entity\Core\Sprache\Sprache;use App\Entity\Entity;use Doctrine\ORM\Mapping as ORM;use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;use Symfony\Component\Validator\Constraints as Assert;/** * @ORM\Entity(repositoryClass="App\Repository\Core\Benutzer\AnredeTranslationRepository") * @UniqueEntity( *     fields={"sprache","anrede"}, *     errorPath="sprache", *     message="error.bereits_vorhanden" * ) */class AnredeTranslation extends Entity{    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\ManyToOne(targetEntity="App\Entity\Core\Kontakt\Anrede", inversedBy="translations")     * @ORM\JoinColumn(nullable=false)     */    private $anrede;    /**     * @ORM\ManyToOne(targetEntity="App\Entity\Core\Sprache\Sprache")     * @ORM\JoinColumn(nullable=false)     * @Assert\NotNull()     */    private $sprache;    /**     * @ORM\Column(type="string", length=255)     * @Assert\NotBlank()     */    private $name;    /**     * @ORM\Column(type="string", length=255, nullable=true)     */    private $anredetext;    public function getId(): ?int    {        return $this->id;    }    public function getAnrede(): ?Anrede    {        return $this->anrede;    }    public function setAnrede(?Anrede $anrede): self    {        $this->anrede = $anrede;        return $this;    }    public function getSprache(): ?Sprache    {        return $this->sprache;    }    public function setSprache(?Sprache $sprache): self    {        $this->sprache = $sprache;        return $this;    }    public function getName(): ?string    {        return $this->name;    }    public function setName(?string $name): self    {        $this->name = $name;        return $this;    }    public function getAnredetext(): ?string    {        return $this->anredetext;    }    public function setAnredetext(?string $anredetext): self    {        $this->anredetext = $anredetext;        return $this;    }}

AnredeType

<?phpnamespace App\Form\Core\Kontakte;use App\Entity\Core\Kontakt\Anrede;use App\Form\Type\SwitchType;use Symfony\Component\Form\AbstractType;use Symfony\Component\Form\Extension\Core\Type\CollectionType;use Symfony\Component\Form\FormBuilderInterface;use Symfony\Component\OptionsResolver\OptionsResolver;class AnredeType extends AbstractType{    public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder            ->add('aktiv', SwitchType::class, ['label' => 'aktiv.name','help'=> 'aktiv.help'            ])            ->add('standard', SwitchType::class, ['label' => 'standard.name','help'=> 'standard.help'            ])            ->add('translations', CollectionType::class, ['label' => 'sprachen.name','entry_type' => AnredeTranslationType::class,'error_bubbling' => true,'prototype' => true,'allow_add' => true,'allow_delete' => true,            ])        ;    }    public function configureOptions(OptionsResolver $resolver)    {        $resolver->setDefaults(['data_class' => Anrede::class,        ]);    }}

AnredeTranslationType

<?phpnamespace App\Form\Core\Kontakte;use App\Entity\Core\Kontakt\Anrede;use App\Entity\Core\Kontakt\AnredeTranslation;use App\Entity\Core\Navigation\Navigation;use App\Entity\Core\Navigation\NavigationTranslation;use App\Entity\Core\Sprache\Sprache;use App\Form\Transform\HiddenTransformer;use App\Form\Type\SprachenType;use App\Services\LocaleService;use Doctrine\ORM\EntityManagerInterface;use Doctrine\ORM\EntityRepository;use Symfony\Bridge\Doctrine\Form\Type\EntityType;use Symfony\Component\Form\AbstractType;use Symfony\Component\Form\Extension\Core\Type\HiddenType;use Symfony\Component\Form\Extension\Core\Type\TextareaType;use Symfony\Component\Form\Extension\Core\Type\TextType;use Symfony\Component\Form\FormBuilderInterface;use Symfony\Component\Form\FormEvent;use Symfony\Component\Form\FormEvents;use Symfony\Component\OptionsResolver\OptionsResolver;use Symfony\Component\Translation\Translator;use Symfony\Component\Translation\TranslatorInterface;class AnredeTranslationType extends AbstractType{    /**     * @var EntityManagerInterface     */    private $manager;    /**     * @var Translator     */    private $translator;    /**     * @var LocaleService     */    private $localeService;    public function __construct(EntityManagerInterface $manager, TranslatorInterface $translator, LocaleService $localeService)    {        $this->manager = $manager;        $this->translator = $translator;        $this->localeService = $localeService;    }    private $options;    public function buildForm(FormBuilderInterface $builder, array $options)    {        $this->options = $options;        $builder            ->add('sprache', SprachenType::class, ['required' => true,            ])            ->add('name', TextType::class, ['required' => true,'label' => 'label.name','help' => 'help.name'            ])            ->add('anredetext', TextType::class, ['required' => false,'label' => 'anredetext.name','help' => 'anredetext.help',            ])            ->add('anrede', HiddenType::class)        ;        $builder->get('anrede')->addModelTransformer(new HiddenTransformer($this->manager, Anrede::class));    }    public function configureOptions(OptionsResolver $resolver)    {        $resolver->setDefaults(['data_class' => AnredeTranslation::class,        ]);    }}

Testing Symfony Bundle : doctrine.orm.entity not found

$
0
0

I'm creating a standalone Symfony 4.4 bundle and I need to test it !

I've created an AppKernelTest which extends Kernel and I registered all my bundles :

class ServicesBundleTestingKernel extends Kernel{    /**     * @inheritDoc     */    public function registerBundles()    {        return [            new FrameworkBundle(),            new MonologBundle(),            new DoctrineBundle(),            new DoctrineMigrationsBundle(),            new MyServicesBundle(), // My custom bundle        ];    }    /**     * @inheritDoc     */    public function registerContainerConfiguration(LoaderInterface $loader)    {    }}

In my bundle, I have a service which require the Doctrine Entity Manager, here is my service.xml (where I declare all services for my bundle)

<service id="ServicesBundle\Service\RequestHandler" class="ServicesBundle\Service\RequestHandler" public="false"><argument key="$logger" type="service" id="monolog.logger"/><argument key="$em" type="service" id="doctrine.orm.entity_manager"/></service><service id="services_request_handler" alias="ServicesBundle\Service\RequestHandler" public="true" />

My test class :

class DependencyTest extends WebTestCase{    //private $container;    public function testServiceWiring()    {        self::bootKernel();    }}

I've configured my .env.test to use my custom kernel class for the tests but when I launch the test, I got this error :

1) ServicesBundle\Tests\DependencyTest::testServiceWiringSymfony\Component\DependencyInjection\Exception\ServiceNotFoundException: The service "services_request_handler" has a dependency on a non-existent service "doctrine.orm.entity_manager".

For the tests bellow, I removed my Bundle from the registerBundle() method.

I try the command : php bin/console debug:container doctrine.orm.entity_manager and the output is : "No service found"

I also tried to see all doctrine services in my container when the app is launched and I have only two services :

  • [0] cache.adapter.doctrine

  • [1] Doctrine\Common\Annotations\Reader

I don't know why the Doctrine Bundle is not correctly registered.


return a custom status code in User Checker

$
0
0

I'm working with Symfony 4.4.I'm using JWT Authentication and I'm now creating a custom user checker:I want to return a custom response code and a custom message when user checker detect that user can not connect.

#security.yaml:

    client_login:        pattern:  ^/api/login        provider: client_entity        stateless: true        anonymous: true        json_login:            check_path: api_login            username_path: email            success_handler:          lexik_jwt_authentication.handler.authentication_success            failure_handler:          lexik_jwt_authentication.handler.authentication_failure        user_checker: App\Security\UserChecker    refresh:        pattern:  ^/api/token/refresh        stateless: true        anonymous: true    api:        pattern:   ^/api        stateless: true        anonymous: true        guard:            authenticators:                - App\Security\TokenAuthenticator            provider: chain_providers #this provider will be ignored when getting the User        user_checker: App\Security\UserChecker

#UserChecker:

class UserChecker implements UserCheckerInterface{    public function checkPreAuth(UserInterface $user)    {        return;    }    public function checkPostAuth(UserInterface $user)    {        if (!$user instanceof Client) {            return;        }        if (!$user->isActive()) {            throw new AuthenticationException('userNotActive');        }    }}

With this user checker the response when client is not active:

{"code": 401,"message": "An authentication exception occurred."}

I want just to customize code and message.

Testing form with 'contraints' in options of TimeType generate an UndefinedOptionsException

$
0
0

I made a form in Symfony 4.4 with a TimeType field defined like this :

$builder    ->add('planned_start', TimeType::class, ['widget' => 'single_text','empty_data' => '','constraints' => [            new NotBlank(['message' => 'worksheet.worker.planned_start.required_error'            ])        ]    ])

Functional tests of my controller work perfectly and return the defined error if no valid is given.

But,when I'm testing the form directly, I get the following exeception like I can't put any constraint on the TimeType field

Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException: An error has occurred resolving the options of the form "Symfony\Component\Form\Extension\Core\Type\TimeType": The option "constraints" does not exist. Defined options are: "action", "allow_file_upload", "attr", "attr_translation_parameters", "auto_initialize", "block_name", "block_prefix", "by_reference", "choice_translation_domain", "compound", "data", "data_class", "disabled", "empty_data", "error_bubbling", "help", "help_attr", "help_html", "help_translation_parameters", "hours", "html5", "inherit_data", "input", "input_format", "label", "label_attr", "label_format", "label_translation_parameters", "mapped", "method", "minutes", "model_timezone", "placeholder", "post_max_size_message", "property_path", "reference_date", "required", "row_attr", "seconds", "translation_domain", "trim", "upload_max_size_message", "view_timezone", "widget", "with_minutes", "with_seconds"./var/www/vendor/symfony/form/ResolvedFormType.php:99/var/www/vendor/symfony/form/FormFactory.php:76/var/www/vendor/symfony/form/FormBuilder.php:94/var/www/vendor/symfony/form/FormBuilder.php:244/var/www/vendor/symfony/form/FormBuilder.php:195/var/www/vendor/symfony/form/FormFactory.php:30/var/www/tests/Form/WorksheetWorkerFormTypeTest.php:39

Here is how I test the form :

<?phpnamespace App\Tests\Form\Type;use App\Form\Type\TestedType;use App\Form\WorksheetWorkerFormType;use Doctrine\Persistence\ObjectManager;use Symfony\Component\Form\PreloadedExtension;use Symfony\Component\Form\Test\TypeTestCase;// ...class WorksheetWorkerFormTypeTest extends TypeTestCase{    private $objectManager;    protected function setUp()    {        // mock any dependencies        $this->objectManager = $this->createMock(ObjectManager::class);        parent::setUp();    }    protected function getExtensions()    {        // create a type instance with the mocked dependencies        $type = new WorksheetWorkerFormType($this->objectManager);        return [            // register the type instances with the PreloadedExtension            new PreloadedExtension([$type], []),        ];    }    public function testMinimal()    {        $form = $this->factory->create(WorksheetWorkerFormType::class);        $form->submit(['planned_start' => '08:00','planned_end' => '16:00'        ]);        $this->assertTrue($form->isValid());    }}

Any Idea ?

Thanks

How to change input "id" in FormType.php Symfony 4

$
0
0

I have tried to change the attr "id" in a FormType.php file :

->add('content', TextareaType::class,(['label' => "Description détaillée",'attr' => ['placeholder' => "Donnez une description qui donne vraiment envoe de venir chez vous !",'id' => "test_id"     ]]))

I only want to change the "ID". How can I do?

How can I implement a dotrine entity event listener

$
0
0

I'm working with Symfony 4.4, at first I want to check my doctrine version I found:in composer:

doctrine/orm": "^2.4.5

in symfony.lock:

"doctrine/orm": {"version": "v2.7.0"},

which one I have to trust ?

So the main problem is that I'm trying to implement a doctrine entity listener but It didn't work for me:

App\Entity\Admin:

/** * @ORM\Entity(repositoryClass="App\Repository\AdminRepository") * * @ORM\EntityListeners({"AdminListener"}) */ class Admin implements UserInterface

services.yaml:

admin_listener:    class: App\EventListener\Doctrine\AdminListener    tags:        -            name: doctrine.orm.entity_listener            event: preRemove            entity: App\Entity\Admin            method: preRemove            connection: 'default'

App\EventListener\Doctrine\AdminListener:

namespace App\EventListener\Doctrine;use Doctrine\Persistence\Event\LifecycleEventArgs;class AdminListener{    public function preRemove(Admin $admin, LifecycleEventArgs $event)    {        dump($admin);        dd($event);    }}

#console:

>bin/console debug:event-dispatcher doctrine.orm.entity_listener#output:                                                                         [WARNING] The event "doctrine.orm.entity_listener" does not have any                registered listeners.    

Symfony 4 Form Builder EntityType Field "not a valid class" error

$
0
0

I am trying to add Select form field by using values in DB table. In the official documentation it is described as in the picture below:

enter image description here

I did implemented in the same way but I am getting Expection:

The "App\Entity\Definition" entity has a repositoryClass set to "App\Entity\DefinitionRepository", but this is not a valid class. Check your class naming. If this is meant to be a service id, make sure this service exists and is tagged with "doctrine.repository_service".

My FormType code:

namespace App\Form;use App\Entity\Company;use App\Entity\Definition;use Doctrine\ORM\EntityRepository;use Symfony\Bridge\Doctrine\Form\Type\EntityType;use Symfony\Component\Form\AbstractType;use Symfony\Component\Form\FormBuilderInterface;use Symfony\Component\OptionsResolver\OptionsResolver;class CompanyDetailType extends AbstractType{    public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder            ->add('name', null, ['label' => 'Company Name'])            ->add('type', EntityType::class, ['class' => Definition::class,'query_builder' => function (EntityRepository $er) {                    return $er->createQueryBuilder('d');                },'choice_label' => 'name','label' => 'Company Type'            ]);    }    public function configureOptions(OptionsResolver $resolver)    {        $resolver->setDefaults(['data_class' => Company::class,        ]);    }}

My DefinitionRepository:

namespace App\Repository;use App\Entity\Definition;use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;use Doctrine\Persistence\ManagerRegistry;class DefinitionRepository extends ServiceEntityRepository{}

the $type field of Company Entity:

/** * @var Definition * * @ORM\ManyToOne(targetEntity="App\Entity\Definition") */private $type;
Viewing all 3925 articles
Browse latest View live


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