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

Api platform - invalid IRI instead of validation error

$
0
0

I'm using API platform for my booking application.

Booking has many to 1 relationship with a department.

When I create a new booking by sending a POST request with an empty string as a value for the department I am expecting a validation error but instead, I got 'invalid IRI'

Booking entity

/**
 * @ApiResource(
 *      itemOperations={
 *          "get"={
 *              "normalization_context"={
 *                  "groups"={"read-item"}
 *              }
 *          },
 *          "put"={
 *              "denormalization_context"={
 *                  "groups"={"put"}
 *              }
 *          }
 *    }
 * @ORM\Entity(repositoryClass="App\Repository\BookingRepository")
class Booking
{
    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Department", inversedBy="bookings")
     * @ORM\JoinColumn(nullable=false)
     * @Assert\NotBlank
     * @Groups({"read-item", "put"})
     */
    private $department;
}

Department entity

/**
 * @ApiResource(
 *     collectionOperations={"get"},
 *      itemOperations={"get"}
 * )
 * @ORM\Entity(repositoryClass="App\Repository\DepartmentRepository")
 */
class Department
{
    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Booking", mappedBy="department")
     */
    private $bookings;
}

e.g sample request to create a booking (POST)

{
  "department": ""
}

Error:

{
    "@context": "/api/contexts/Error",
    "@type": "hydra:Error",
    "hydra:title": "An error occurred",
    "hydra:description": "Invalid IRI \"\".",
    "trace": [
        {
            "namespace": "",
            "short_class": "",
            "class": "",
            "type": "",
            "function": "",
            "file": "/var/www/html/vendor/api-platform/core/src/Serializer/AbstractItemNormalizer.php",
            "line": 418,
            "args": []
        },
        {
            "namespace": "ApiPlatform\\Core\\Serializer",
            "short_class": "AbstractItemNormalizer",
            "class": "ApiPlatform\\Core\\Serializer\\AbstractItemNormalizer",
            "type": "->",
            "function": "denormalizeRelation",
            "file": "/var/www/html/vendor/api-platform/core/src/Serializer/AbstractItemNormalizer.php",
            "line": 685,
            "args": [
                [
                    "string",
                    "department"
                ],
                [
                    "object",
                    "ApiPlatform\\Core\\Metadata\\Property\\PropertyMetadata"
                ],
                [
                    "string",
                    "App\\Entity\\Department"
                ],
                [
                    "string",
                    ""
                ],
                [
                    "string",
                    "json"
                ],
                [
                    "array",
                    {
                        "operation_type": [
                            "string",
                            "collection"
                        ],
                        "collection_operation_name": [
                            "string",
                            "post"
                        ],
                        "api_allow_update": [
                            "boolean",
                            false
                        ],
                        "resource_class": [
                            "string",
                            "App\\Entity\\Department"
                        ],
                        "input": [
                            "null",
                            null
                        ],
                        "output": [
                            "null",
                            null
                        ],
                        "request_uri": [
                            "string",
                            "/api/bookings"
                        ],
                        "uri": [
                            "string",
                            "http://localhost/api/bookings"
                        ],
                        "skip_null_values": [
                            "boolean",
                            true
                        ],
                        "api_denormalize": [
                            "boolean",
                            true
                        ],
                        "cache_key": [
                            "string",
                            "db505854694e53aec6831eb427a03028"
                        ]
                    }
                ]
            ]
        }, 
}

Please advise if I'm missing something


Denormalizer on MongoDb Embedded Document in Symfony API Platform

$
0
0

I am attempting to run a denormalizer (data in) on an embedded mongodb document with Symfony 4.4 using the Api Platform bundle. This works as expected for normalization (data out), but for the denormalization process nothing is fired on the embedded data, just on the parent data.

If this is the way it works, then I may need to move the logic for denormalization into the parent. Or perhaps I am just doing something wrong. What I am attempting to accomplish is throw exceptions on inbound requests that contain fields which have been deprecated. The classes which parse the annotations and scan the attributes works as expected, its just determining where to plug it in and I was hoping the denormalization process on embedded documents would work.

Here is my services.yaml:

'App\Serializer\InvestmentNormalizer':
    arguments: [ '@security.authorization_checker' ]
    tags:
        - { name: 'serializer.normalizer', priority: 64 }
'App\Serializer\InvestmentDenormalizer':
    tags:
        - { name: 'serializer.denormalizer', priority: 64 }
'App\Serializer\ProjectNormalizer':
    tags:
        - { name: 'serializer.normalizer', priority: 64 }
'App\Serializer\ProjectDenormalizer':
    tags:
        - { name: 'serializer.denormalizer', priority: 64 }

Then my denormalizer class which never gets executed:

class ProjectDenormalizer implements DenormalizerInterface
{
    private const ALREADY_CALLED = 'PROJECT_DENORMALIZER_ALREADY_CALLED';

    public function denormalize($data, $class, $format = null, array $context = [])
    {
        $context[self::ALREADY_CALLED] = true;

        return $this->removeDeprecatedFields($data);
    }

    public function supportsDenormalization($data, $type, $format = null)
    {
        if (isset($context[self::ALREADY_CALLED])) {
            return false;
        }

        return $type == get_class(new Project());
    }

    private function removeDeprecatedFields(array $normalizedData) : array
    {
        $apiPropertyReader = new AnnotationReader(Project::class, ApiProperty::class);
        $deprecatedProperties = $apiPropertyReader->readAllHavingAttribute('deprecationReason');

        $errors = [];

        foreach (array_keys($deprecatedProperties) as $deprecatedPropertyName) {

            if (!isset($normalizedData[$deprecatedPropertyName])) {
                continue;
            }

            $errors[] = $deprecatedPropertyName . ' has been deprecated';
        }

        if (!empty($errors)) {
            throw new DeprecatedFieldException(implode('. ', $errors));
        }

        return $normalizedData;
    }
}

Virtual hosts configuration with Symfony

$
0
0

I have a problem with my virtual host on WAMP server. I tested projects that I worked on before, and they all work.

When I hit my localhost name of the project

127.0.0.1 project.local

defined in my hosts file, it returns

This page isn’t working

It's my first Symfony 4 project and I think my virtual hosts configuration may not be right.

This is my project skeleton:

iproject-skeleton-image

And my virtual host config:

<VirtualHost *:80>
     ServerName project.local
     DocumentRoot "${INSTALL_DIR}/www/project/public"
     SetEnv APPLICATION_ENV "development"<Directory "${INSTALL_DIR}/www/project/public/">
           AllowOverride All
           Order Allow,Deny
           Allow from All
           <IfModule mod_rewrite.c>
             Options -MultiViews +FollowSymlinks
               RewriteEngine On
               RewriteCond %{REQUEST_FILENAME} !-f
               RewriteRule ^(.*)$ index.php [QSA,L]
           </IfModule>
       </Directory>
     </VirtualHost>

Symfony Codeception functional test: environment variable not found

$
0
0

I'm using Codeception v2.4.1 with PHPUnit 7.1.3 in a new Symfony 4 project.

I created a functional test, and attempt to run it, and receive an error: ./vendor/bin/codecept run functional

There was 1 error:

---------
1) CustomerControllerCest: Customers on index
 Test  tests/functional/Controller/Internal/CustomerControllerCest.php:customersOnIndex

  [Symfony\Component\DependencyInjection\Exception\EnvNotFoundException] 
