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

Can't get the IriConverter from the container because it's not public

$
0
0

I trying to load the api_platform.iri_converter but get an error:

The \"api_platform.iri_converter\" service or alias has been removed or inlined when the container was compiled. You should either make it public, or stop using the container directly and use dependency injection instead.

This is the code:

declare(strict_types=1);

namespace App\Security\Authorization\Voter;

use Symfony\Component\DependencyInjection\ContainerInterface;

abstract class BaseVoter extends Voter
{
    public ContainerInterface $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }
}
declare(strict_types=1);

namespace App\Security\Authorization\Voter;

class VenueVoter extends BaseVoter
{
    protected function voteOnAttribute(): bool
    {
        /** @var User $tokenUser */
        $tokenUser = $token->getUser();

        if (self::VENUE_CREATE === $attribute) {
            $iri = $this->container->get('api_platform.iri_converter')->getItemFromIri($valueWithIri);
        }
    }
}

Symfony 4 Access Denied in logged in user submission form

$
0
0

I have a symfony 4 installation and I use the msgphp user bundle in order to authenticate the users. Despite the user logs in normally, when he tries to submit an entity form access denied error appears:

Access denied, the user is not fully authenticated; redirecting to authentication entry point.

I tried to modify the security yaml but I still get the same error. I would appreciate any help since I am novice in symfony.. I paste below my files:

security.yaml

 security:
        encoders:
            MsgPhp\User\Infrastructure\Security\UserIdentity: auto
        # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
        providers:
            msgphp_user: { id: MsgPhp\User\Infrastructure\Security\UserIdentityProvider }
        firewalls:
            dev:
                pattern: ^/(_(profiler|wdt)|css|images|js)/
                security: false
            main:
                anonymous: true
                provider: msgphp_user

                # 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 used
        access_control:
            # - { path: ^/admin, roles: ROLE_ADMIN }
            - { path: ^/profile, roles: ROLE_TRAVELER }

framework.yaml

framework:
    secret: '%env(APP_SECRET)%'
    csrf_protection: true
    #http_method_override: true

    # Enables session support. Note that the session will ONLY be started if you read or write from it.
    # Remove or comment this section to explicitly disable session support.
    session:
        handler_id: 'session.handler.native_file'
        save_path: '%kernel.project_dir%/var/sessions/%kernel.environment%'
        cookie_secure: auto
        cookie_samesite: lax

    #esi: true
    #fragments: true
    php_errors:
        log: true

How to handle routing with locale in Symfony 4.3 KernelTestCase?

$
0
0

I need to test (PHPUnit) a service in Symfony 4.3 application and that service depends on the framework. It uses Translator and Router and it also depends on User. This means I want to write a KernelTestCase with User (done). The problem is the Router fails because the Routes need _locale. How can I address the issue?

1) App\Tests\blahblah\MenuFactoryTest::testMenuItemsByRoles with data set "ROLE_ADMIN" (array('ROLE_ADMIN'), array(array('Menu Label 1', 'Menu Label 2')))
Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("_locale") to generate a URL for route "default_dashboard".

class MenuFactoryTest extends KernelTestCase
{
    use LogUserTrait; // my trait allowing to emulate a user with particular roles 

    /** @var MenuFactory */
    private $menuFactory;

    protected function setUp(): void
    {
        static::bootKernel();

        $this->menuFactory = static::$container->get(MenuFactory::class);

    }

    // ...

    /**
     * @param array $roles
     * @param array $menuLabels
     *
     * @dataProvider provideMenuItemsByRoles
     */
    public function testMenuItemsByRoles(array $roles, array $menuLabels): void
    {
        $this->logIn($roles);

        $this->assertMenuItemsHaveLabels(
            $menuLabels,
            $this->menuFactory->getMenuItems()
        );
    }

    // ...
}

class MenuFactory implements MenuFactoryInterface
{
    /** @var RouterInterface */
    private $router;

