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

Symfony 4 deploying in azure error : The page isn’t redirecting properly

$
0
0

First I'm using "Azure for students" and this is my website : immonova.azurewebsites.net


Ok so the problem is I get from the browser "The page isn’t redirecting properly" when in the home page :

  1. I try to search for a property in the menu (After clicking on the button "Rechercher")

  2. Also in the navbar when I click on the button "Mes favoris" to get the user's favourites (it uses session)

My code works on local.

To solve the second problem I found that I have to use a session state provider there are 3 :

  1. Table Storage

  2. SQL Azure

3.Windows Azure Caching

I've choosed Windows Azure Caching.

This is my web.config file :

<configuration>
  <system.webServer>

<sessionState mode="Custom" customProvider="AzureCacheSessionStoreProvider">
  <providers>
    <add name="AzureCacheSessionStoreProvider"
          type="Microsoft.Web.DistributedCache.DistributedCacheSessionStateStoreProvider, Microsoft.Web.DistributedCache"
          cacheName="default" useBlobMode="true" dataCacheClientName="default" />
  </providers>
</sessionState>


    <rewrite>
      <rules>
        <rule name="Imported Rule 1" stopProcessing="true">
          <match url="^(.*)/$" ignoreCase="false" />
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
          </conditions>
          <action type="Redirect" redirectType="Permanent" url="/{R:1}" />
        </rule>
        <rule name="Imported Rule 2" stopProcessing="true">
          <match url="^" ignoreCase="false" />
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" negate="true" />
          </conditions>
          <action type="Rewrite" url="index.php" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

But I get a "The page cannot be displayed because an internal server error has occurred." when I refresh the website. I don't know if my web.config is right or should I do something else to solve this issue ??


How do I write a function for Converting IP decimal number format to IP address format in Symfony 4?

$
0
0

Is there any function or API or method that will convert an IP decimal format to an IP address format? Like '16801024' convert to '1.0.93.0'

Symfony4: No route found for "GET /lucky/number"

$
0
0

I am starting to play with symfony4. I've just created new application and create new LuckyController. It works with routes.yaml configured in this manner:

lucky:
    path: /lucky/number
    controller: App\Controller\LuckyController::number

With the following controller:

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;

class LuckyController
{
    public function number()
    {
        return new Response('<html><head></head><body>' . rand(111, 999) . '</body></html>');
    }
}

But I want to use annotations. So I decided to comment routes.yaml. Following documentation that explain how to create a route in symfony I've made this:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class LuckyController extends Controller
{
    /**
     * @Route("/lucky/number")
     */
    public function number()
    {
        return new Response('<html><head></head><body>' . rand(111, 999) . '</body></html>');
    }
}

No route found

How to hide or delete the defaults available console commands?

$
0
0

I created a new Symfony 4 project via symfony new my_project_name.

Currently when I execute ./bin/console, the output shows

console output

I will create some custom console commands and I want show only my custom commands when I do ./bin/console

Maybe I should create a custom executable 'console' from scratch, but I don't know how do that.

PHPUnit, Symfony4 and namespaces

$
0
0

I have the following error:

In TestFixturesCommand.php line 32:

  Attempted to load class "AbstractTest" from namespace "App\Tests\Functional  
  ".                                                                           
  Did you forget a "use" statement for "Symfony\Component\Validator\Tests\Val  
  idator\AbstractTest"?

I can't solve it even with composer dump-autoload. Here is the TextFixturesCommand code:

<?php

namespace App\Command;

use App\Tests\Functional\AbstractTest;
use Doctrine\Common\DataFixtures\Loader;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

/**
 * Class TestFixturesCommand
 * @package App\Command
 */
class TestFixturesCommand extends Command
{
    protected static $defaultName = 'test:fixtures';

    protected function configure()
    {
        $this->setDescription('Execute test fixtures');
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int|void|null
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $loader = new Loader();
        dump(AbstractTest::test()); exit; //this is line 32
        $loader->loadFromDirectory(AbstractTest::getKernel()->getProjectDir() . '/tests/DataFixtures');
        AbstractTest::executeFixtures($loader);
    }
}

Abstract test class look like:

namespace App\Tests\Functional;

use Doctrine\Common\DataFixtures\Executor\ORMExecutor;
use Doctrine\Common\DataFixtures\Loader;
use Doctrine\Common\DataFixtures\Purger\ORMPurger;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Client;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\KernelInterface;
use Unirest\Method;

/**
 * Class AbstractTest
 * @package App\Tests\Functional
 */
//abstract class AbstractTest extends WebTestCase
class AbstractTest extends WebTestCase

