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

"405 method not allowed" when making AJAX request

$
0
0

I am making simple todo app, with Symfony 4 in the back-end and Vue.js for front-end.

I am getting a 405 error status for unknown reasons since a few other endpoints are working correctly.

Here is part of my listController:

/**
 * @return \FOS\RestBundle\View\View
 */
public function getListsAction()
{
    $data = $this->taskListRepository->findAll();
    return $this->view($data, Response::HTTP_OK);
}


/**
 * @Rest\RequestParam(name="title", description="Title of the list", nullable=false)
 * @param ParamFetcher $paramFetcher
 * @return \FOS\RestBundle\View\View
 */
public function postListsAction(ParamFetcher $paramFetcher)
{
    $title = $paramFetcher->get('title');
    if ($title) {
        $list = new TaskList();
        $preferences = new Preference();
        $preferences->setList($list);
        $list->setPreferences($preferences);
        $list->setTitle($title);
        $this->entityManager->persist($list);
        $this->entityManager->flush();
        return $this->view($list, Response::HTTP_CREATED);
    }
    return $this->view(['title' => 'This cannot be null'], Response::HTTP_BAD_REQUEST);
}

the get action is working correctly here it allows me to get all lists from db

and nelmio_cors.yaml file:

nelmio_cors:
    defaults:
        origin_regex: true
        allow_credentials: true
        allow_origin: ['%env(CORS_ALLOW_ORIGIN)%']
        allow_methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']
        allow_headers: ['Content-Type', 'Authorization', 'origin', 'Accept', 'bearer', 'Allow']
        expose_headers: ['Link']
        max_age: 3600
    paths:
        '^/': ~

as you can see POST method is allowed.

debug:router log : enter image description here

as shown the method occurs under expected method and endpoint, register and login_check, where method is not specified working correctly with using POST

Network error:

enter image description here

and in console I am getting CORS error.


How to set up a basic symfony 4 background task?

$
0
0

I am trying to set up a very basic hello background task in my Symfony 4 project. I have tried using mmucklo/DtcQueueBundle having a Hello class as

<?php


namespace App\Worker;


class Hello extends \Dtc\QueueBundle\Model\Worker
{
    public function run(string $name = null, int $times = 1, bool $askHowTheyAre = false): int
    {
        if (null === $name) {
            $name = '';
        }

        for ($i = 0; $i < $times; $i++) {
            $message = sprintf(
                'Hello %s',
                $name
            );
            if ($askHowTheyAre) {
                $message .= ', How are you?';
            }
            print($message.PHP_EOL);
        }
        return self::RESULT_SUCCESS;
    }

    public function getName() {
        return 'hello';
    }
}

as suggested in the documentation. But when I run

bin/console dtc:queue:create_job -j hello run '[ "Matthew" ]'

I get the following error

In WorkerCompilerPass.php line 120:
Class does not exist

Has anyone worked with DtcQueueBundle before or has another background task method to suggest for Symfony 4?

All entities made by doctrine does not contains properties

$
0
0

good afternoon, I'm trying to use donctrine to make entities. My purpose is to make all the entities to generate the database from doctrine with a simple migration. My issue is that when i made my an entities, doctrine only generate the class names but it doesn't generate any properties... So when i migrate, doctrine builds empty tables.

Thx

This is what a generation made...

<?php

namespace App\Repository;

use App\Entity\Login;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Persistence\ManagerRegistry;

/**
 * @method Login|null find($id, $lockMode = null, $lockVersion = null)
 * @method Login|null findOneBy(array $criteria, array $orderBy = null)
 * @method Login[]    findAll()
 * @method Login[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class LoginRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Login::class);
    }

    // /**
    //  * @return Login[] Returns an array of Login objects
    //  */
    /*
    public function findByExampleField($value)
    {
        return $this->createQueryBuilder('l')
            ->andWhere('l.exampleField = :val')
            ->setParameter('val', $value)
            ->orderBy('l.id', 'ASC')
            ->setMaxResults(10)
            ->getQuery()
            ->getResult()
        ;
    }
    */

    /*
    public function findOneBySomeField($value): ?Login
    {
        return $this->createQueryBuilder('l')
            ->andWhere('l.exampleField = :val')
            ->setParameter('val', $value)
            ->getQuery()
            ->getOneOrNullResult()
        ;
    }
    */
}