    /** @var AuthorizationCheckerInterface */
    private $securityChecker;

    /** @var TranslatorInterface */
    private $translator;

    public function __construct(
        RouterInterface $router,
        AuthorizationCheckerInterface $securityChecker,
        TranslatorInterface $translator
    ) {
        $this->router = $router;
        $this->securityChecker = $securityChecker;
        $this->translator = $translator;
    }

    public function getMenuItems(string $appMenuName = null): array
    {
        $menuItems = [];

        $dashboardMenu = new DefaultMenuItem(
            $this->translator->trans('menu.dashboard'),
            $this->router->generate('default_dashboard'),
            'fa fa-dashboard'
        );

        $menuItems[] = $dashboardMenu;

        // ...

        return $menuItems;
    }
}

how to avoid creating a slug that already exists as a Route "Symfony 4"

$
0
0

I have the entity Page identified by slug. Also I have the action to view a page in the Page controler :

class PageController extends AbstractController
{
   /**
    * @Route("/{slug}", name="fronend_page")
    */
   public function show(Page $page)
   {
       return $this->render("font_end/page/show.html.twig", [
           "page" => $page,
       ]);
   }
}

I am looking for good practice to validate the slug ( check if exist in routes) before save it in the database without use prefixes Example :

route exist : @route ("/blog")

check if blog exist before create slug : /{slug} = /blog

thanks

Symfony self-update failing

$
0
0

When I do symfony self-update I get the following error - how can I solve it?

Backup failed, rename D:\SERVER\Symfony\symfony.exe C:\Users\FairyWilbury\.symfo
ny\autoupdate\2019-07-19_14-57-14-79024bb-old: The system cannot move the file t
o a different disk drive.. Canceling upgrade.

UPD. I have just realized that the latest symfony version seems to be 4.3 with 4.4 due to release in November https://symfony.com/roadmap/4.4 Yet whenever I run symfony new --full %projectName% it suggests I should update to 4.6 (and then fails to update as described above). Screenshot of the command line: s What can this problem be?

Symfony 4: Remove methode is not working with js redirectory

$
0
0

when i use this code

<td class="d-flex justify-content-center" onclick="fct()"><a href="{{ path('admin_card_delete', {slug:restaurantData.slug,id:restaurant.id}) }}"><img src="{{ asset('images/products/cancel.png') }}"></a></td>
    </tbody>

i'm redirected on my deleting page and all things are going well, and the selected element is deleted without any issue.

But when i try this

<td class="d-flex justify-content-center" onclick="fct()"><img src="{{ asset('images/products/cancel.png') }}"></td>
<script>
    function fct(){
        if(confirm("are you sure to delete this item ?")===true)
        {
            document.location.href="{{ path('admin_card_delete', {slug:restaurantData.slug,id:restaurant.id}) }}"
        }}
</script>

The redirection also goes well but for some reason remove method is not working, here is the code of my deleting page.

$em->remove($toRemove);
$em->flush();
return $this->redirectToRoute('admin_restaurant_card',[
    'slug' => $slug,
    'id' => $id
]);

Warning: strpos() expects parameter 1 to be string, object given when calling doctrine's getRespository() method

$
0
0

Just passing the class name to getRepository() method

/**
 * @Rest\Route("/batches", name="isbn_list_batches", methods={"GET"})
 * @Rest\QueryParam(name="page", default=1, requirements="\d+")
 * @Rest\QueryParam(name="limit", default=10, requirements="\d+")
 *
 * @param ParamFetcher $fetcher
 * @return \Pagerfanta\Pagerfanta
 */
public function listAction(ParamFetcher $fetcher)
{
    return $this
        ->em->getRepository("App:Batch")
        ->createPaginator(
            (int)$fetcher->get('page'),
            (int)$fetcher->get('limit')
        );
}

It was working and now is throwing that error. I also tried using getRepository(Batch::class)

enter image description here

Execute bundle command line

$
0
0