and I can also show you the dev autoloader section from composer.json:

"autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "src/Tests"
        }
    },

From my understanding of the problem, there is a confusion between my AbstractTest class and Symfony\Component\Validator\Tests\Validator\AbstractTest but I already change the name of AbstractTest class to check if the problem is solved, but it's not

Symfony 4: How to disable profiler in test-env through command line

$
0
0

I am trying for quite some time now to disable the profiler in the test-environment. The only way it works is manually setting APP_ENV=test in file .env but I want to do this through the command line, not by editing a file.

Here's everything I tried:

  • I tried editing bin/console like described in Chris Brown's answer in this thread: Load different .env file with a Symfony 4 command (I also added the file .env.test, and according to xdebug it loads the appropriate file and runs through the appropriate code and also the variables $env and $debug get the appropriate value when I run the server with --env=test --no-debug)

  • I tried setting profiler: enabled: false like described in flu's answer in this thread: How to disable profiler in Symfony2 in production? (in config/packages/test/framework.yaml)

  • I tried setting the profiler line in bundles.php to

Symfony\Bundle\WebProfilerBundle\WebProfilerBundle::class => ['dev' => true],

and to

Symfony\Bundle\WebProfilerBundle\WebProfilerBundle::class => ['dev' => true, 'test' => false, 'test_cached' => false],

I tried those solutions separately and also all together, still the profiler keeps popping up. Does anybody have an idea?

EDIT: After applying Alister Bulman's answer the command gives me this:

#php bin/console -e test debug:config framework profiler

Current configuration for "framework.profiler"
==============================================

enabled: true
collect: false
only_exceptions: false
only_master_requests: false
dsn: 'file:%kernel.cache_dir%/profiler'

EDIT 2: Thanks to Jared Farrish I just found out the browser is receiving the website in "dev" mode although the server is started in test environment on cli. Obviously editing bin/console and public/index.php is not enough, they're not called when the server receives a request from the browser.

EDIT 3: So I found out the http request goes first to public/index.php, but whatever I do, I cannot seem to make anything available there which was defined in bin/console although the whole server is started there in the first place. Anyone an idea how this can be done?

Select 2 Webpack-encore

$
0
0

I'm trying to use select2 with webpack-encore on my symphony4 project. My app.js file is loaded without problem but not select2 while i installed it .. I do not understand why it's not working at all ...

My html

<select>
    <option value="">--Please choose an option--</option>
    <option value="dog">Dog</option>
    <option value="cat">Cat</option>
    <option value="hamster">Hamster</option>
    </select>

My app.js

require('../css/app.css');

const $ = require('jquery');





console.log('Hello Webpackfdsfds Encore! Edit me in assets/js/app.js');

require('select2')

$('select').select2({ width: '100%', placeholder: "Select an Option", allowClear: true })

What it looks likehttps://imgur.com/Wh1zMn8

I would be grateful if you would help me

How to display a datepicker on Symfony?

$
0
0

I want to set up a date-picker for my date type fields based on symfony documentation. I have installed the package since packagist 'eternicode / bootstrap-datepicker'. I am able to apply my defined conditions for entering the date field in my js (like the date format) but the display is still impossible. I do not have an error message in my js console. I don't even see the datepikcer component..

My Form Type:

   ->add('date_entree', DateType::class, [ 
                'widget' => 'single_text',
    'html5' => false,
    'attr' => ['class' => 'js-datepicker'],
                ])

My JS:

    $(document).on('ready', function() {
         $('.js-datepicker').datepicker({
              format: 'dd-mm-yyyy',
         });
     });

Have you please an idea about this issue?


Symfony 4 extremely slow on windows

$
0
0

I've used Symfony on Windows 10 for my projects for a few years (SF2, SF3), and I recently moved to Symfony 4 to build a new project but performances are catastrophic.

Symfony initialization time takes from 5 to 25s, as in this example example

It is the same with console: for example a cache:clear can last 1 minute.

I searched for similar problems and issues in Symfony doc and forums, and I've tested recommended optimizations (increase some values for ​​opcache, enable APCu, disable xdebug, add realpath_cache_size in php.ini, use Composer Class Map Functionality) but in my case it does not change anything.

Here are my phpinfo for APCu: APCu and Opcache: opcache

I'm using PHP 7.1.9, Apache 2.4.27, MariaDB 10.2.8.

Is there someone with same problems and/or ideas ?

Symfony 4 - ServiceCircularReferenceException

$
0
0