EDIT :

After several tries, doctrine finaly works. Maybe some Entity files did not save or i had troubles with the compatibilities of doctrine with symfony cause i made an update just before it works...

Symfony 4.4 unknown inky_to_html filter

$
0
0

I recently updated Symfony to 4.4 (from 4.3) and can't have my translations files updated automatically (using php bin/console tran:up --force) any more. The error that pops up is:

In body.html.twig line 1:
Unknown "inky_to_html" filter.

The file in question is vendor/symfony/twig-bridge/Resources/views/Email/zurb_2/notification/body.html.twig which I never use, I have no idea why it's inclued all at a sudden. To get rid of the message I tried to require twig/inky-extra but that requires the ext-xsl-extension and I don't really want to bloat my code with things I don't need just to get rid of an error related to a twig-extension that's also not needed.

I tried to change the version of the translation-interface as described here, but that also didn't change anything.

I guess it has something to do with my project as I couldn't find any similar problem, but I can't figure it out, so any help is appreciated.

EDIT: Here's my composer.json, it's basically the same as it was generated when creating the Symfony 4.3-project, I only changed the version names to upgrade as described in the docs and ran composer update.

{
  "type": "project",
  "license": "proprietary",
  "require": {
    "php": "^7.1.3",
    "ext-ctype": "*",
    "ext-iconv": "*",
    "ext-intl": "*",
    "apy/breadcrumbtrail-bundle": "^1.5",
    "craue/config-bundle": "^2.3",
    "easycorp/easy-log-handler": "^1.0",
    "friendsofsymfony/jsrouting-bundle": "^2.4",
    "league/csv": "^9.4",
    "nesbot/carbon": "^2.25",
    "sensio/framework-extra-bundle": "^5.1",
    "sg/datatablesbundle": "^1.1",
    "symfony/apache-pack": "^1.0",
    "symfony/asset": "^4.0",
    "symfony/console": "^4.0",
    "symfony/dotenv": "^4.0",
    "symfony/expression-language": "^4.0",
    "symfony/flex": "^1.3.1",
    "symfony/form": "^4.0",
    "symfony/framework-bundle": "^4.0",
    "symfony/http-client": "^4.0",
    "symfony/intl": "^4.0",
    "symfony/monolog-bundle": "^3.1",
    "symfony/orm-pack": "*",
    "symfony/process": "^4.0",
    "symfony/security-bundle": "^4.0",
    "symfony/security-csrf": "^4.0",
    "symfony/serializer-pack": "*",
    "symfony/swiftmailer-bundle": "^3.1",
    "symfony/translation": "^4.0",
    "symfony/twig-bundle": "^4.0",
    "symfony/validator": "^4.0",
    "symfony/web-link": "^4.0",
    "symfony/yaml": "^4.0",
    "tetranz/select2entity-bundle": "^3.0"
  },
  "require-dev": {
    "dama/doctrine-test-bundle": "^6.1",
    "doctrine/doctrine-fixtures-bundle": "^3.2",
    "pdepend/pdepend": "^2.5",
    "phpmd/phpmd": "^2.7",
    "phpunit/php-code-coverage": "^7.0",
    "roave/security-advisories": "dev-master",
    "squizlabs/php_codesniffer": "3.*",
    "symfony/debug-pack": "*",
    "symfony/maker-bundle": "^1.0",
    "symfony/phpunit-bridge": "^4.3",
    "symfony/profiler-pack": "*",
    "symfony/test-pack": "*",
    "symfony/web-server-bundle": "^4.0"
  },
  "config": {
    "preferred-install": {
      "*": "dist"
    },
    "sort-packages": true
  },
  "autoload": {
    "psr-4": {
      "App\\": "src/"
    }
  },
  "autoload-dev": {
    "psr-4": {
      "App\\Tests\\": "tests/"
    }
  },
  "replace": {
    "paragonie/random_compat": "2.*",
    "symfony/polyfill-ctype": "*",
    "symfony/polyfill-iconv": "*",
    "symfony/polyfill-php71": "*",
    "symfony/polyfill-php70": "*",
    "symfony/polyfill-php56": "*"
  },
  "scripts": {
    "auto-scripts": {
      "cache:clear": "symfony-cmd",
      "assets:install %PUBLIC_DIR%": "symfony-cmd"
    },
    "post-install-cmd": [
      "@auto-scripts"
    ],
    "post-update-cmd": [
      "@auto-scripts"
    ]
  },
  "conflict": {
    "symfony/symfony": "*"
  },
  "extra": {
    "symfony": {
      "allow-contrib": false,
      "require": "4.4.*"
    }
  }
}