I created a small symfony4 bundle to manage Mysql database backup.

I created a packagist folder to implement it easily.

after install, my package path is:

webDirectory\vendor\fpasquer\symfony-backup-bundle\BackupSymfonyBundle.php

I'm able to use every class from this bundle excepted commands.

This is one command:

<?php

namespace Fpasquer\BackupSymfony\Command;

use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class BackupExportCommand extends AbstractBackup
{
    protected static $defaultName = 'Fpasquer:BackupSymfony:extract';

    ...
}

When I run it :

php bin/console Fpasquer:BackupSymfony:extract

I get this exception:

There are no commands defined in the "Fpasquer:BackupSymfony" namespace.

I'm sure my bundle is installed correctly because in my app:controller I'm able to use DependencyInjection from this bundle

Do you have any idea what's wrong?


Doctrine: Exception in One-To-Many cascading: Integrity constraint violation 1451

$
0
0

I am trying to build a very basic CMS using Symfony and Doctrine. I have entities emulating my sites' structure like so:

Entity: Page

/**
 * @ORM\Entity(repositoryClass="App\Repository\ContentTree\PageRepository")
 */
class Page extends SortableBase
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * @ORM\OrderBy({"sort_order" = "ASC"})
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Website", inversedBy="pages", cascade={"all"}, fetch="EAGER")
     */
    private $website;

    /**
     * Owning side of relation
     * @ORM\OneToMany(targetEntity="Section", mappedBy="page", fetch="EAGER")
     */
    private $sections;


    public function __construct()
    {
    ...

Entity: Section

/**
 * @ORM\Entity(repositoryClass="App\Repository\ContentTree\SectionRepository")
 */
class Section extends SortableBase
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Page", inversedBy="sections", cascade={"all"}, fetch="EAGER")
     */
    private $page;

    /**
     * Owning side of relation
     * @ORM\OneToMany(targetEntity="Entry", mappedBy="section", fetch="EAGER")
     */
    private $entries;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\SectionTemplating\SectionType", fetch="EAGER")
     */
    private $sectionType;


    public function __construct()
    {

Entity: Entry

/**
 * @ORM\Entity(repositoryClass="App\Repository\ContentTree\EntryRepository")
 */
class Entry extends SortableBase
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="Section", inversedBy="entries", cascade={"all"}, fetch="EAGER")
     */
    private $section;

    /**
     * Owning side of relation
     * @ORM\OneToMany(targetEntity="App\Entity\ContentTypes\Content", mappedBy="entry", fetch="EAGER")
     */
    private $contents;


    public function __construct()
    {
    ...

So in the end a Page can have Sections which can have Entries and so forth. Now, from what I gathered from the docs I was under the assumption that with how I setup the cascades I could just go and use the EntityManager to remove an instance of any Entity (lets say Section) and it would automatically delete that instance as well as all contained Entries.

However, when I do something like:

$section = $this->getSectionByID($sectionid);

$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($section);
$entityManager->flush();

as soon as the Section has any Entries, I get:

An exception occurred while executing 'DELETE FROM section WHERE id = ?' with params [10]:

SQLSTATE[23000]: Integrity constraint violation: 
1451 Cannot delete or update a parent row: 
a foreign key constraint fails (`webdata`.`entry`, CONSTRAINT `FK_2B219D70D823E37A` 
FOREIGN KEY (`section_id`) REFERENCES `section` (`id`))

I know what it it means but I just cannot figure out what I should do different here in order to force the EntityManager to traverse down my entity graph and delete everything from bottom to top.

Symfony deprecated Role entity

$
0
0

I'm trying to migrate from Symfony 3.4 to Symfony 4.4 and I see there are changes.One of which is that they have made Role class to be deprecated.I've searched a bit and found that we could simply store those roles as JSON, but I don't like it.The following code does not work any more and I have to refactor it somehow.

public function findStudentsBySchoolAndRole(School $school, Role $role)
{
    $qb = $this->getEntityManager()->createQueryBuilder();
    $qb ->select(array('p'))
        ->from('AppBundle:User', 'p')
        ->join('p.school', 's', 'WITH', $qb->expr()->in('s.id', $school->getId()))
        ->join('p.roles', 'r', 'WITH', $qb->expr()->in('r.id', $role->getId()));
    $result = $qb->getQuery()->execute();

    return $result;
}

I'm thinking about deleting the Role entity and just store it using ArrayCollection.Would it be wrong? If I delete the Role entity I wouldn't be able to find specific users by given role

Call js function from external file Symfony Twig

$
0
0

I'm having issues calling functions from twig views in Symfony 4.4. This view is called UserList.html.view and it extends base.html.twig

The beginning of the file is as following :

{% extends 'base.html.twig' %}
{% block body %}
{% block javascripts %}
    <script src="{{ asset('build/js/custom.js') }}"></script>
...

I also tried with Encore by adding an entry but it's not working. The only way to access external functions is to call them from the parent view which is not what I want obviously.

The error I get :

Uncaught ReferenceError: coucou is not defined at HTMLButtonElement.onclick (VM3883 manageAccounts:183) onclick @ VM3883 manageAccounts:183

I read some other posts about this but none of them actually provided a working solution.

Thank you for your help !

Save dates in UTC

$
0
0

I'm currently trying to save my dates in database with de UTC timezone.

To get the user timezone, I have a JS function that makes an AJAX request to my back-end like this :

import $ from 'jquery';
import jstz from 'jstz';

export default function setSessionTimezone(route)
{
    var timezone = jstz.determine();
    $.ajax({
        type:'POST', async:true, cache:false, url:route, data:"timezone="+timezone.name(),
        success:function(data) { if (data.reloadPage) location.reload(); }
    });
}

This method is called only if the timezone is not already in session. So, for now, I have the user timezone in my back-end, that was the first step.

I want to save it in the database. With this SO post, I found something interesting : Symfony buildForm convert datetime to local and back to utc

They recommend to use the "model_timezone" and "view_timezone" for the forms, so did I :

use Symfony\Component\Form\AbstractTypeExtension;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TimeType;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class UtcTypeExtension extends AbstractTypeExtension
{
    /**
     * @var SessionInterface
     */
    private $session;

    public function __construct(SessionInterface $session)
    {
        $this->session = $session;
    }

    /**
     * Return the class of the type being extended.
     */
    public static function getExtendedTypes(): iterable
    {
        return [TimeType::class, DateType::class];
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        parent::configureOptions($resolver);

        $resolver->setDefaults([
            'model_timezone' => 'UTC',
            "view_timezone" => $this->session->get('tools_timezone')
        ]);
    }
}

And hooora, it works. But only within the forms.

If I want to display the dates with Twig or from PHP, I need to get the timezone from session and change the DateTime's Timezone.

So I searched another option. I found this on the Doctrine Website to change the timezone directly from Doctrine.

This sound interesting, but I'm probably missing a point because it doesn't seem to work, even after I added the following configuration :

doctrine:
    dbal:
        types:
            datetime: SomeNamespace\DoctrineExtensions\DBAL\Types\UTCDateTimeType

So I would like to know if what I want to do is even possible ? Or if I'm forced to override Twig "date" filter to use my timezone ? And if I want to display a date from PHP, I'm also force to use the timezone from the session?

PHP Symfony 4.4.5 Error: Could not load type "Doctrine\DBAL\Types\DateType": class does not implement "Symfony\Component\Form\FormTypeInterface"

$
0
0

I am trying to do a Symfony 4 tutorial and I am trying to create a form and it is saying that my class does not implement "Symfony\Component\Form\FormType" even though my class implements FormTypeInterface:

<?php

namespace App\Form;

use Doctrine\DBAL\Types\DateType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\FormTypeInterface;

class ContactType extends AbstractType implements FormTypeInterface{
    public function buildForm(FormBuilderInterface $builder, array $options){
        $builder
            ->add('name', TextareaType::class)
            ->add('email', EmailType::class)
            ->add('dateOfBirth', DateType::class)
            ->add('message', TextareaType::class)
            ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            // Configure your form options here
        ]);
    }
}