I am currently porting our Symfony application to Symfony 4.3. I understand from the documentation that instead of doing $this->container->get ( 'service_a' ) the new best practice is to use Dependency Injection to attach the service in the constructor like so:

    public function __construct(ServiceA $service_a)
    {
        $this->service_a = $service_a;
    }

I have two services that in certain functions call each other, ServiceA and ServiceB. When I added ServiceA to ServiceB's constructor I saw no error but after adding ServiceB to ServiceA's constructor I received the following error:


(1/1) ServiceCircularReferenceException
Circular reference detected for service "App\Service\ServiceA", path: "App\Service\ServiceA -> App\Service\ServiceB -> App\Service\ServiceA".

(All of this code worked without issue in Symfony 2)

Have I misunderstood the new methodology? Am I using DependencyInjection wrong here?

How to fix problem with authentication? Authenticator has no access to property 'username'

$
0
0

I create a project in php with symfony. I made registration form and it works but, I was trying to make login form, when I found out a problem.

Could not determine access type for property "username" in class "App\Entity\User": Neither the property "username" nor one of the methods "addUsername()"/"removeUsername()", "setUsername()", "username()", "__set()" or "__call()" exist and have public access in class "App\Entity\User".

Ok... I cannot understand what happen. I make my project with YT course and my code looks identically or I'm blind.

Code works only if I change

private $username;

into

public $username;

But this is not a solution. I still don't know why authenticator cannot get access to this property.

User Entity :

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=180, unique=true)
     */
    private $username;

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

    /**
     * @ORM\Column(type="string", length=180, nullable = true)
     */
    private $secondName;

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

    /**
     * @ORM\Column(type="datetime")
     */
    private $birthDate;

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

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

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


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

    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     */
    private $password;

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

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUsername(): string
    {
        return (string) $this->username;
    }

    public function setUsername(): self
    {
        $this->username = substr($this->name,0,1) . $this->lastname . rand(1000,9999);

        return $this;
    }
...

LoginAuth:

<?php

namespace 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\Http\Util\TargetPathTrait;

class LoginAuthenticator extends AbstractFormLoginAuthenticator
{
    use TargetPathTrait;

    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 'app_login' === $request->attributes->get('_route')
            && $request->isMethod('POST');
    }

    public function getCredentials(Request $request)
    {
        $credentials = [
            'username' => $request->request->get('username'),
            'password' => $request->request->get('password'),
            'csrf_token' => $request->request->get('_csrf_token'),
        ];
        $request->getSession()->set(
            Security::LAST_USERNAME,
            $credentials['username']
        );

        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(['username' => $credentials['username']]);

        if (!$user) {
            // fail authentication with a custom error
            throw new CustomUserMessageAuthenticationException('Username could not be found.');
        }

        return $user;
    }

    public function checkCredentials($credentials, UserInterface $user)
    {
        return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
            return new RedirectResponse($targetPath);
        }

        // For example : return new RedirectResponse($this->urlGenerator->generate('some_route'));
        return new RedirectResponse($this-> urlGenerator() -> generate('main'));
    }

    protected function getLoginUrl()
    {
        return $this->urlGenerator->generate('app_login');
    }
}

Symfony 4.x route annotations not working on homestead

$
0
0

On Windows, when I install a clean symfony project with

composer create-project symfony/skeleton my-project

and set a Route like

/**
 * @Route("/login", name="login")
 */

and then start the symfony dev server, everything works just fine.

If I try to run the same environment on a homestead vagrant box, then the annotations get ignored. bin/console debug:router shows no routes either.

If I define them in the routes.yaml though they work. What am I missing?

I have tried with homestead 8.5.3 and with 8.4.0.

My homestead.yaml is like:

ip: 192.168.10.10
memory: 2048
cpus: 1
provider: virtualbox
authorize: ~/.ssh/id_rsa.pub
keys:
    - ~/.ssh/id_rsa
folders:
    -
        map: '/path/to/code'
        to: /home/vagrant/code
sites:
    -
        map: homestead.test
        to: /home/vagrant/code/public
        type: symfony4
databases:
    - homestead
name: my_project
hostname: my_project

I have a feeling that it has to do with the shared folders. Have you ever experienced such a behavior?

api-platform/symfony security voter subject null when Entity implements interface

$
0
0

When I implement an interface or extend a class, the subject in the voter class is null. This is not expected behaviour, after removing the interface works all fine. am I doing something wrong or this is by design not working?

class SomeVoter implements VoterInterface
{
    ..
    public function vote(TokenInterface $token, $subject, array $attributes)
    {
        if ($subject != null)
        {
            //some logic..
            return VoterInterface::ACCESS_GRANTED;
        }

        return VoterInterface::ACCESS_DENIED;
    }
}