Environment variable not found: "CORS_ALLOW_ORIGIN".

I have a phpunit.xml file that has this environment configured:

<php>
        <ini name="error_reporting" value="-1" />
        <env name="KERNEL_CLASS" value="App\Kernel" />
        <env name="APP_ENV" value="test" />
        <env name="APP_DEBUG" value="1" />
        <env name="APP_SECRET" value="191a5940854807ee081eaa57aff30562" />
        <env name="SHELL_VERBOSITY" value="-1" />
        <!-- define your env variables for the test env here -->
        <env name="CORS_ALLOW_ORIGIN" value="^https?://localhost:?[0-9]*$" />
    </php>

I also tried using .env.test, and included this same variable:

CORS_ALLOW_ORIGIN=^https?://localhost:?[0-9]*$

I checked in functional.suite.yml and my environment is set to test:

actor: FunctionalTester
modules:
    enabled:
        - Symfony:
            app_path: 'src'
            environment: 'test'
            em_service: ‘doctrine.orm.entity_manager’
#        - Doctrine2:
#            depends: Symfony
        # add a framework module here
        - \Helper\Functional

Not sure where the issue is. Is there an additional config where I tell codeception where to look for these environment variables?

Symfony 4 OneToOne relationship not pulling from database

$
0
0

This issue is so weird!