What do I need to do to make this work?

Symfony 4 EasyAdminBundle: Problem with encoding and saving of Plain Password

$
0
0

these are my first steps with Symfony. I try to implement a simple user management with Easyadmin Bundle in Symfony 4.4. I followed the Tutorial on symfony.com and most of it is working correctly (Sign up form, backend login, backend security, backend listing of users from database).

My Problem is the creation and updating of a user in the Easyadmin backend. When I try to create a new user, I see the correct fields, I do enter some data and if I click "Save changes" it throws the following error:

An exception occurred while executing 'INSERT INTO app_users (username, email, roles, password, is_active) VALUES (?, ?, ?, ?, ?)' with params ["testname", "test@example.com", "a:1:{i:0;s:9:\"ROLE_USER\";}", null, 1]:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'password' cannot be null

Column 'password' cannot be null is pretty clear: I need to provide it with some encoded password string.

I think the data in the plain password field I enter is not encoded and/or not processed by the setPassword() method in my User entity.

As far as I understand some SO answers and the Symfony documentation it should work automagically!? I don't know. I tried to create an AdminController that extends EasyAdminController and hook it in somewhere in the persisting of the user entity, but I couldn't get it to work. (Something like this: https://stackoverflow.com/a/54749433)

How do I process/encode the plainpassword that it is saved to the password field in database?


User entity:

// /src/Entity/User.php
namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;

/**
 * @ORM\Table(name="app_users")
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 * @UniqueEntity("username")
 * @UniqueEntity("email")
 */
class User implements AdvancedUserInterface, \Serializable
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=254, unique=true)
     * @Assert\NotBlank(groups={"edit"})
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=254, unique=true)
     * @Assert\NotBlank()
     * @Assert\Email(groups={"edit"})
     */
    private $email;

    /**
     * @ORM\Column(type="array")
     */
    private $roles;

    /**
     * @Assert\Length(max=4096)
     */
    private $plainPassword;

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

    /**
     * @ORM\Column(name="is_active", type="boolean")
     */
    private $isActive;

    public function __construct(){
        $this->roles = array('ROLE_USER');
        $this->isActive = true;
    }

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

    public function getUsername(){
        return $this->username;
    }

    public function setUsername($username){
        $this->username = $username;
    }

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

    public function setEmail($email){
        $this->email = $email;
    }

    public function getIsActive(){
        return $this->isActive;
    }

    public function setIsActive($is_active){
        $this->isActive = $is_active;
    }

    public function getRoles(){
        return $this->roles;
    }

    public function setRoles($roles){
        $roles[] = 'ROLE_USER';
        $this->roles = $roles;
    }

    public function getPlainPassword(){
        return $this->plainPassword;
    }

    public function setPlainPassword($password){
        $this->plainPassword = $password;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function setPassword($password){
        $this->password = $password;
    }

    public function getSalt(){
        return null;
    }

    public function eraseCredentials(){}

    public function isAccountNonExpired(){
        return true;
    }

    public function isAccountNonLocked(){
        return true;
    }

    public function isCredentialsNonExpired(){
        return true;
    }

    public function isEnabled(){
        return $this->isActive;
    }

    /** @see \Serializable::serialize() */
    public function serialize(){
        return serialize(array(
            $this->id,
            $this->username,
            $this->email,
            $this->password,
            $this->isActive,
        ));
    }

    /** @see \Serializable::unserialize() */
    public function unserialize($serialized){
        list (
            $this->id,
            $this->username,
            $this->email,
            $this->password,
            $this->isActive,
        ) = unserialize($serialized, array('allowed_classes' => false));
    }
}

