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

Setting HWIAuthBundle without FOSUserBundle

$
0
0

In HWIOAuthBundle,

There is samples to use FOSUserbundle in the document.

my.oauth_aware.user_provider.service:
    class: HWI\Bundle\OAuthBundle\Security\Core\User\FOSUBUserProvider
    arguments:
        - '@fos_user.user_manager'
        - ['pass properties as array']

However in my case (Symfony4.4), there is already native security system and set up in security.yaml.

security:
    app_user_provider:
        entity:
            class: App\Entity\User
            property: email

So I want to make HWIAOuthBundle to use this native security system.

my.oauth_aware.user_provider.service:
    class: HWI\Bundle\OAuthBundle\Security\Core\User\EntityUserProvider
    arguments:
                class: App\Entity\User
                property: email

However it shows like this,

Invalid service "my.oauth_aware.user_provider.service": did you forget to add the "$" prefix to argument "class"?

How can I use HWIOAuthBundle without FOSUserBundle??

services.yaml

parameters:

services:
    _defaults:
        autowire: true     
        autoconfigure: true 

    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

    my.oauth_aware.user_provider.service:
        class: HWI\Bundle\OAuthBundle\Security\Core\User\EntityUserProvider
        arguments:
            class: App\Entity\User
            property: email
hwi_oauth:
    resource_owners:
        any_name:
            type:                facebook
            client_id:           <client_id>
            client_secret:       <client_secret>

security.yaml

security:
    encoders:
        App\Entity\User:
            algorithm: auto

    providers:
        app_user_provider:
            entity:
                class: App\Entity\User
                property: email

    access_control:
        # require ROLE_ADMIN for /admin*
      #  - { path: '^/admin', roles: ROLE_ADMIN }
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: ~
            guard:
                authenticators:
                    - App\Security\LoginFormAuthenticator
            logout:
                path: app_logout
            oauth:
                resource_owners:
                    vkontakte:           "/social-login/check-vkontakte"
                    facebook:            "/social-login/check-facebook"
                    google:              "/social-login/check-google"
                    twitter:             "/social-login/check-twitter"
                login_path:        /login
                use_forward:       false
                failure_path:      /login
                oauth_user_provider:
                    service: my.oauth_aware.user_provider.service

Symfony4 : ./node_modules/.bin/encore: No such file or directory

$
0
0

I try to use webpack to generate assets on Symfony4

I started by adding it using yarn :

yarn add @symfony/webpack-encore --dev

On the installation I get this error

error An unexpected error occurred: "EPROTO: protocol error, symlink '../../../parser/bin/babel-parser.js' ->'/home/vagrant/Symfony/node_modules/@babel/core/node_modules/.bin/parser'".

After a search on the net, I found that the solution is by adding --no-bin-links, so I try it and the installation ended without any error.

but when I want to generate the assets by this command

./node_modules/.bin/encore dev

I get this error (.bin folder not found)

-bash: ./node_modules/.bin/encore: No such file or directory

and when I try to use this command yarn encore dev or yarn run encore dev

error Command "encore" not found.

I searched a lot on the net, but nothing works, is there any solution to fix this problem ?

PS : I use Vagrant and Homestead

Symfony profiler error regarding not available messages when using custom domain

$
0
0

I have the following code under user profile form:

public function __construct(TranslatorInterface $translator)
{
    $this->translator = $translator;
}

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('firstName', TextType::class, 
                               ['label' => $this->translator->trans('First name', [], 'profile')]);
    // more fields
}

My profile.en.yaml file contains line:

'First name': First name value

I just added ' value' to reproduce the exact error.

Now, when I update my translations with

php bin/console translation:update --force en

An xml file for profile domain is generated.

When I run the form on my browser, I get the value translated into 'First name value'.

But on the symfony profiler toolbar I get an error. When I open it, I have record for successful profile translation:

These messages are correctly translated into the given locale.

Locale  Domain  Times used  Message ID  Message Preview
en      profile          1  First name  First name value

And error message for missing message translation:

These messages are not available for the given locale and cannot be found in the fallback locales. Add them to the translation catalogue to avoid Symfony outputting untranslated contents.

Locale  Domain  Times used  Message ID          Message Preview
en      messages         1  First name value    First name value

How can I get rid of the error without using default messages domain?