Example structure of entities relating to each other:

Property -> InstructionToSell (OneToOne) -> acceptedOffer (OneToOne)

If I do something like:

$property = $repo->findOneBy([‘id’=> 1]);

It works, all the relationships come back ok.

But now if I create a custom method in the property repo to search postcode with a LIKE query the acceptedOffer relationship is null

It’s confusing me as to why this is happening? It’s the same entity, same relationships, I’m just loading it via a like instead of directly by Id.

Even if I use fetchAll it works fine.

I hope I explained this well enough it’s difficult to explain what I’m seeing.

Symfony forms : Set an embedded field to null

$
0
0

Hy,

I'm on Symfony with MongoDb. I have a problem when I want update a document. This one has an embedded field. If I give it a not null value on POST, I can't update it to null when I patch.

When I POST :

"destination": {
  "address1": "my address"
}

I have a good response :

"destination": {
  "address1": "my address"
}

But when I want PATCH to null :

"destination": null

I always have :

"destination": {
  "address1": "my address"
}

For PATCH I use Form Builder with my own FormType, I have this :

->add('destination', DestinationType::class, [
   'required' => false,
])

And it's Ok for not embedded fields

Thank's

Using the resolve operator in the Symfony config env() helper

$
0
0

This article introduces type-casting and some convenient operators which can be used inside the env() helper in the Symfony configs. Everything's clear except the resolve: operator. The article says:

The resolve: operator replaces container parameter names by their values:

What I am going to have the parameters whose names are taken from the values of the env variables? What's the point?

It's used in the doctrine bundle's config, for example:

dbal:
    # configure these for your database server
    driver: 'pdo_mysql'
    server_version: '5.7'
    charset: utf8mb4

    # With Symfony 3.3, remove the `resolve:` prefix
    url: '%env(resolve:DATABASE_URL)%'

I was googling the issue, but it's almost no info on the Internet, and it doesn't clarify anything to me.

Symfony 4: files in environment folders suddenly not executed anymore

$
0
0

I am a relative symfony beginner, I have a strange effect of the files in environment folders suddenly not being executed anymore. I did seemingly nothing out of the ordinary, I rely on these files like /config/packages/test/services.yaml but suddenly all contents are not found/available anymore as if they didn't exist. I tried to place my files in all different environment folders dev, prod, test, ect to find out if the env variable has suddenly changed but it doesn't make a difference.

Can anyone point me to the spot where symfony includes these files, so I can debug this behaviour? Thank you very much in advance!


Symfony: Validate array of models before group persist

$
0
0

I had group of objects which extends abstract class. I validate it in models. When I insert it one by one its everything ok, but now i wanna add possibility to import it from files. I had all logic to it but I had problem with validation because each type of object has different validation options. For example object A has properties name, type, speed max, speed min, intenstity another object B has properties name, type. In each model I had Assertions, but some of them base on that what is in database. For example if object in database had type: Movement, name: Running and intensity: "Fast" each new object with the same type and name cannot had the same intensity. The problem is that if I try insert few rows in one time each of model itself pass validate with db entities but in array of models can be 2, 3 or maybe more new models which has the same type, name and intensity. If persist and flush them one by one it works fine but if I wanna persist it by group like that:

$batchSize = 10;
$i = 1;
foreach ($activities as $activity) {
    $entityManager->persist($activity);
    if (($i % $batchSize) === 0) {
        $entityManager->flush();
        $entityManager->clear();
    }
++$i;
}
$entityManager->flush();

It can be group of the same objects which will be inserted to db. I know the problem is simple I validate in model by searching in db another object with the same properties, but persisted object it's not in db yet so each next in group not flushed objects can pass validation before insert to db. I think about few possibilities to fix that problem: First one is push models to db one by one but it's can be performance issue when user wanna insert really big piece of data in one file. Second one is create ArrayCollection of models and try validate it by Collection Assert and this sounds best to me. Third option is create validator service for arrays of models and there get values of properties and check just values from models in array.