Security.yaml:

# /config/packages/security.yaml
security:
    encoders:
        App\Entity\User:
            algorithm: bcrypt
    providers:
        users_in_memory: { memory: null }
        our_db_provider:
            entity:
                class: App\Entity\User
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: true
            pattern: ^/
            provider: our_db_provider
            form_login:
                login_path: login
                check_path: login
                default_target_path: account
                always_use_default_target_path: true
                csrf_token_generator: security.csrf.token_manager
            logout:
                path: /logout
                target: /login
    access_control:
        - { path: ^/admin, roles: ROLE_ADMIN }
        - { path: ^/account, roles: ROLE_USER }
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/, roles: IS_AUTHENTICATED_ANONYMOUSLY }

Easyadmin.yaml:

# /config/packages/easy_admin.yaml
easy_admin:
    design:
        menu:
            - { entity: User, label: 'Benutzerverwaltung', icon: 'user' }
    entities:
        User:
            class: App\Entity\User
            label: 'Benutzer'
            password_encoding: { algorithm: 'bcrypt', cost: 12 }
            form:
                form_options: { validation_groups: ['Default'] }
                fields:
                    - { type: 'group', icon: 'address-card', label: 'Informationen', css_class: 'col-lg-6' }
                    - username
                    - email
                    - { type: 'group', icon: 'user-shield', label: 'Rechteverwaltung', css_class: 'col-lg-6' }
                    - { property: 'is_active', type: 'checkbox' }
                    - { property: 'roles', type: 'choice', type_options: { multiple: true, choices: { 'ROLE_USER': 'ROLE_USER', 'ROLE_ADMIN': 'ROLE_ADMIN' } } }
                    - { type: 'group', icon: 'user-lock', label: 'Passwort', css_class: 'col-lg-6' }
                    - { property: 'plainPassword', type: 'text', type_options: { required: false } }