Symfony 4 route annotations cause error with openapi annotations

$
0
0

Currently our project has Symfony 4.3 installed. We have grown since 2.7 so there may be some legacy garbage but overall our app works nicely. We have a flavoring system that gets prefixed to every route (if this is a good idea I dont know but it was like this when we started supporting it). So a link would look like this:

test.me/{flavor}/project/{UUID}

We are using annotations for the routing and therefore have an annotations.yaml:

controllers:
    resource: ../../src/App/Controller/
    type: annotation
    prefix:   /{flavor}/

Now since we want to introduce an API documentation we wanted to use this php package: https://github.com/zircote/swagger-php which lets us write annotations for our API as we do it with routes and generates a swagger.json that can be distributed to our connected projects. Problem is when writing the annotations this error pops up:

$:bin/console cache:clear -e dev                                

 // Clearing the cache for the dev environment with debug true                                           


In FileLoader.php line 166:

  [Semantical Error] The annotation "@OA\Schema" in class App\Controller\Api\Model\APIMessage  
   was never imported. Did you maybe forget to add a "use" statement for this annotation? in /config/routes/../../src/Catrobat/Controller/ (which is being imported from "/config/routes/annotations.yaml"). Make sure annotations are installed  
   and enabled. 

Any Idea how I can tell the framework to ignore this annotation in the file loader? swagger-php parses the files on its own so it dosent really care if this is imported or not. I also tried importing the Openapi Annotations but this did not work either. Any help into this is greatly appreciated!

Symfony 4, setup Rest API user management

$
0
0

I'm creating my first Symfony 4 Rest API, which will be connected to a AngularJS front website.

Until now I used FOSUserBundle to manage the users of my Symfony applications, but I don't know if it's really necessary for a full-api oriented app.

Do someone have a bundle usefull for API-oriented user management ? Or if I can manage everything easily with my own controllers/services ?

Moreover, when I try to install FOS UserBundle with composer "composer require fos/userbundle", i get the famous error message

The child node "db_driver" at path "fos_user" must be configured.

And then composer revert changes and cancel the bundle installation. I thought since Symfony 4, composer was automaticly creating configurations files.

Thanks

Updating symfony/symfony version in composer.json

$
0
0

Looking at the Symfony demo repository, I find it hard to discern exactly which package you would target in order to update the symfony package.

Take a look here: https://github.com/symfony/demo/blob/master/composer.json

In my previous project, there was a distinct symfony/symfony package, so it was pretty clear where to do it.

Right now, my app is on version 4.2.5. I tried updating the symfony version at the bottom under extras: https://github.com/symfony/demo/blob/master/composer.json then ran composer update symfony/symfony.

Result:

$ composer update symfony/symfony
Package "symfony/symfony" listed for update is not installed. Ignoring.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Restricting packages listed in "symfony/symfony" to "4.4.*"
Nothing to install or update

It's clear that there's been a change in procedure, and I'm sure there's docs for this somewhere, but I haven't been able to find it.

Run Server Symfony 4

$
0
0

I start developp an application web with framework symfony4 , I download composer

and for the server I use wampserver , and I alraeady hava php 7 on my pc.

i put composer in the path( variable system)

After creating my project with cmd, I Want to run my server

--> I write the cmd line: php bin/console server:run

but it show a message " Command:"server:run" is not defined  

Someone have a idea ?? Explain to me what happen , and what should I do ??


Sonata admin dashborad block that could list details

$
0
0

I have tried to integrate blocks which is displayed properly but i want to list the recent updates done on each block in my dashboard it self

Rest-bundle of Synfomy 4 requires config in 4.3 version, while Symfony 4 uses 5.0

$
0
0

Following this tutorial I tried to configure REST API on fresh new Symfony 4 install.

The first step in the tutorial is doing:

