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

Symfony 4.4 - Custom error pages not working when exception controller is enabled

$
0
0

When implementing fos_rest bundle with symfony, I cannot seem to have symfony's normal behavior when handling custom error pages on a 404, 405, 500 or any other error triggered by symfony.

It works fine for every error triggered with the rest bundle in a normal rest controller.

But on my landing page (and about us and so on), which is not using fos_rest bundle, but twig instead, the custom error pages don't work, instead, it seems to be handled by the fos_rest bundle anyway, and always sends a default error 500 (even if it should be triggering a 404 error).

If I deactivate exceptions in fos_rest.yaml file (enabled: false), then, the custom error pages works fine (configured following this documentation here: https://symfony.com/doc/4.4/controller/error_pages.html )

fos_rest:
    routing_loader:
        default_format: json
        include_format: false
    body_listener: true
    format_listener:
        rules:
            - { path: '^/myROUTE1', priorities: ['json'], fallback_format: json, prefer_extension: false }
            - { path: '^/myROUTE2', priorities: ['json'], fallback_format: json, prefer_extension: false }
            - { path: '^/myROUTE3', priorities: ['json'], fallback_format: json, prefer_extension: false }
            - { path: '^/myROUTE4', priorities: ['json'], fallback_format: json, prefer_extension: false }
            - { path: '^/', priorities: ['html', 'json'], fallback_format: 'html' }
    param_fetcher_listener: true
    access_denied_listener:
        json: true
    view:
        view_response_listener: 'force'
        formats:
            json: true
    exception:
        enabled: true
        exception_controller: 'fos_rest.exception.controller:showAction'
        codes:
            Doctrine\ORM\EntityNotFoundException: 404
            \LogicException: 400
            \DomainException: 400
        messages:
            Doctrine\ORM\EntityNotFoundException: true
            \LogicException: true
            \DomainException: true

How do I set up fos_rest bundle to only handle exceptions for the routes handled by my rest controllers, and leave the normal symfony 4 behavior for the rest of the site?

Thank you for your help.


How do I handle special chars in the credentials of the Symfony Mailer component in SMTP transport?

$
0
0

Context

In Symfony 4.3 a new emailer was introduced.

See here:

For the SMTP transport it is established that the DSN in the ENV var has this format:

MAILER_DSN=smtp://user:pass@smtp.example.com

Question

How do I handle special characters in the user and password when writing the DSN?

Let's suppose that the credentials are:

username: alice@example.com
password: the:password:is:difficult

Setting like this most likely will fail:

MAILER_DSN=smtp://alice@example.com:the:password:is:difficult@smtp.example.com

How should I encode/escape things? What would be a correct DSN for it?

Custom error pages not working when exception controller is enabled

$
0
0

When implementing fos_rest bundle with symfony, I cannot seem to have Symfony's normal behavior when handling custom error pages on a 404, 405, 500 or any other error triggered by Symfony.

It works fine for every error triggered with the rest bundle in a normal rest controller.

But on my landing page (and about us and so on), which is not using fos_rest bundle, but twig instead, the custom error pages don't work, instead, it seems to be handled by the fos_rest bundle anyway, and always sends a default error 500 (even if it should be triggering a 404 error).

If I deactivate exceptions in fos_rest.yaml file (enabled: false), then, the custom error pages works fine (configured following this documentation here: https://symfony.com/doc/4.4/controller/error_pages.html )

fos_rest:
    routing_loader:
        default_format: json
        include_format: false
    body_listener: true
    format_listener:
        rules:
            - { path: '^/myROUTE1', priorities: ['json'], fallback_format: json, prefer_extension: false }
            - { path: '^/myROUTE2', priorities: ['json'], fallback_format: json, prefer_extension: false }
            - { path: '^/myROUTE3', priorities: ['json'], fallback_format: json, prefer_extension: false }
            - { path: '^/myROUTE4', priorities: ['json'], fallback_format: json, prefer_extension: false }
            - { path: '^/', priorities: ['html', 'json'], fallback_format: 'html' }
    param_fetcher_listener: true
    access_denied_listener:
        json: true
    view:
        view_response_listener: 'force'
        formats:
            json: true
    exception:
        enabled: true
        exception_controller: 'fos_rest.exception.controller:showAction'
        codes:
            Doctrine\ORM\EntityNotFoundException: 404
            \LogicException: 400
            \DomainException: 400
        messages:
            Doctrine\ORM\EntityNotFoundException: true
            \LogicException: true
            \DomainException: true

How do I set up fos_rest bundle to only handle exceptions for the routes handled by my rest controllers, and leave the normal Symfony 4 behavior for the rest of the site?

How to add placeholder on input in Symfony 4 form?

$
0
0

In my Symfony 4 form, I am try to get a placeholder for my input. I tried the below but I get an error that it is not allowed. Any ideas how else I can achieve this?

        ->add('firstname', TextType::class, ['label' => 'Vorname ', 'placeholder' => 'Your name',])

As suggested in the documentation I have also tried the below, here I am not getting an error, just nothing is rendering.

        ->add('firstname', TextType::class, ['label' => 'Vorname '], ['attr' => ['placeholder' => 'Vorname ']])

hello please can someone help me configure webpack? I'm on symfony 4 projects

$
0
0

Hello please I just installed Babel via the command "npm install --save @ babel / preset-env", Once installed, I created a ".babelrc" file at the root and put the following config: {"presets": ["@ babel / preset-env"]} despite that I get the error below

WARNING The "callback" argument of configureBabel() will not be used because your app already provides an external Babel configuration (a ".babelrc" file, ".babelrc.js" file or "babel" key in "package.json"). Use null as a first argument to remove that warning. DEPRECATION configureBabel: "include_node_modules" is deprecated. Please use "includeNodeModules" instead. Error: "includeNodeModules" and "exclude" options can't be used together when calling configureBabel().

Liip Imagine ProxyResolver - how to remove bucket prefix

$
0
0
app.imagine.cache.resolver.proxy:
        class: Liip\ImagineBundle\Imagine\Cache\Resolver\ProxyResolver
        arguments:
            - "@app.imagine.cache.resolver.s3"
            - [ '%env(S3_CDN_URL)%' ]
        tags:
            - { name: "liip_imagine.cache.resolver", resolver: "proxy" }
app.s3:
        class: Aws\S3\S3Client
        factory: [Aws\S3\S3Client, factory]
        arguments:
            -
                version: 'latest'
                region: 'fra1'
                endpoint: '%env(S3_BASE_URL)%'
                credentials:
                    key: '%env(S3_KEY)%'
                    secret: '%env(S3_SECRET_KEY)%'
app.imagine.cache.resolver.s3:
        class: Liip\ImagineBundle\Imagine\Cache\Resolver\AwsS3Resolver
        arguments:
            - "@app.s3"
            - '%env(S3_BUCKET_NAME)%'
        tags:
            - { name: "liip_imagine.cache.resolver", resolver: "s3" }

The problem is I'd like to use DigitalOcean spaces CDN and its CDN is per bucket, so there is no bucket prefix.

In the end I get a resolved url like:

S3_CDN_URL/bucketName/filePath

which is non existent.

I need to get:

S3_CDN_URL/filePath

I can't find any setting for that.

Basically, I need to access S3 in 'Virtual Hosted Style': https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingBucket.html#access-bucket-intro

How can I move my new message function after submit new conversation form

$
0
0

I made a simple messaging system where users can create conversation with message.

When a user create a conversation, the form ask for the title (Conversation Entity) and the content of the message (Message Entity). So I made a form with custom data class.

When the user submit the form, it call my create discussion route.

/** public function create(Request $request) {

    //TODO: check permission
    $user = $this->getUser();

    // Create a new conversation object
    $conversation = new Conversation();

    // Make the form
    $form = $this->createForm(ConversationType::class);

    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {

        // Check if recipient is a valid user

        // Get username from form
        $recipient = $this->getDoctrine()->getRepository(User::class)
            ->findOneBy(array('username' => $form->get('recipient')->getData()));


        //Redirect user if recipient doesn't exist
        if ($recipient === null) {
            // TODO: Redirect
        } else if ($recipient === $user) {
            // TODO: Redirect
        }

        // Set conversation title
        $conversation->setTitle($form->get('title')->getData());
        // Add participants to conversation
        $conversation->addParticipant($user);
        $conversation->addParticipant($recipient);

        //Save conversation
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($conversation);



        //Message
        $message = new Message();
        // Set message informations
        $message->setAuthor($user);
        $message->setContent($form->get('content')->getData());
        $message->setConversation($conversation);
        $conversation->setUpdatedAt(new \DateTime("now"));
        $this->denyAccessUnlessGranted('new', $message, "The conversation is locked or the user isn't participant");
        //Save message
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($message);
        $entityManager->flush();


        return $this->redirectToRoute('app_conversation_show', array('id' => $conversation->getId()));
    }


    return $this->render('conversation/create.html.twig', array(
        'form' => $form->createView()
    ));

}

Ask you can see, it also create a new message in same time. But this is what my "new" method do (because there is also a form to create a message in the conversation).

public function new(Request $request, Conversation $conversation) {

    $user = $this->getUser();

    $message = new Message();
    $form = $this->createForm(MessageType::class, $message)->handleRequest($request);


    if ($form->isSubmitted() && $form->isValid()) {

        // Set message informations
        $message->setAuthor($user);
        $message->setContent($request->get('message')['content']);
        $message->setConversation($conversation);
        $conversation->setUpdatedAt(new \DateTime("now"));


        $this->denyAccessUnlessGranted('new', $message, "The conversation is locked or the user isn't participant");

        //Save message
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($message);
        $entityManager->flush();

        return $this->redirectToRoute('app_conversation_show', array('id' => $conversation->getId()));
    }


    return $this->render('conversation/conversation.html.twig', array(
        "conversation" => $conversation,
        "form" => $form->createView(),
    ));

}

It's repetitive and this is not what I want. I tried to redirect the user to the "new" route after the create of discussion, but it didn't work.

There is a solution to send automatically the message after submit the create conversation form? Or I've no choice to duplicate my function...

Does only using single constant from a class constant affect performance or load time of a class?

$
0
0

Our project is built on PHP 7.2 / Symfony 4.

We have a class constant for reusability.

class MyConstants {
    const STRING_1 = 'string1';
    const STRING_2 = 'string2';
    // more const string...
}

I want to use the class constant but only need 1 constant from it and only used once (for now).

use MyConstants;
class MyClass {
    function() {
         // do something
         echo MyConstants::STRING_1;
    }
}

My question is does it in any way affect load time or performance of MyClass due to using MyConstant for just one constant?

Is it better to just use a string literal instead?


Symfony 4, get the root path of the project from a custom class (not a controller class)

$
0
0

In the src/Utils directory, I created a custom class Foo for various things. I'm looking for a way to get the absolute root path of the symfony 4 project

From a controller, its easy with :

$webPath = $this->get('kernel')->getProjectDir();

But from a custom class I created in my src/Utils directory, how can I get the root path directory ?

I could pass the path from the controller to the Foo class :

$webPath = $this->get('kernel')->getProjectDir();
$faa = new Foo($webPath);
$faa->doSomething();

but I think its more proper to store this information in the Foo class and have only "controller logic" in the controller class

Symfony Doctrine query builder find entity with many to one relation

$
0
0

I'm building a website with Symfony for a project which will act like "booking.com" websites but much simplier and with some variations.

Some errors on the database fields but not really important for my issue.

enter image description here

As you can see, these tables concern two entities : apartment and visit.A customer can ask for a visit of an apartment. It is a many to one relationship.

I have a search form to search for apartments with criterias. I want to only show apartments that don't have any visits between the arrival and departure dates that the user provided. So I ended up making a function in apartmentRepository to manage that and other cases.

Problem is: how can I get these apartments ?

Here is a draft of this function which is of course not finished neither perfect (if you have some comments to improve it, it would be great !).

public function findByCustom($parameters): ?array{   $query =  $this->createQueryBuilder('a');   foreach ($parameters as $key=> $parameter){       if($key != 'keywords' and $key!= 'priceMin'& $key!='priceMax' and $key!="typeAp" and $key!="searchVisitDate") $query->orWhere('a.'.$key." = '".$parameter."'");       if($key == "typeAp")       {           $typeApQuery = "";           foreach ($parameters[$key] as $index => $type)           {               if($index !== count($parameters[$key])-1)               {                   $typeApQuery.=" a.typeAp = '".$type."' or";               }               else               {                   $typeApQuery.= " a.typeAp = '".$type."'";               }           }           $query->andWhere($typeApQuery);       }   }   $query->andWhere('a.rentPrice >='.$parameters['priceMin']." and a.rentPrice <= ".$parameters['priceMax']);   $withoutInner = $query;   $query       ->join('App\Entity\Visit', 'v', Join::ON, 'a = v.apartment')       ->where("v.date between '2020-03-15' and '2020-03-19'");    $query->getQuery()->getResult();    $sorted = $withoutInner->andWhere($this->createQueryBuilder('a')->expr()->notIn('a.id', $query));   return array($sorted);

Of course apartment has a collection of visits and visit as a field named "apartment" which is related to the apartment object.

I really didn't find a proprer way to do it and I want to avoid doing SQL, to improve my understanding of Doctrine.

Thank you for your help because I'm stuck right now :/

EDIT 1: forgot to mention that I want to get apartments that don't have visits between required dates or that don't have any visits at all

EDIT 2 :

public function findByCustom($parameters): ?array{   $query =  $this->createQueryBuilder('a');    $withoutInner = $this->createQueryBuilder("a");   foreach ($parameters as $key=> $parameter){       if($key != 'keywords' and $key!= 'priceMin'& $key!='priceMax' and $key!="typeAp" and $key!="searchVisitDate")       {           $withoutInner->orWhere('a.'.$key." = '".$parameter."'");           $query->orWhere('a.'.$key." = '".$parameter."'");       }       if($key == "typeAp")       {           $typeApQuery = "";           foreach ($parameters[$key] as $index => $type)           {               if($index !== count($parameters[$key])-1)               {                   $typeApQuery.=" a.typeAp = '".$type."' or";               }               else               {                   $typeApQuery.= " a.typeAp = '".$type."'";               }           }           $withoutInner->andWhere($typeApQuery);           $query->andWhere($typeApQuery);       }   }   $query->andWhere('a.rentPrice >='.$parameters['priceMin']." and a.rentPrice <= ".$parameters['priceMax']);   $withoutInner->andWhere('a.rentPrice >='.$parameters['priceMin']." and a.rentPrice <= ".$parameters['priceMax']);   $query       ->join('App\Entity\Visit', 'v', Join::WITH, 'a.id = v.apartment')       ->where("v.date between '2020-03-15' and '2020-03-19'");    $query->getQuery()->getResult();    $sorted = $withoutInner->andWhere($this->createQueryBuilder('a')->expr()->notIn('a.id', $query));

With this function I get doctrine error :

Error: Method Doctrine\Common\Collections\ArrayCollection::__toString() must not throw an exception, caught ErrorException: Catchable Fatal Error: Object of class Doctrine\ORM\EntityManager could not be converted to string

EasyAdmin image path

$
0
0

I can't figure out how to display an image uploaded via EasyAdmin. When it uploads the image it displays an absolute path on the server and stores the whole thing together with the filename to the database, so it can't be used for the html <img> tag.

How can I store a relative path to the image instead? Or do I need to apply some filter in twig to display it?

I have an EasyAdmin form with a field:

- { property: 'imageFile', type: 'file_upload', type_options: { upload_dir: '/public/data/gallery/images/', upload_filename: '[uuid]-[timestamp].[extension]'}}

symfony4 : how to get current logged user in subscriber?

$
0
0

I try to inject Security and the TokenStorageInterface in both cases it returns null despite the user is logged in .

public function __construct(Security $security)
{
    $this->security = $security;
}

public function someMethod()
{
    // returns User object or null if not authenticated
    $user = $this->security->getUser();
}

}

even when I try with the TokenStorageInterface it ruterns null.

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class A { private $user;

public function __construct(TokenStorageInterface $tokenStorage)
{
    $this->user = $tokenStorage->getToken()->getUser();
}

public function foo()
{
    dump($this->user);
}

}

How can I configure webpack for use with Symfony 4 projects

$
0
0

I just installed Babel via the command npm install --save @ babel / preset-env, Once installed, I created a ".babelrc" file at the root and put the following config: {"presets": ["@ babel / preset-env"]}.

Despite that I get the error below:

WARNING The "callback" argument of configureBabel() will not be used because your app already provides an external Babel configuration (a ".babelrc" file, ".babelrc.js" file or "babel" key in "package.json"). Use null as a first argument to remove that warning. DEPRECATION configureBabel: "include_node_modules" is deprecated. Please use "includeNodeModules" instead. Error: "includeNodeModules" and "exclude" options can't be used together when calling configureBabel().

How to get current logged user in subscriber?

$
0
0

I try to inject Security and the TokenStorageInterface in both cases it returns null despite the user is logged in .

public function __construct(Security $security)
{
    $this->security = $security;
}

public function someMethod()
{
    // returns User object or null if not authenticated
    $user = $this->security->getUser();
}

}

even when I try with the TokenStorageInterface it ruterns null.

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class A
{
    private $user;

    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->user = $tokenStorage->getToken()->getUser();
    }

    public function foo()
    {
        dump($this->user);
    }
}

Warning: ftp_get(): File not found

$
0
0

Maybe this is a stupid question, In Symphony (prestashop) this exception stops execution. Can you prevent this behaviour without checking if the file exists in the ftp server?


DoctrineBehaviors Tree get tree from specific child

$
0
0

I have an entity that implement TreeNodeInterface of KnpLabs doctrine Behaviors Tree.

I can get all tree from root with :

$repo = $em->getRepository('Folder');
$folderList = $repo->getTree()->getChildNodes(); // return all tree from root

// but i need tree from specific child

I test this :
$parentPath = $repo->find($idIWantFound)->getRealMaterializedPath();
$tree = $this->getTree($parentPath);

$tree->getChildNodes() // return array()
$tree->getParentNode() // return always null but i need node

I need to retrieve all tree and mostly the parent tree.

I search on web and i didn't found anything to do this.

Thanks in advance for your help

Symfony 4: How to get current logged user in subscriber?

$
0
0

I try to inject Security and the TokenStorageInterface in both cases it returns null despite the user is logged in .

   {       $this->security = $security;   }   public function someMethod()   {       // returns User object or null if not authenticated       $user = $this->security->getUser();   }}

even when I try with the TokenStorageInterface it ruterns null.

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;class A{    private $user;    public function __construct(TokenStorageInterface $tokenStorage)    {        $this->user = $tokenStorage->getToken()->getUser();    }    public function foo()    {        dump($this->user);    }}

Referer Redirect in a POST call in symfony 4 using URL with annotations comments Routes

$
0
0

In version symfony 4, I am trying to resolve a redirect in a action done before with a parameter. I Have annotations Routes.

The problem is it is a POST call and I do not know how convert the URL $request->headers->get('referer') in a action_name or how insert the parameters in the call.

$op = 4; //This is an example of a number$response = new RedirectResponse($request->headers->get('referer'),307,$headers=['Id'=>$Id]);return $response;

or

$op = 4; //This is an example of a number    $response = $this->redirect($request->headers->get('referer'));return $response;

Do you know any way resolves this?

How to get current logged user in subscriber?

$
0
0

I try to inject Security and the TokenStorageInterface in both cases it returns null despite the user is logged in .

public function __construct(Security $security){   $this->security = $security;}public function someMethod(){    // returns User object or null if not authenticated   $user = $this->security->getUser();}

even when I try with the TokenStorageInterface it ruterns null.

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;class A{    private $user;    public function __construct(TokenStorageInterface $tokenStorage)    {        $this->user = $tokenStorage->getToken()->getUser();    }    public function foo()    {        dump($this->user);    }}

Set entity value in listener

$
0
0

I've got a set of entities for which I have a field owned. I need to set owned manually as it's dependent on both a ManyToMany and an inherited system (if a user owns a Course they also own all Subject within, etc).

This class is retrieved from the database using Doctrine ORM annotations. Originally I wanted to set it inside the App\Entity declaration, but since this isn't good practice, I've been looking at maybe using an event listener or factory. I'm stuck with how to do this.

For example, the following is what I'm wanting to set based on the current logged in user.

class Course {    private $owned = false;    public function getOwned(): ?bool    {        return $this->owned;    }    public function setOwned( bool $state )    {        $this->owned = $state;        return $this;    }
Viewing all 3917 articles
Browse latest View live


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