Restore the full-page error message with Symfony 4.4

$
0
0

Since I remove the now deprecated symfony/webserver, I started working with Symfony Local Web Server. Unfortunately, now Symfony just shows "Oops! An Error Occurred" on errors, while before I had very helpful full-page, complete error messages.

Where can I configure this behaviour and restore the old, full-page errors?


How to create Dependent dropdowns in Sonata Admin?

$
0
0

I have a form in Sonata and I want to create a dependent dropdown like:

EEUU

California, Texas, Florida

When you select a country, it should only show states from the selected country.

I'm using Symfony 4.2 with Sonata project.

FOS Rest bundle - Not able to use customized error controller

$
0
0

I have a project with Symfony 4.4 and FosRestBundle. I'm trying to customize the exception handling by changing the json output. In this particular case I have a controller that receives a query string language param and it validates it's correct (en_GB, it_IT, etc...). So when I pass an incorrect language code I want it to be handled by my own controller. The exception is thrown but is catched by it never goes to my custom controller, seems like its directly Symfony who does the output. My fos_rest.yaml:

fos_rest:
  param_fetcher_listener: force
  exception:
    enabled: true
    exception_controller: 'AppBundle\Action\ExceptionAction'

My action controller:

    /**
     * @Route(
     *     "/api/v1/categories/{id}",
     *     name="get_category",
     *     methods={"GET"},
     *     requirements={"id"="\d+"}
     * )
     *
     * @QueryParam(
     *     name="language",
     *     requirements=@Assert\LanguageCode,
     *     strict=false,
     *     description="Language code in ISO format, i.e. fr_FR"
     * )
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function __invoke(Request $request): JsonResponse
    {
        /**
     * @Route(
     *     "/api/v1/categories/{id}",
     *     name="get_category",
     *     methods={"GET"},
     *     requirements={"id"="\d+"}
     * )
     *
     * @QueryParam(
     *     name="language",
     *     requirements=@Assert\LanguageCode,
     *     strict=false,
     *     description="Language code in ISO format, i.e. fr_FR"
     * )
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function __invoke(Request $request): JsonResponse
    {

One thing that bothers me is I can write whatever I want in the exception_controller configuration option (like non-existent-controller) and the code doesn't fail witch makes me think that something is not plugged correctly. Any ideas why this is not working? Thanks a lot!

what is missing in my code (symfony 5) so that the image inserted in my form can be stored in the database? [closed]

$
0
0

I am a beginner in symfony, I wanted to make a form to insert and store files in the database, I created my form, and here is my controller, and the services.yaml in which there is the path to where store the files, I would like to know what is missing so that the files can be saved in the database.

My controller

<?php
    class ProductController extends AbstractController
{
    /**
     * @Route("/product/new", name="app_product_new")
     */
    public function new(Request $request)
    {
        $product = new Product();
        $form = $this->createForm(ProductType::class, $product);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var UploadedFile $brochureFile */
            $brochureFile = $form->get('brochure')->getData();

            // this condition is needed because the 'brochure' field is not required
            // so the PDF file must be processed only when a file is uploaded
            if ($brochureFile) {
                $originalFilename = pathinfo($brochureFile->getClientOriginalName(), PATHINFO_FILENAME);
                // this is needed to safely include the file name as part of the URL
                $safeFilename = transliterator_transliterate('Any-Latin; Latin-ASCII; [^A-Za-z0-9_] remove; Lower()', $originalFilename);
                $newFilename = $safeFilename.'-'.uniqid().'.'.$brochureFile->guessExtension();

                // Move the file to the directory where brochures are stored
                try {
                    $brochureFile->move(
                        $this->getParameter('brochures_directory'),
                        $newFilename
                    );
                } catch (FileException $e) {
                    // ... handle exception if something happens during file upload
                }

                // updates the 'brochureFilename' property to store the PDF file name
                // instead of its contents
                $product->setBrochureFilename($newFilename);
            }

            // ... persist the $product variable or any other work

            $this->entityManager->persist($product);
            $this->entityManager->flush();

            return $this->redirect($this->generateUrl('app_product_list'));
        }

        return $this->render('product/new.html.twig', [
            'form' => $form->createView(),
        ]);
    }
}
?>