composer create-project symfony/skeleton rest_api_project

Followed by

composer require friendsofsymfony/rest-bundle

However, when I try to install friendsofsymfony/rest-bundle, I get:

Your requirements could not be resolved to an installable set of packages. Problem 1 - Installation request for friendsofsymfony/rest-bundle ^2.6 -> satisfiable by friendsofsymfony/rest-bundle[2.6.0]. - friendsofsymfony/rest-bundle 2.6.0 requires symfony/config ^3.4|^4.3 -> no matching package found.

So basically that this bundle requires symfony/config ^3.4|^4.3 while Symfony 4 uses 5.0.

How to make it work? And how this tutorial meant for Symfony 4 could even work when the friendsofsymfony/rest-bundle does not support config in 5.0 version?

Doctrine: Write SQL instead of executing

$
0
0

I want to try executing an SQL import job directly on the server instead of batch-importing it using doctrine (<4M rows).

Is there any configuration option in Doctrine to save/print the generated SQL instead of executing it directly?

I'am using Symfony 4.3, Doctrine 2.6.4

Optional trainling slash for optional slugs in POST route

$
0
0

I am using Symfony 4.2. When I set a route with an optional parameter, can I still use the route without a trailing slash?

api_post:
    path: /api/drive/{slug?}
    controller: App\Controller\Api::load
    methods: POST

My problem is, that the above route works WITH a trailing slash only. This is quite obvious, because I set this slash right after the word "drive" in the path. But how can I make the trailing slash optional too?

Access to images in the public directory with Symfony 4

$
0
0

In two Symfony 4 instances, I get different results with the same code. In a twig template, I have the line

<img src="{{  asset('images/DM_logo.jpg')}}"/>

In the online server, all works well: i get the image and the generated URL is /images/DM_logo.jpg for the absolute URL http://mysite.mydomain.com/images/DM_logo.jpg

But, locally, with the access to http://localhost/mysite/, the generated url is /mysite/images/DM_logo.jpg for the absolute url http://localhost/mysite/images/DM_logo.jpg which generate a NotFoundHttpException.

If i change the template to

<img src="{{  asset('public/images/DM_logo.jpg')}}"/>

it works locally but not online...

I doesn't find how to use the same code online and locally. Advices?

symfony4 handleRequest not working correctly with fileType in form

$
0
0

Im trying to validate my form, it has a fileType field in it. I use asserts to validate the form. The validation works correctly for all field except the fileType field. It is only allowed to upload jpg jpeg and png files, but if I try to upload for example a PDF file it says my form is valid.

This is the code of the field holding the filename in the db

/**
 * @ORM\Column(name="imgHomepage", type="string")
 * @Assert\File(
 *     maxSize = "1024k",
 *     mimeTypes = {"image/jpg", "image/jpeg", "image/png"},
 *     mimeTypesMessage = "Images must be  jpg,  jpeg or  png"
 * )
 */
private $imgHomepage = '';

This is the code of my fileType being added in the formtype of my entity

->add('imgHomepage', FileType::class, [
            'mapped' => false,
            'data_class' => null,
            'required' => false,
            'error_bubbling' => true
 ])

This is the code from my controller

$influencer = self::getInfluencerById($influencerId);
$influencerShowForm = self::CreateInfluencerForm($influencer);
$influencerShowForm->handleRequest($request);
if ($influencerShowForm->isSubmitted() && $influencerShowForm->isValid()) {
  // handle form
}

Duplicate insert with Symfony 4

$
0
0

I have a code/condition to getting chat between users like:

    $chat = $chatRepository->findChat($firstUser, $secondUser);
    if (!$chat) {
        $chat = new Chat();
        $chat->setSecondUser($secondUser);
        $chat->setFirstUser($firstUser);
        $entityManager->persist($chat);
        $entityManager->flush();
    } else {
        ...
    }

    return $chat;

So if chat entity between users does not exist I create it. Problem is that somehow from frontend arrived two requests of getting this chat with half of second difference and in database I got two same records:

  id first_user  second_user    time
   1       1           2      10:20:20
   2       1           2      10:20:21

Which is wrong. How can I solve it without unique indexes? Thank you

UPD: findChat function