But maybe it is another option to resolve that problem?? Thanks a lot for any ideas :)

Sonata admin sortabe listing, fields are blank

$
0
0

Im trying to make a simple sortable system on one of my tables in the sonata admin bundle, i have followed this tutorial (https://symfony.com/doc/master/bundles/SonataAdminBundle/cookbook/recipe_sortable_listing.html#the-recipe) and yet Im not capable of doing it.

I have followed each of the steps carefully but on my admin table i can only see a blank action field, no arrows in it.

I have searched and searched throught articles but am not having any success, i feel like im very close to figure it out.

Here is my src/Entity/Podcast.php file

/**
* @Gedmo\SortablePosition
*@ORM\Column(name="position", type="integer")
*/
private $position;

//getters and setters 

public function setPosition($position)
{
  $this->position = $position;

  return $this;
}

public function getPosition()
{
  return $this->position;
}

As far as i know my entity file is just fine

my services.yaml file

  //Gedmo
  gedmo.listener.sortable:
    class: Gedmo\Sortable\SortableListener
    tags:
      - { name: doctrine.event_subscriber, connection: default }
    calls:
      - [ setAnnotationReader, [ "@annotation_reader" ] ]

//podcast admin
admin.podcast:
  class: App\Admin\PodcastAdmin
  tags:
    - name: sonata.admin
      manager_type: orm
      label: 'Programa'
      show_mosaic_button: true
  arguments:
    - ~
    - App\Entity\Podcast
    - 'PixSortableBehaviorBundle:SortableAdmin'
  calls:
     - [ setPositionService, ['@pix_sortable_behavior.position']]

my stof_doctrine_extension.yaml file

stof_doctrine_extensions:
default_locale: en_US
orm:
  default:
    sortable: true

And last but not least, my PodcastAdmin.php file

protected function configureRoutes(RouteCollection $collection)
{
  $collection->add('move', $this->getRouterIdParameter().'/move/{position}');
}

protected function configureListFields(ListMapper $listMapper) {
    $listMapper
    ->add('id')
    ->addIdentifier('title')
    ->add('description')
    ->add('author.name')
    ->add('_action', null, [
      'actions' => [
        'move' => [
          'template' => '@App/Admin/_sort.html.twig',
        ],
      ],
    ]);
}

As it right now im getting the following error There are no registered paths for namespace "App" in @SonataAdmin/CRUD/list__action.html.twig at line 17.

And if i switch the temmplate value to @PixSortableBehavior/Default/_sort.html.twig, im able to see the page but the action field is all blank, there are no arrows

In Symfony 4,The server returned a "500 Internal Server Error"

$
0
0

Using Symfony 4. In my local environment everything is okay, but in production server it is showing the following error,

The server returned a "500 Internal Server Error". Something is broken. Please let us know what you were doing when this error occurred. We will fix it as soon as possible. Sorry for any inconvenience caused.

try to clean the production server cache, but it does not work. Do not have any ideahow to resolve this issue. Colud anyone please help to solve this issue?

How to add the input username in fosCommentBundle without fosUser?

$
0
0

I want to add the Username field (input) in bundle FOSCommentBundle without using FOSUserBundlde.

the user must enter his username and comment. The basic model does not offer the pseudo field because it relies on the connected user or "anonymous" if no connected user.

Can you tell me how to do this?

Symfony 4.4

Thank's

Symfony 4 is painfully slow in DEV

$
0
0

I try to run a simple Symfony 4 project on a docker container. I have tested regular PHP scripts, and they work very well. But, with Symfony project, the execution gets ridiculously slow. For example, a page without any significant content takes 5-6 seconds.

I have attached the screenshots from Symfony's performance profiler.

Screenshot1Screenshot2Screenshot3Screenshot4

Do you have any idea what how to reduce this execution time to an acceptable level?

How to change parent entity on inherited entity in Symfony4 Doctrine

$
0
0

I have multiple entity type which extends each other in order to create my model. In my application I need to manage Interimaries, Employes and Users.

An Interimary is working in a company, as is an Employe. A user in an Employe of my application with an access to the application.

My model is defined as follow :

Worker :

<?php

/**
 * @ORM\Entity(repositoryClass="App\Repository\User\WorkerRepository")
 * @ORM\Table(name="usr_worker")
 * @ORM\InheritanceType("JOINED")
 * @ORM\DiscriminatorColumn(name="discr", type="string")
 * @ORM\DiscriminatorMap({"worker" = "Worker", "employe" = "Employe", "interimary" = "Interimary", "user" = "User"})
 */
class Worker
{
    private $id;
}

Interimary :

<?php

/**
 * @ORM\Entity(repositoryClass="App\Repository\User\InterimaryRepository")
 * @ORM\Table(name="usr_interimary")
 */
class Interimary extends Worker{}

Employe :

<?php

/**
 * @ORM\Entity(repositoryClass="App\Repository\User\EmployeRepository")
 * @ORM\Table(name="usr_employe")
 */
class Employe extends Worker{}

User :

<?php

/**
 * @ORM\Entity(repositoryClass="App\Repository\User\UserRepository")
 * @ORM\Table(name="usr_user")
 * @Gedmo\SoftDeleteable(fieldName="deletedAt", timeAware=false)
 * @ORM\HasLifecycleCallbacks()
 */
class User extends Employe implements UserInterface
{
    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    private $username;


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

All my authentication logic is in my User class. The logic of my application is that when a user first login, he must select in a dropdown the Employe he is attached to.

Problem : So I have an Employe entity and a User entity I want to "merge" when the user select the employe.

Solution ? : My first idea was to change the User ID to fit my Employe ID, and then delete the old User's Employe but this is not working. I'm not sure the approach is bad but I have no idea about what is not working with this method.

/**
 * @Route("/user/linkemploye", name="user_employe_link")
 */
public function linkUserEmploye(Request $request)
{
    $user       = $this->getUser();
    $employes   = $this->employeRepository->findUnlincked();

    if($request->isMethod('POST')){

        $idEmploye = $request->request->get('employe');

        $employe        = $this->employeRepository->find($user->getId());
        $intoEmploye    = $this->employeRepository->find($idEmploye);

        $this->mergeEmployes($employe, $intoEmploye);

        $user->setUserLincked(true);

        $em = $this->getDoctrine()->getManager();
        $em->persist($user);
        $em->flush();

        return $this->redirectToRoute('app_homepage');
    }

    return $this->render('app/users/security/UserEmployeLink/userEmployeLink.html.twig', [
        "employes" => $employes
    ]);
}

public function mergeEmployes(Employe $employe, Employe $intoEmploye){
    //How to properly merge my 2 entities ?
}

Symfony 4 : How to make an eventListener

$
0
0

Now I'm training on event management on Symfony.

So far everything is going well!

I have the following code:

When a user connects to the application, a listerner detects the connection event and updates the last_login_at field in bdd

So far all is going well.

The problem appears when the user wants to log out.

Indeed, when disconnected, the listener's onSecurityAuthenticationSuccess method is always called.

Problem once disconnected we can no longer recover a user (in the session)

Consequence: that bug!

 What I would like:

It is able to record the date of the last connection in the database called the onSecurityAuthenticationSuccess method only on login and not on login and logout In addition I have an is_in_line field in the database and I would like to disconnect, I can detect the event "disconnection" and update this field How can I do this?

Here is my code to list it

public function onSecurityAuthenticationSuccess (AuthenticationEvent $ event) {
     $ user = $ event-> getAuthenticationToken () -> getUser ();
     if ($ user) {
             // dd ($ user);
        $ user-> setLastLoginAt (new \ Datetime ('now'));
         $ this-> em-> persist ($ user);
        $ this-> em-> flush ();
    }
}

symfony 4.4 : datetime must be a string?

$
0
0

I migrated a project from Symfony 3.4 to Symfony 4.4 (back side with API platform)

In an entity I have a date field, which is automatically generated on today's date, So when I make a POST or a PUT, she is not in my JSON

/**
     * @Groups({"get_logement", "post_logement", "put_logement"})
     * @ORM\Column(type="datetime", nullable=false)
     * @Assert\Date(message="the date is not correct.")
     */
    private $dateEtat;
public function getDateEtat(): ?\DateTimeInterface
    {
        return $this->dateEtat;
    }

    public function setDateEtat(?\DateTimeInterface $dateEtat): self
    {
        $this->dateEtat = $dateEtat;

        return $this;
    }

and a construct :

public function __construct()
    {
        $this->dateEtat = new \Datetime();
    }

since version 4.4 when I do a POST or a PUT, I get this error

"type": "https://tools.ietf.org/html/rfc2616#section-10",
  "title": "An error occurred",
  "detail": "dateEtat: Cette valeur doit être de type string.",
  "violations": [
    {
      "propertyPath": "dateEtat",
      "message": "This value must be of type string."
    }
  ]

Symfony 4 redirect 404 error to my controller

$
0
0

I'm trying to catch the 404 error and redirect it to custom controller, so I could get some data from database. I find this article https://symfony.com/doc/4.4/controller/error_pages.html

and overide custom 404 page by creating structure templates/bundles/TwigBundle/Exception/error404.html.twig

but in that case it is imposible to load data from database to 404 page. Is it possible to do what I'm asking???

CKFinder error when browsering (Symfony4 + EasyBundle + CKEditor)

$
0
0

Here's my stack :

  • Symfony4
  • EasyAdmin
  • Webpack
  • FOSCkEditor
  • CKFinder

And here's my problem :

I got a form with a WYSIWYG field, and when I click on the "Image" icon, a popup open with all the properties of the image (size, alt, border, link, etc.). As I installed the Symfony bundle "ckfinder", there's now a new button "Browser".

When I click on the button, a new window open, calling this URL :

/bundles/cksourceckfinder/ckfinder/ckfinder.html?CKEditor=article_content&CKEditorFuncNum=1&langCode=fr

And here's the error I get :

No route found for "GET /bundles/cksourceckfinder/ckfinder/core/connector/php/connector.php" (from "http://192.168.2.1:8000/bundles/cksourceckfinder/ckfinder/ckfinder.html?CKEditor=article_content&CKEditorFuncNum=1&langCode=fr")

I followed the documentation but I think I missed something.

There is no file name connector.php in my code, should I create it ?

Here's my configuration for fosckeditor :

twig:
    form_themes:
        - '@FOSCKEditor/Form/ckeditor_widget.html.twig'

fos_ck_editor:
    default_config: default
    configs:
        default:
            toolbar: full      
            fullscreen: true

And ckfinder's configuration :

ckfinder:
    connector:
        authenticationClass: App\CustomCKFinderAuth\CustomCKFinderAuth

Do I need to create a route ? A new template ? I'm stuck.

Please, if you know how to deal with this, help me !

Thanks and take care.

How to start a Symfony server with environment variables from .env.test?

$
0
0

Is there any way to start the build in server with environment variables like DATABASE_URL from other environments like .env.test instead of .env?

I want to use diffrent databases for dev and test but the Symfony server allways starts using dev.

I already tried stuff like:

APP_ENV=test bin/console server:start

Im using symfony4

How to listen to the log out event to record the event on the database?

$
0
0

When a user connects to the application, a listener detects the connection event and updates the last_login_at field for the user.

The problem appears when the user wants to log out.

When disconnected, the listener's onSecurityAuthenticationSuccess method is always called.

Problem once disconnected we can no longer recover a user (in the session)

What I would like is to be able to record the date of the last connection in the database called the onSecurityAuthenticationSuccess method only on login and not on login and logout.

In addition I have an is_in_line field in the database and I would like to disconnect, I can detect the event "disconnection" and update this field How can I do this?

Here is my code to list it

public function onSecurityAuthenticationSuccess (AuthenticationEvent $ event) {
     $ user = $ event-> getAuthenticationToken () -> getUser ();
     if ($ user) {
             // dd ($ user);
        $ user-> setLastLoginAt (new \ Datetime ('now'));
         $ this-> em-> persist ($ user);
        $ this-> em-> flush ();
    }
}
Viewing all 3917 articles
Browse latest View live