Edit 1: I played a little with domains and values. Some update to my question. Even if I use messages domain, if I translate id value to a different text, I get two records under profiler - one for successful translation from id to value and one for 'missing' value.

My assumption: when I use translator under form builder with label, Symfony attempts to translate a value from that label and the value from the form view. If two values are the same, I get record with two successful translation. If value is different from id, I have one successful translation and one failed.

When I just use explicit translation under rendered view, everything works fine.

Therefore my question is the same, but more specific: how to tell Symfony not to translate value upon the form view if it was already translated as label under Form class.

Edit 2: The only method worked so far is to get rid of translator under Form class and assign texts to labels without translation. But with this approach I can use only messages and cannot use different domain.

In my twig file the form is encapsulated under

{{ form_widget(form) }}

and I cannot get labels out of that if I do not specify the code or use form themes. And even if I do that, it's still confusing, because I cannot use translator under Form class / builder labels and I lose such an important capability to specify profile domain and translation ids under Form class and not to worry about that under Form view. So the initial question is not answered.

AOuth login User data is stored but no login-ed. with HWIAOuthBundle and Custom UserProvider

$
0
0

I am using HWIAOuthBundle and Custom UserProvider on Symfony 4.4

in MyUserProvider

It stored the access_token and create new user. It works successfully.

namespace App\Security;

use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthAwareUserProviderInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\EntityUserProvider;
use Doctrine\ORM\EntityManagerInterface;


class MyUserProvider extends EntityUserProvider implements OAuthAwareUserProviderInterface 
{

   private $entityManager;


   /**
   * {@inheritdoc}
   */
   public function loadUserByOAuthUserResponse(UserResponseInterface $response)
   {

      $username = $response->getUsername();
      $email = $response->getEmail();
      $user = $this->em
         ->getRepository(\App\Entity\User::class)
         ->findOneByEmail($response->getEmail());
  //when the user is registrating
      if (null === $user) {
         $service = $response->getResourceOwner()->getName();
         $setter = 'set'.ucfirst($service);
         $setter_id = $setter.'Id';
         $setter_token = $setter.'AccessToken';
      // create new user here
         $user = new \App\Entity\User();
         $user->$setter_id($username);
         $user->$setter_token($response->getAccessToken());
         //I have set all requested data with the user's username
         //modify here with relevant data
      //   $user->setUsername($username);
         $user->setEmail($email);
         $user->setPassword($username);
         $user->setEnabled(true);
         $this->em->persist($user);
         $this->em->flush();
         //$this->userManager->updateUser($user);
         return $user;
      }

    //if user exists - go with the HWIOAuth way
      $user = parent::loadUserByOAuthUserResponse($response);

      $serviceName = $response->getResourceOwner()->getName();
      $setter = 'set' . ucfirst($serviceName) . 'AccessToken';

   //update access token
      $user->$setter($response->getAccessToken());

      return $user;
   }

}

However even the user is created correctly in Database, but not login-ed

$this->getUser(); in Controller returns null.

enter image description here

So, I am confused that where the user login accomplished???

my setting is below

security:
    firewalls:
        main:
            oauth:
                resource_owners:
                    facebook:            "/login/check-facebook"
                    google:              "/login/check-google"
                    twitter:             "/login/check-twitter"
                login_path:        /login
                use_forward:       false
     #          failure_path:      /login
                oauth_user_provider:
                    service: my.user.provider

services.yml

my.user.provider:
    class:        App\Security\MyUserProvider
    arguments: ['@doctrine', App\Entity\User , { facebook: facebook_id, twitter: twitter_id, google: google_id }]


hwi_oauth:
    resource_owners:
        facebook:
            type:           facebook
            client_id:      '%env(FB_ID)%'
            client_secret:  '%env(FB_SECRET)%'
            scope:          "email user_posts"
        google:
            type:                google
            client_id:           <client_id>
            client_secret:       <client_secret>
            scope:               "email profile"
        twitter:
            type:                twitter
            client_id:           XXXXXXX
            client_secret:       XXXXXX
            scope:               "email profile"

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 is not defined...

C:\Users\Chris\Code\api-test> php bin/console server:run
Command "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, for start the server I follow this document.

https://symfony.com/doc/current/setup/web_server_configuration.html

But I did not understand that...

How to post data in symfony using objectManager?

$
0
0

I am trying to post to table. I am using objectManager.