/**
 * @ApiResource(
 *     graphql={
 *          "item_query"={
 *              "security"="is_granted('view_',object)"
 *          }
 *     }
 * )
 */
class Folder implements CurrentUserInterface
{
    ...
}   

Symfony 4 - correct Semantic UI integration

$
0
0

I want to integrate Semantic UI in my Symfony 4.3 project. I installed with npm:

npm install semantic-ui --save

But is it correct to build the Semantic folder in the root of the Symfony project?

/semantic (default)

Or must I go to the node_modules semantic folder and run gulp build there? Is there help for me how to implement correct in Symfony?

THX Mike

Doctrine won't connect to MAMP mysql database

$
0
0

I have started learninng Symfony for a school project, and I was following a tutorial from Symfony's website, but for some reason Doctrine dosn't manage to connect to mysql database I have running on my computer. I'm on a Macbook, using MAMP to run a local mysql server. Whenever I try to execute any doctrine commands that interact with the database such as php bin/console doctrine:database:create it never works.

So far, I have checked that I could indeed connect to the database using phpmyadmin. I have also tried to changing the DATABASE_URL in the .env file, but this hasn't solved my issue. I have als tried creating a symbolic link with sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock mysql.sock but that didn't work either.

This is what my .env file looks like:

###> doctrine/doctrine-bundle ###
# Format described at https://www.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url
# For an SQLite database, use: "sqlite:///%kernel.project_dir%/var/data.db"
# For a PostgreSQL database, use: "postgresql://db_user:db_password@127.0.0.1:5432/db_name?serverVersion=11"
# IMPORTANT: You MUST also configure your db driver and server_version in config/packages/doctrine.yaml
DATABASE_URL=mysql://root:root@127.0.0.1:8888/pweb2
###< doctrine/doctrine-bundle ###

And I get this error when trying to create a database with doctrine:

In AbstractMySQLDriver.php line 93:

  An exception occurred in driver: SQLSTATE[HY000] [2002] No such file or directory  


In PDOConnection.php line 31:

  SQLSTATE[HY000] [2002] No such file or directory  


In PDOConnection.php line 27:

  SQLSTATE[HY000] [2002] No such file or directory  

Anything that can point me in the right direction is greatly apreaciated, thanks!


Symfony: Update entity without related entity

$
0
0

I need to update entity (PostMeta) without related entity (Post). The + code looks like this:

$post = $postRepository->findOneBy(['id' => $postId]);

$postMeta = new PostMeta;
$postMeta->setPost($post);
$postMeta->setMetaKey('views');
$postMeta->setMetaValue($count + 1);
$postMeta->setUser(null);
$postMeta->setDate(new \DateTime());

$this->_em->persist($postMeta);
$this->_em->flush($postMeta);

How to persist PostMeta entity, but not update Post entity?

Semantic UI Icons not loading Symfony Webpack-Encore

$
0
0

I build in Symfony 4.3 my Semantic UI folder under assets/. The problem is, that it is not loading the icons (fonts). If i change the webpack encore link (css and js) to the node_modules folder, it works.

// enable JQuery for Semantic UI
.autoProvidejQuery()

// add semantic-ui entries
.addEntry('semantic_styles', './assets/bundles/semantic/dist/semantic.min.css')
.addEntry('semantic_javascripts', './assets/bundles/semantic/dist/semantic.min.js')

Any idea why and how to fix this?

Symfony 4, get .env parameter from a controller, is it possible and how?

$
0
0

From symfony 4, I want create a global parameter and get the value of this parameter from a controller.

This parameter is the path of an another app in the server. So, I thinked add the paramerter in the .env file. But how can I get the value of this parameter from a controller?

How to gzip compress Symfony4 http response before sending it?

$
0
0

I am developing a site with Symfony 4. After a test with GTmetrix, it appears that the files sent by the site are not compressed.

At the beginning I thought it should be a process made by the web server by default but after having contacted the hosting provider, they said it should be done by the code itself.

Do you have any idea of how it should be done with Symfony 4?

Form with query builder

$
0
0

I'm trying to achieve a specific form with the query builder, but I get an error when I add the ->select->distinct to my query builder.

Here is the error:

Warning: spl_object_hash() expects parameter 1 to be object, string given

My code:

 ->add('ville',
    EntityType::class,
    [   
        'class' => Core::class,
        'query_builder' => function(EntityRepository $r)
        {
            return $qb = $r->createQueryBuilder('u')
                           ->select('DISTINCT u.town');
        },
        'choice_label' => 'town',
       ]
    )
Viewing all 3917 articles
Browse latest View live


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