public function findChat($userId, $otherUserId)
{
    $qb = $this->createQueryBuilder('u');

    $qb->where($qb->expr()->orX(
        $qb->expr()->andX(
            $qb->expr()->eq('u.firstUser', ':firstUser'),
            $qb->expr()->eq('u.secondUser', ':secondUser')
        ),
        $qb->expr()->andX(
            $qb->expr()->eq('u.firstUser', ':secondUser'),
            $qb->expr()->eq('u.secondUser', ':firstUser')
        )
    ));

    $qb->setParameter('firstUser', $userId);
    $qb->setParameter('secondUser', $otherUserId);
    $qb->orderBy('u.dateCreated', 'DESC');

    return $qb->getQuery()->getOneOrNullResult();
}

Symfony upgrade give me error from 4.1 to 4.4

$
0
0

I just made the migration from symfony 4.1 to 4.4 I have this error:

Argument 1 passed to App\EventListener\KernelRequestListener::__construct() must be an instance of Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage, instance of Symfony\Component\Security\Core\Authentication\Token\Storage\UsageTrackingTokenStorage given, called in C:\xampp\htdocs\chat-project-symfony\var\cache\dev\Container06Mjwya\srcApp_KernelDevDebugContainer.php on line 1130

While if you look at my KernelRequestListener :

<?php

namespace App\EventListener;

use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
//..

class KernelRequestListener
{
    private $tokenStorage;

    /**
     * KernelRequestListener constructor.
     * @param TokenStorage $tokenStorage
     * ...
     */
    public function __construct(TokenStorage $tokenStorage/*...*/)
    {
        $this->tokenStorage = $tokenStorage;
        //..
    }
}

Here is my config/services.yaml file:

#...
services:
  #..
  App\EventListener\KernelRequestListener:
    arguments: [ '@security.token_storage' ]
    tags:
    - { name: kernel.event_listener, event: kernel.request }
    - { name: kernel.event_listener, event: kernel.response }

I don't know why symfony tell me that I'm using Symfony\Component\Security\Core\Authentication\Token\Storage\UsageTrackingTokenStorage while it's clearing written Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage

I already tried to clear the cache folder and also delete the cache folder and it didn't change.

How can I fix this ?

Thank you

Is it possible to use function on different classes in Symfony 4?

$
0
0

I was planning to use different entities for my project. And I created an entity project and entity users. I need to get all rows from every table, therefore I used:

return $this->getDoctrine()->getRepository(project::class)->findAll();

But soon, I will be working with different entities and I would like to create a function that will take in the entity name and fetch all rows:

private function ConnDB($table)
    {
       return $this->getDoctrine()->getRepository($table::class)->findAll();
    }

But I have different problems with this code. How to do it?

Symfony 4 - Default value form not working

$
0
0

I have a little problem I don't understand. I want to display my errors in the same location at the top of the form, I used form_errors(form)

Then in my form, I added a default value to my fields.

        

$resolver->setDefaults([
    'data_class' => Whitelist::class,
    'error_bubbling' => true
]);

Currently, it does not work and my errors appear in their respective fields.

But if I put this option 'error_bubbling' => true to my field, it works. Why by default it does not work?

->add('firstName', null, [
     'label' => "Prénom de votre personnage",
     'error_bubbling' => true
])

Sorry for my english, thanks.

Retrieve and display the values of a form

$
0
0

This is not a question but I would like to share my experience regarding value recovery and its poster. I hope this little piece of code can help more than one.

Here's how I did it:

{{ form.vars.value.Age}} #Allows you to display the value of the field: anneeDeNaissance

Here is an example of a (functional) condition :

{%  if form.vars.value.anneeDeNaissance >= 700 %}
    <h2> test </h2>
{%  endif %}

Documentation : https://symfony.com/doc/4.1/reference/forms/twig_reference.html

If you have any suggestions regarding the code, do not hesitate. This is the first time I've done this kind of post

Password validation in controller Symfony4

$
0
0

I would like an advice. I work on Symfony 4.

I need to check in my controller if the password got an uppercase letter, a number, a special character and if the length is 8 characters minimum. I already do the checking in my twig by adding the regex in the attribute of the input.

I don't know if I must take the string and check for each letter.

Do you know a better way to do it?

Thanks.

Viewing all 3916 articles
Browse latest View live


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