use Doctrine\Common\Persistence\ObjectManager;
public function postListsAction(ObjectManager $objectManager, Request $request)
    {
        dump($request);

But I am getting following error in postman.

Cannot autowire argument $objectManager of \"App\\Controller\\ListController::postListsAction()\": it references interface \"Doctrine\\Persistence\\ObjectManager\" but no such service exists. You should maybe alias this interface to the existing \"doctrine.orm.default_entity_manager\" service.

If I hover over that $objectManager, I get Class 'ObjectManager' is deprecated error as well.

How to modelize privilèges in Symfony 4 database? [closed]

$
0
0

Hello everyone I want to model a privilege system in my database under symfony 4 and I would like to know if my design is good or not?

Here is an overview of the system of privileges I would have for each User on each resource.

enter image description here

Adding the repository to construct gives user deprecated error

$
0
0

I have following lines of code in my controller.

<?php

namespace App\Controller;

use App\Repository\TaskListRepository;
use FOS\RestBundle\Controller\AbstractFOSRestController;

class ListController extends AbstractFOSRestController
{
    /**
     * @var TaskListRepository
     */
    private $taskListRepository;

    public function __construct(TaskListRepository $taskListRepository)
    {
        $this->taskListRepository = $taskListRepository;
    }

    /**
     * @Route("/lists", name="lists")
     */
    public function getListsAction()
    {
        return $this->taskListRepository->findAll();
    }

}

When I try to debug route, I am getting following error:

[info] User Deprecated: Using the WebserverBundle is deprecated since Symfony 4.4. The new Symfony local server has more features, you can use it instead. 2019-12-16T04:37:53+01:00 [info] User Deprecated: Loading the file "../../src/Controller/" from the global resource directory "D:\xampp\htdocs\symfony_rest\src" is depre cated since Symfony 4.4 and will be removed in 5.0.

How can I fix this issue?


AOuth login can't store session token, but userdata is stored correctly in DB with HWIAOuthBundle

$
0
0

I am using HWIAOuthBundle and Custom UserProvider on Symfony 4.4

in MyUserProvider

It stored the access_token and create new user. It works successfully.

namespace App\Security;

use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthAwareUserProviderInterface;
use HWI\Bundle\OAuthBundle\Security\Core\User\EntityUserProvider;
use Doctrine\ORM\EntityManagerInterface;


class MyUserProvider extends EntityUserProvider implements OAuthAwareUserProviderInterface 
{

   private $entityManager;


   /**
   * {@inheritdoc}
   */
   public function loadUserByOAuthUserResponse(UserResponseInterface $response)
   {

      $username = $response->getUsername();
      $email = $response->getEmail();
      $user = $this->em
         ->getRepository(\App\Entity\User::class)
         ->findOneByEmail($response->getEmail());
  //when the user is registrating
      if (null === $user) {
         $service = $response->getResourceOwner()->getName();
         $setter = 'set'.ucfirst($service);
         $setter_id = $setter.'Id';
         $setter_token = $setter.'AccessToken';
      // create new user here
         $user = new \App\Entity\User();
         $user->$setter_id($username);
         $user->$setter_token($response->getAccessToken());
         //I have set all requested data with the user's username
         //modify here with relevant data
      //   $user->setUsername($username);
         $user->setEmail($email);
         $user->setPassword($username);
         $user->setEnabled(true);
         $this->em->persist($user);
         $this->em->flush();
         //$this->userManager->updateUser($user);
         return $user;
      }

    //if user exists - go with the HWIOAuth way
      $user = parent::loadUserByOAuthUserResponse($response);

      $serviceName = $response->getResourceOwner()->getName();
      $setter = 'set' . ucfirst($serviceName) . 'AccessToken';

   //update access token
      $user->$setter($response->getAccessToken());

      return $user;
   }

}

However even the user is created correctly in Database, but not login-ed

$this->getUser(); in Controller returns null.

enter image description here

So, I am confused that where the user login accomplished???

my setting is below

security:
    firewalls:
        main:
            oauth:
                resource_owners:
                    facebook:            "/login/check-facebook"
                    google:              "/login/check-google"
                    twitter:             "/login/check-twitter"
                login_path:        /login
                use_forward:       false
     #          failure_path:      /login
                oauth_user_provider:
                    service: my.user.provider

services.yml

my.user.provider:
    class:        App\Security\MyUserProvider
    arguments: ['@doctrine', App\Entity\User , { facebook: facebook_id, twitter: twitter_id, google: google_id }]


hwi_oauth:
    resource_owners:
        facebook:
            type:           facebook
            client_id:      '%env(FB_ID)%'
            client_secret:  '%env(FB_SECRET)%'
            scope:          "email user_posts"
        google:
            type:                google
            client_id:           <client_id>
            client_secret:       <client_secret>
            scope:               "email profile"
        twitter:
            type:                twitter
            client_id:           XXXXXXX
            client_secret:       XXXXXX
            scope:               "email profile"

Additional

   $token = $this->container->get('security.token_storage')->getToken();
   var_dump($token);

There is only annonymous.

object(Symfony\Component\Security\Core\Authentication\Token\AnonymousToken)#664 (6) { ["secret":"Symfony\Component\Security\Core\Authentication\Token\AnonymousToken":private]=> string(7) "QZZau69" ["user":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=> string(5) "anon." ["roles":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=> array(0) { } ["roleNames":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=> array(0) { } ["authenticated":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=> bool(true) ["attributes":"Symfony\Component\Security\Core\Authentication\Token\AbstractToken":private]=> array(0) { } }

So, I think MyUserProvider or somewhere( like AuthenticationListener??) else that should store the token failed.

How to add $request into the construct method?

$
0
0

I have defined Request inside the construct method of this class.

/**
     * @var Request
     */
    protected $request;

    public function __construct(Request $request)
    {
        $this->request = $request;
    }

Now when I try to retrieve the post data in some function like this:

public function postListsAction()
    {

        dd($this->request->get("title"));

I am getting following error:

Cannot autowire service "App\Controller\ListController": argument "$request" of method "__construct()" references class "Symfony\Component\HttpFoundation\Request" but no such service exists.

How can I fix this issue?

List of entites not converting to json instead I get an array of empty objects

$
0
0

I have the following code:

public function adminListAction(Request $request)
{
    if (!$this->isGranted('ROLE_ADMIN')) {
        return new JsonResponse("Not granted");
    }

    $page = $request->query->get('page', 1);

    $criteria = new DocumentaryCriteria();
    $criteria->setStatus(DocumentaryStatus::PUBLISH);
    $criteria->setSort([
        DocumentaryOrderBy::CREATED_AT => Order::DESC
    ]);

    $qb = $this->documentaryService->getDocumentariesByCriteriaQueryBuilder($criteria);

    $adapter = new DoctrineORMAdapter($qb, false);
    $pagerfanta = new Pagerfanta($adapter);
    $pagerfanta->setMaxPerPage(12);
    $pagerfanta->setCurrentPage($page);

    $items = (array) $pagerfanta->getCurrentPageResults();

    $data = [
        'items'             => $items,
        'count_results'     => $pagerfanta->getNbResults(),
        'current_page'      => $pagerfanta->getCurrentPage(),
        'number_of_pages'   => $pagerfanta->getNbPages(),
        'next'              => ($pagerfanta->hasNextPage()) ? $pagerfanta->getNextPage() : null,
        'prev'              => ($pagerfanta->hasPreviousPage()) ? $pagerfanta->getPreviousPage() : null,
        'paginate'          => $pagerfanta->haveToPaginate(),
    ];

    return new JsonResponse($data);
}

which returns the following, notice the array of empty objects

{ "items": [ {}, {}, {}, {}, {}, {}, {}, {}, {} ], "count_results": 9, "current_page": 1, "number_of_pages": 1, "next": null, "prev": null, "paginate": false }

I know their properties aren't null by doing this:

foreach ($items as $item) {
    echo $item->getTitle();
}

// returns 'Documentary 1'

ODBC Driver 17 unable to establish connection to MSSQL 2008 R2

$
0
0

I'm having an issue concerning my Debian 9 server on Apache2, php7.3, ODBC Driver 17, sqlsrv (7.3). I can't connect it to my Microsoft SQL Server 2008 R2 running on a Windows Server 2005.

I tried using isql -v -k "DRIVER={ODBC Driver 17 For SQL Server};Server=SRV-WINDOS\MSSQLSERVER2008;UID=MyUser;PWD=MyPWD;Database=DB on the Debian Server. Outputs: [08001][unixODBC][Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: Error code 0x2746 [08001][unixODBC][Microsoft][ODBC Driver 17 for SQL Server]Client unable to establish connection [ISQL]ERROR: Could not SQLConnect

The SQL server seems correctly set-up as I can connect to it with the same Symfony project on my local machine (Windows 10 running Wamp - apache2, php7.2.18, symfony4, doctrine and the sqlsrv extensions).

I also tried using the ODBC Driver 13 but I'm having issues with it ([01000][unixODBC][Driver Manager]Can't open lib '/opt/microsoft/msodbcsql/lib64/libmsodbcsql-13.1.so.9.2' : file not found since it seems like ODBC Driver 13 and lower are not supported on Debian 9`)

I'm a bit lost, ODBC Driver 17 should enable me to establish a connection to my MSSQLSERVER 2008 R2 right ?

N.B: The Debian 9 server can indeed ping and resolves the domain of the MSSQLSERVER 2008 so it's not a networking issue.

Download PhpSpreadsheet file without save it before

$
0
0

I'm using PhpSpreadsheet to generate an Excel file in Symfony 4. My code is:

$spreadsheet = $this->generateExcel($content);

$writer = new Xlsx($spreadsheet);
$filename = "myFile.xlsx";
$writer->save($filename); // LINE I WANT TO AVOID
$response = new BinaryFileResponse($filename);
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->setContentDisposition(
    ResponseHeaderBag::DISPOSITION_ATTACHMENT,
    $filename
);

But I don't want to save the file and then read it to return to the user. I would like to download Excel content directly. Is there a way to do It?

I've searched how to generate a stream of the content (as this answer says) but I hadn't success.

Thanks in advance and sorry about my English

Symfony 4 : why the attributes of the 'first_options' doesn't apply in a form with a RepeatedType?

$
0
0

I'm doing a form with 2 fields to ask a password and to confirm the password.

I would like to have a message on the first field if the pattern is not the good one.

I tried to put attributes in 'options', the pattern goes to 2 fields, but the 'oninvalid' and 'oninput' goes only to the second field.

 $textInvalidFormat = $translator->trans('invalidFormat', [], 'general');
        $form = $this->createFormBuilder()
            ->add('password', RepeatedType::class, array(
                'type' => PasswordType::class,
                'options' => ['attr' => ['oninvalid'=>'setCustomValidity("' .$textInvalidFormat . '")',
                    'oninput'=>"setCustomValidity('')",
                    'pattern' => '^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[^\w\d\s:])([^\s]){8,}$']],
                'first_options' => array(
                    'translation_domain' => 'request',
                    ),
                'second_options' => array('label' => 'field.request.secondpwd',
                    'translation_domain' => 'request',),
            ))
            ->getForm();

I also tried to put these options in the 'first_options' but the result is the same.

$textInvalidFormat = $translator->trans('invalidFormat', [], 'general');
        $form = $this->createFormBuilder()
            ->add('password', RepeatedType::class, array(
                'type' => PasswordType::class,
                'first_options' => array(
                    'translation_domain' => 'request',
                    'attr' => ['oninvalid'=>'setCustomValidity("' .$textInvalidFormat . '")',
                        'oninput'=>"setCustomValidity('')",
                        'pattern' => '^(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[^\w\d\s:])([^\s]){8,}$']
                    ),
                'second_options' => array('label' => 'field.request.secondpwd',
                    'translation_domain' => 'request',),
            ))
            ->getForm();

The result:

enter image description here

The problem is : I just have the message of my browser but not the one I define in my translation file.

Can you tell me where is the mistake and why the attributes of the 'first_options' doesn't apply ?

Sonata Admin CollectionType to add one-to-many entities

$
0
0

I'm using Sonata Admin Bundle 3.4 with Symfony 4.3.

I'm trying to figure out how to add multiple somethings to an entity. For the sake of this example, it could be GalleryHasMedias to a Gallery, as mentioned in the documentation: https://sonata-project.org/bundles/doctrine-orm-admin/3-x/doc/reference/form_field_definition.html#advanced-usage-one-to-many

My first issue was that I didn't get a select-box to select existing GalleryHasMedias. I just got the label. This was resolved by adding 'allow_add' => true to the options array, but now I just get a plain input field for each added row.

What I would like instead, is a select-box with the existing GalleryHasMedias plus an 'Add new' button, so that I can create a new one. When creating a new one, I would expect a form in a modal where I could enter the details about my new GalleryHasMedia.

I've set up the Gallery entity with OneToMany GalleryHasMedias, and my GalleryAdmin looks like this:

        $formMapper
            ->add(
                'galleryHasMedias',
                CollectionType::class,
                [
                    'by_reference' => false,
                    'allow_add' => true,
                ],
                [
                    'edit' => 'inline',
                    'inline' => 'table',
                    'sortable' => 'position',
                    'limit' => 3,
                ]
        );

What else do I need to set this up?


Limit login attempts under Symfony 4 and FOSRestBundle

Symfony 4 autowiring not working properly

$
0
0

Here is the context:

  1. Installed beanstalk bundle with composer "composer require leezy/pheanstalk-bundle"

  2. I'm trying to using inside a command but i get this error

Cannot autowire service "App\Command\Worker\ProcessParserCommand": argument "$pheanstalk" of method "__construct()" references interface "Pheanstalk\Contract\PheanstalkInterface" but no such
service exists. You should maybe alias this interface to the existing "leezy.pheanstalk.proxy.default" service.

class ProcessParserCommand extends Command
{
    protected static $defaultName = 'app:worker:process-parser';

    /** @var PheanstalkInterface $pheanstalk */
    private $pheanstalk;

    protected function configure()
    {
        $this
            ->setDescription("Parse something")
        ;
    }



    public function __construct(PheanstalkInterface $pheanstalk)
    {
        $this->pheanstalk=$pheanstalk;

        parent::__construct();
    }
}

Error content-type after update Symfony from 4.3 to 4.4

$
0
0

I have updated Symfony project (api platform) from 4.3 to 4.4 with composer update, but now I receive this error in POST requests:

The content-type "application/json" is not supported. Supported MIME types are "".

Trace where broke:

../vendor/api-platform/core/src/EventListener/DeserializeListener.php

Any idea?

Including Assets (CSS, JS) in Symfony 4 / Twig Template

$
0
0

Im learning Symfony and trying to set up a boilerplate app in Symfony 4

This Symfony document describes how to include assets in your page, namely using the asset package like so..

<img src="{{ asset('images/logo.png') }}" alt="Symfony!" />

<link href="{{ asset('css/blog.css') }}" rel="stylesheet" /> 

I have installed this package and trying to link to a css file in my /public directory.

I know Symfony recommends placing assets in an /assets folder at the root, but I would like to avoid this if possible. It makes more sense to me to place assets in the public directory.

My Twig base template is as follows:

<html>
    <head>
        <meta charset="UTF-8">
        <title>{% block title %}Welcome!{% endblock %}</title>

        {% block stylesheets %}
            <link href="{{ asset('public/css/main.css') }}" rel="stylesheet" />
        {% endblock %}
    </head>
    <body>
        {% block body %}{% endblock %}
        {% block javascripts %}{% endblock %}
    </body>
    <footer>footer</footer>
</html>

Problem

When I load the route/page/template, the linked css is rendered as a simple link from the root (as if Im linking it as <link href="public/css/main.css" rel="stylesheet" /> - there is of course no route set for public/* and this returns 404/Not Found.

Its as if the asset() function is not even used.

Ive tried

  • Restarting my local Symfony server
  • moving the asset to an assets folder at the root at adjusting the link accordingly
  • verifying that the asset package was installed (it is)
  • googling this issue (nothing for Symfony 4)

Questions

  • How can I let Symfony know that the public/* path is a filesystem path to assets, NOT a URL route, and include my assets successfully?
  • Is there such a feature to set a default location for assets other than the recommended /assets folder at the root?

Can't create postgres database with doctrine in symfony 4.4

$
0
0

I'm using Symfony 4.4 with PHP 7.2 and postgres 11

I have enabled extension=pdo_pgsql and extension=pgsql in file php.ini (/etc/php/7.2/fpm/php.ini

And then, I have restarted PHP and Nginx server.

I have added this line in .env file in the Symfony application directory

DATABASE_URL=pgsql://postgres:postgres@127.0.0.1:5432/db_name?serverVersion=5.7

When I tried to create the database by running this command

php bin/console doctrine:database:create

I got following errors

In AbstractPostgreSQLDriver.php line 79:
An exception occurred in driver: could not find driver
In PDOConnection.php line 31:
could not find driver
In PDOConnection.php line 27:
could not find driver
Viewing all 3916 articles
Browse latest View live


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