My application keeps loading after trying to clear FilesystemCache

$
0
0

I have an application that runs on Symfony 4. I use the filesystem cache component. I wanted to create a function that empties it, but unfortunately, my entire application is now broken. All pages will continue to load forever.

enter image description here

Below the script that I have executed:

<?php

namespace App\Controller\Admin;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Cache\Simple\FilesystemCache;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;

use App\Entity\Instelling;

class AdminInstellingController extends AbstractController
{
    /**
     * @Route("/beheer/cache-clear")
     */
    public function clearCache()
    {
        $cache = new FilesystemCache();
        $cache->clear();

        $this->addFlash("success", "De <strong>CRM DataServer</strong> cache is succesvol geleegd.");
       // return $this->redirect('/beheer/dashboard');
    }
}

I have deleted my var/cache folder, my temp folder where this cache is stored by default (sys_get_temp_dir), reinstalled my vendors, emptied my cookies and cache and restarted my computer. Nothing works at all and the application keeps loading. What do I have to do to resolve this?

How to get the client IP using a Symfony 4 application hosted on Azure Web App

$
0
0

I want to log every login attempts on a Web App (Symfony 4.1) hosted on Azure.

Based on this question, to get the client IP, I'm using :

// $requestStack being Symfony\Component\HttpFoundation\RequestStack
$ip = $this->requestStack->getMasterRequest()->getClientIp();

However, the logs tell :

[2020-03-10 10:55:56] login_attempt.INFO: User 'username' successfully logged in from ip '172.16.1.1' [] []

As you can notice, this is a private IP. I tried to log in from differents connections, but I'm always getting that IP, 172.16.1.1. Where does this IP come from and how to get the real public IP of the client ?

Viewing all 3924 articles
Browse latest View live


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