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

Normalize virtual property with API Platform

$
0
0

I'm trying to return a virtual property with API Platform, but the only thing that I can get is the IRI.

I have multiple User, linked to multiple Organization. Those Organization have only one "Owner" (User class).

I want a property named "coach" which return the Owner of the first Organization

The case is a bit more complex but I simplified it.

App\Entity\User

/**
 * @ApiResource(
 *      itemOperations={
 *          "get"={"security"="is_granted('view', object)"},
 *      },
 *      normalizationContext={"groups"={"user", "user:read"}},
 *      denormalizationContext={"groups"={"user", "user:write"}}
 * )
 * @ORM\Table(name="user")
 */
class User extends BaseUser
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    protected $id;

    /**
     * @Groups({"user"})
     */
    protected $email;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Groups({"user"})
     */
    private $firstName;

    /**
     * @ApiProperty()
     * @Groups({"user"})
     */
    private $coach;

    /**
     * User constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->organizations = new ArrayCollection();
    }

    [...]

    public function getCoach(): ?User
    {
        $coach = null;
        if (count($this->getOrganizations()) > 0) {
            $coach = $this->getOrganizations()->first()->getOwnerUser();
        }

        return $coach;
    }
}

I still getting

{
    email: xxx;
    firstName: xxx;
    organizations: [
       {
          name: xxx;
       },
       {
          name: xxx;
       }
    ],
    coach: "/api/users/4"
}

and I would like a proper User like

{
    email: xxx;
    firstName: xxx;
    organizations: [
       {
          name: xxx;
       },
       {
          name: xxx;
       }
    ],
    coach: {
       email: xxx;
       firstName: xxx;
    }
 }

Empty project symfony + mongo: Attempted to load interface CommandSubscriber in index page

$
0
0

I have a problem with the Symfony 4 project from MongoDB

Empty project Symfony + mongo = Attempted to load interface CommandSubscriber in index page Symfony after installation

error:

Attempted to load interface "CommandSubscriber" from namespace "MongoDB\Driver\Monitoring". Did you forget a "use" statement for another namespace?

doctrine/mongodb-odm                2.0.5  
doctrine/mongodb-odm-bundle         4.1.0  
mongodb/mongodb                     1.5.2

php-mongodb                      1.6.1-1+0~20191219.12+debian10~1.gbpe14612  

mongo 3.6.17

how to fix it?

Match URL using Regex

$
0
0

I use following regex pattern in PHP (Symfony framework) to match URL

^/api/v1/account/verify
^/api/v1/account/register
^/api/v1/account/forgot-password

I now have a following URL

/api/v1/payment/{token}/success/jJBePenWo0eN

{token} will consist of dynamic values, but string "jJBePenWo0eN" will always be static how do I make a match that will satisfy the above URL?

Update: 1

I am looking for something like this

^/api/v1/payment/[a-zA-Z0-9]/success/jJBePenWo0eN

However this is not working

How to add Radio Button in Symfony Form

$
0
0
 //RamsurathType.php 
 use Symfony\Component\Form\Extension\Core\Type\RadioType;  
 //...
 ->add('Gender',RadioType::class,array(
    'choices'=>[
        'Male'=>'Male',
        'Female'=>'Female'
    ]
 ));

Hi all I'm new to symfony. Today i created a symfony Form using php bin/console make:form . After that i created a Form Type(Ramsurath Type.php) and Entity with(Firstname,Lastname,Email,Gender,Phone) Text Fields except phone. Output form is working (Using CRUD function). Now i want to change the Gender field in Radio button type. for that i changed my code in Ramsurath Type.php I got error while run the program.Please Help to resolve the error... Thanks ..

How to validate embedded form property before main form properties?

$
0
0

What do I have: EasyAdmin form for MyEntity with embedded type EmbeddedType.

easy_admin:
    entities:
        MyEntity:
            new:
                fields:
                    # other MyEntity fields
                    - { property: embedded_property, type: Namespace\EmbeddedType }

Namespace\EmbeddedType:

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => EmbeddedEntity::class,
            'factory' => EmbeddedEntity::class,
            'validation_groups' => new GroupSequence(['test'])
        ]);
    }

Namespace\EmbeddedEntity:

    public function __construct(string $someString)
    {
        $this->someString = $someString;
    }

    //...

    public function getGroupSequence()
    {
        return ['test'];
    }

validation.yaml:

Namespace\MyEntity:
    group_sequence:
        - test
        - MyEntity

Namespace\MyEntity:

    public function __construct(/* other fields */, EmbeddedEntity $embedded)
    {
        /* other fields */
        $this->embedded = $embedded;
    }

My problem: I can't make it to validate EmbeddedEntity first, even having that group_sequence.
As a result:

  1. if I don't fill embedded_property's someString field...
  2. EmbeddedEntity is not instantiated because of someString type mismatch (null instead of string)...
  3. I get exception on MyEntity::__construct() because of second argument type mismatch (null instead if EmbeddedEntity).

Stack trace from Symfony profiler is like

    /path/to/the/EmbeddedEntity.php {▼
      › 
      › public function __construct(string $someString)
      › {
    }
    .../vendor/sensiolabs-de/rich-model-forms-bundle/src/Instantiator/ObjectInstantiator.php:63 {▼
      › if (\is_string($this->factory)) {
      ›     return new $this->factory(...$arguments);
      › }
      arguments: {▼
        $someString: null
      }
    }

What have I tried: adding Valid constraint to validation.yaml:

Namespace\MyEntity:
    group_sequence:
        - test
        - MyEntity
    properties:
          embedded_property:
              - Valid: ~

but it didn't help. constraints value, related to embedded_property, was still an empty array, according to Symfony profiler.

I'm using Symfony 4.3.2.

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?

Problem with exporting data to excell with Symfony 4

$
0
0

I have a problem .I want to export my data book from my database to excell with symfony. I tried to use phpSpreadSheet . My function works but just for one value(the last value).I don't understand why I can't retrieve all my values.If you have any idea , it will be great.

/** * @Route("/create",name="createE") * * */

public function createSpreadsheet(){
    $this->allExcel();
    return $this->render('admin/book/sendExcelOk.html.twig');


}
public function allExcel(){

    $books =$this->getDoctrine()->getRepository(Book::class)->findAll();
    $spreadsheet = new Spreadsheet();

    $sheet = $spreadsheet->getActiveSheet()->setTitle('Export Books');

    $sheet->setCellValue('C1', 'Book')->mergeCells('C1:D1');
    $columnNames = [
        'Title',
        'Author',
        'PublicationDate',
        'Format',
        'Language'
    ];
    $columnLetter = 'A';
    foreach ($columnNames as $columnName) {
        // Allow to access AA column if needed and more
        $columnLetter++;
        $sheet->setCellValue($columnLetter.'3', $columnName);
    }


    foreach ($books as $book) {
        $columnValues = [
            [$book->getTitle(),
            $book->getAuthor(),
           $book ->getPublicationDate(),
           $book->getFormat(),
           $book->getLanguage()],

        ];
    }

    $i = 4; // Beginning row for active sheet
    $columnLetter = 'A';
    foreach ($columnValues as $columnValue) {

        foreach ($columnValue as $value) {
            $columnLetter++;
            $sheet->setCellValue($columnLetter.$i, $value);

        }
        $i++;

    }

    $writer = new Xlsx($spreadsheet);
    $nombre =Book::$nombreExcell++;
    $name ="Book ".$nombre;
    $writer->save($name.'.xlsx');
    return $spreadsheet;

}

Sylius: Additional checkout step missing listener

$
0
0

I want to add a checkout step to the sylius checkout process. It's working in the sense that when I am at cart overview and click checkout my added step is shown. But when I click "Next" I am getting an error "Unable to generate a URL for the named route “sylius_order_index” as such route does not exist."

What I did so far (for now to avoid distraction I called my checkout step "test"):

config/packages/_sylius.yaml:

winzou_state_machine:
    sylius_order_checkout:
        states:
            test_selected: ~ 
        transitions:     
            select_test:
                from: [cart, test_selected, addressed, shipping_selected, shipping_skipped, payment_selected, payment_skipped]
                to: test_selected
            address:
                from: [cart, test_selected, addressed, shipping_selected, shipping_skipped, payment_selected, payment_skipped]
                to: addressed
            select_shipping:
                from: [addressed, test_selected, shipping_selected, payment_selected, payment_skipped]
                to: shipping_selected
            select_payment:
                from: [payment_selected, test_selected, shipping_skipped, shipping_selected]
                to: payment_selected           
        callbacks:
            after:
                sylius_process_cart:
                    on: ["select_shipping", "address", "select_payment", "skip_shipping", "skip_payment", "select_test"]
                    do: ["@sylius.order_processing.order_processor", "process"]
                    args: ["object"]

sylius_shop:
    product_grid:
        include_all_descendants: true
    checkout_resolver:
        route_map:
            cart:
                route: sylius_shop_checkout_test
            test_selected:
                route: sylius_shop_checkout_address

routes/Checkout/checkout.yml:

sylius_shop_checkout_start:
    path: /
    methods: [GET]
    defaults:
        _controller: FrameworkBundle:Redirect:redirect
        route: sylius_shop_checkout_test

sylius_shop_checkout_test:
    path: /test
    methods: [GET, PUT]
    defaults:
        _controller: sylius.controller.order:updateAction
        _sylius:
            event: test
            flash: false
            template: "Checkout/Test/test.html.twig"
            form:
                type: App\Form\TestType
            repository:
                method: findCartForAddressing
                arguments:
                    - "expr:service('sylius.context.cart').getCart().getId()"
            state_machine:
                graph: sylius_order_checkout
                transition: select_test
#after this all other states as they are in native Sylius in this file. The original checkout.yml is completely overridden with this one.

I followed the compiler in MY as opposed to NATIVE checkout steps and the difference is that in

Bundle/Controller/ResourceController.php line 311:

    $postEventResponse = $postEvent->getResponse();
    if (null !== $postEventResponse) {
        return $postEventResponse;
    }

the Response object is null (thereby the if is not gotten into and the compiler moves on generating the arbirary/misleading error message mentioned above). So I noticed that occurs because in

symfony/event-dispatcher/EventDispatcher.php line 72:

if ($listeners) {
    $this->callListeners($listeners, $eventName, $event);
}

$listeners is an empty array in my case whereas with every other native sylius step there is at least 1 listener subscribed here. I just don’t know where to add it. Can anybody point me to where/how that is done?


Symfony 4 - Assets folder not found

$
0
0

According to Symfony Best Practices,

Store your assets in the assets/ directory at the root of your project.

But currently, I don't have this folder created and if I create it, I got the error telling me that ressources can't be found.

I tried composer require webassets , but don't working.

Anyone have the solution ?

Regards

php symfony - log each request and it's duration

$
0
0

I have a symfony application that keeps overflowing the apache server's max_children settings. Which I guess it means that there are some requests that take too much time to release the connection.

How can I log every request to see where to begin the optimisation.

Thanks!

Symfony 4. Is there a bundle to count + save info about visitors of my S4 web site? Otherwise, how do I develop one?

$
0
0

Symfony 4. Is there a bundle to count visitors of a S4 web site and save info about them (IP, date, visited pages, downloaded items, ...)? Otherwise, how do I develop one?

Symfony - User logged in but session variables empty after some hours away

$
0
0

I have a Symfony 4.4 project, with registered users (using Guard). When the users log in, they're redirected to an url to select a value that is stored in the session (something like the id of his office). I mean: a page is shown with a list of all the available offices, and when the user click on one, a session variable officeId is stored.

This works correctly, but this morning I've found a problem: if the user is logged in with the "remember me" option, when he uses the application after 6-8h away, he doesn't need to log in again, but the officeId session variable doesn't exist.

Is there any way to avoid this problem? Or I should create a filter to redirect the user if any session variable isn't set?

custom query execute on mongoDb using php libaray

$
0
0

Firstly, I tried all the questions & answers related to this topic. Additionally and I tried related questions and try to solve it but no success. So please read my question thoroughly.

MongoDb Query:

db.getCollection('Address').find({})

i want to direct run Query

i am using PHP Library .

$database = (new MongoDB\Client)->mydatabasename;

and this query run controller i am using Symfony 4

i know about MongoClient but i want to run MongoDB\Client

$mongoClient=new MongoClient('mongodb://username:password@dbServer:port/test_db');
$mongoDB=$mongoClient->test_db;
$mql='db.products.insert( { item: "card", qty: 15 } );';
$data=$mongoDB->execute($mql);
var_dump($data);die;

please guide me

import a xlsx file into my database symfony [closed]

$
0
0

I tried to import a xlsx file into my database (MySQL) with symfony.So to do it , I used phpSpreadsheet. My to do list than I achieved : -upload file -read file -retrieval data spreadsheet

But I don't understand how to use this data and inject data to to my database. I need to use insert into values but I don't understand how to it. If anyone can just explain me this because it's been hours than I'm searching to achieve this.

following code (it's just my function who retrieve data because I think it's here when I have forgotten something to do ) :

protected function createDataFromSpreadsheet($spreadsheet)
{
    $data = [];
    foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
        $worksheetTitle = $worksheet->getTitle();
        $data[$worksheetTitle] = [
            'columnNames' => [],
            'columnValues' => [],
        ];
        foreach ($worksheet->getRowIterator() as $row) {
            $rowIndex = $row->getRowIndex();
            if ($rowIndex > 1) {
                $data[$worksheetTitle]['columnValues'][$rowIndex] = [];
            }
            $cellIterator = $row->getCellIterator();
            $cellIterator->setIterateOnlyExistingCells(false); // Loop over all cells, even if it is not set
            foreach ($cellIterator as $cell) {
                if ($rowIndex === 1) {
                    $data[$worksheetTitle]['columnNames'][] = $cell->getCalculatedValue();
                }
                if ($rowIndex > 1) {
                    $data[$worksheetTitle]['columnValues'][$rowIndex][] = $cell->getCalculatedValue();

                    $query = "INSERT INTO Book(id,title,author,publicationDate,format,language,user)";
                    $query .= "values(?,?,?,?,?,?,?)";

                }
            }

        }
    }

    return $data;
}

How to make session variables available as Twig globals?

$
0
0

Within a twig view, it's possible to get a session variable with

{% set myVar=app.session.get('myVar') %}

It's handy, but I need to do it each time I use a view that doesn't extends base template.

Instead, I would like to set those sessions variables, as twig globals.

I tried to use @session in config/packages/twig.yaml, under globals, but beside @session.storage, I can't find any methods to access my variables.

I thought about doing it in my kernelListener event, but I don't know which service to import to add some dynamics twig globals (if it's even possible).


Symfony Cache across load balanced servers and blue-green deployment (for cache)

$
0
0

I'm currently using Symfony (4.4) across some load balanced, auto-scaling, servers to provide a stateless API authenticated by JSON Web Tokens. These servers are deployed by a Jenkins server, which uses Packer with Ansible provisioning.

For both development and production I'm stripping the deploy down to the bare minimum (no console, no other environment files, dumping the env-file config with Composer, etc). Much of the usual Symfony deployment procedures are being run from Jenkins (because it wouldn't be feasible to run them from within Packer).

I'm also using Redis to store a few things that need to be accessible from any of the load balanced instances.

I had the bright idea of using Redis for the Symfony caches and Doctrine caches to help speed things up. The Redis server is on the same network and has a fast connection. Latency isn't really an issue and I figured that these servers should probably all share the same cache as they are entirely stateless.

However I think that during the deployment, between the cache being cleared and Packer finishing the image (and the image being put into the scaling group) that the servers may well be rebuilding their caches.

The end result, I think, is a new version of code using old caches and this is causing problems in deployment. I don't want to keep the console on the server, for security, and I don't want to hack the cloud-init script to clear the cache when an instance is booted, either, as this would happen whenever a new instance is added to a scaling group.

Is there a way of creating a prefix for the Redis caches so that the new version of the cache can be created, alongside the old, without them interfering?

Angular 8 - Error: - Http failure response for http://fake-api/api/test/1/test/1/test: 0 Unknown Error

$
0
0

I'm lost. I don't understand why it's not working.

I have an Angular 8 application which calls an api on Symfony4 (API platform). Nearly all of my calls are OK and I get responses. My web server is running with apache, PHP7.2 and MySQL 5.7.

But on one page, I have 3 calls and I get this error each time :

"Error: - Http failure response for http://fake-api/api/test/1/test/1/test: 0 Unknown Error" with an "net::ERR_EMPTY_RESPONSE". But it's working on my api/doc and on Postman/Insomnia too.

I just reconfigured my machine. It was OK before reconfiguring but I don't understand why multiple calls are ok and not the others.

I tried to increaase the timeout configuration on Apache and the max_execution_time on PHP. I tried to uninstall my antivirus. I tried to update my cors configuration on the API application.

I don't have any idea what's the problem is... Can you help me or do you have an idea for this problem ?

Thank you very much !

Problem with login in portuguese and security settings in symfony 4.4

$
0
0

Right now I have the following configuration in security.yml:

security:
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
    app_user_provider:
        id: App\Security\UserProvider

encoders:
    App\Security\User:
        algorithm: argon2i

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    main:
        anonymous: true
        json_login:
            check_path: /es/es/venta-recuperable/login-ajax
            remember_me: true
        form_login:
            provider: app_user_provider
            csrf_token_generator: security.csrf.token_manager
            login_path: /es/es/venta-recuperable/login
        logout:
            path:   /es/es/venta-recuperable/logout
            target: /es/es/venta-recuperable/


        remember_me:
            secret:   '%kernel.secret%'
            lifetime: 604800 # 1 week in seconds
            path:     /
            user_providers: [app_user_provider]

        guard:
            authenticators:
                - App\Security\LoginFormAuthenticator
                - App\Security\TokenAuthenticator
            entry_point: App\Security\LoginFormAuthenticator

        # activate different ways to authenticate

        # http_basic: true
        # https://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate

        # form_login: true
        # https://symfony.com/doc/current/security/form_login_setup.html
role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
    ROLE_SUPER_ADMIN: [ ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH ]

That configuration with the login in Spanish works correctly.

My problem comes, when I want to edit this file, to allow login in Portuguese. I have to leave it this way to make it work :

security:
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
    app_user_provider:
        id: App\Security\UserProvider

encoders:
    App\Security\User:
        algorithm: argon2i

firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    main:
        anonymous: true
        json_login:
            check_path: /pt/pt/venda-recuperavel/login-ajax
            remember_me: true
        form_login:
            provider: app_user_provider
            csrf_token_generator: security.csrf.token_manager
            login_path: /pt/pt/venda-recuperavel/login
        logout:
            path:   /pt/pt/venda-recuperavel/logout
            target: /pt/pt/venda-recuperavel/


        remember_me:
            secret:   '%kernel.secret%'
            lifetime: 604800 # 1 week in seconds
            path:     /
            user_providers: [app_user_provider]

        guard:
            authenticators:
                - App\Security\LoginFormAuthenticator
                - App\Security\TokenAuthenticator
            entry_point: App\Security\LoginFormAuthenticator

        # activate different ways to authenticate

        # http_basic: true
        # https://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate

        # form_login: true
        # https://symfony.com/doc/current/security/form_login_setup.html
role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
    ROLE_SUPER_ADMIN: [ ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH ]

I tried putting a pattern in the main.json_login.check_path and main.form_login.login_path allowing both urls, but the login does not work.

main:
        anonymous: true
        json_login:
            check_path: ^(/es/es/venta-recuperable|/pt/pt/venta-recuperavel)$/login-ajax
            remember_me: true
        form_login:
            provider: app_user_provider
            csrf_token_generator: security.csrf.token_manager
            login_path: ^(/es/es/venta-recuperable|/pt/pt/venta-recuperavel)$/login
        logout:
            path:   ^(/es/es/venta-recuperable|/pt/pt/venta-recuperavel)$/logout
            target: ^(/es/es/venta-recuperable|/pt/pt/venta-recuperavel)$/

Here you have the Symfony log debug when I'm going to log in, with the previous configuration :

[2020-02-14 13:50:18] security.DEBUG: Checking for guard authentication credentials. {"firewall_key":"main","authenticators":2} [] [2020-02-14 13:50:18] security.DEBUG: Checking support on guard authenticator. {"firewall_key":"main","authenticator":"App\Security\LoginFormAuthenticator"} [] [2020-02-14 13:50:18] security.DEBUG: Guard authenticator does not support the request. {"firewall_key":"main","authenticator":"App\Security\LoginFormAuthenticator"} [] [2020-02-14 13:50:18] security.DEBUG: Checking support on guard authenticator. {"firewall_key":"main","authenticator":"App\Security\TokenAuthenticator"} [] [2020-02-14 13:50:18] security.DEBUG: Guard authenticator does not support the request. {"firewall_key":"main","authenticator":"App\Security\TokenAuthenticator"} [] [2020-02-14 13:50:18] security.INFO: Populated the TokenStorage with an anonymous Token. [] []

Symfony form builder: How to iterate/render dynamic amount of text fields in twig? (Sylius - exta checkout step)

$
0
0

I added an extra checkout step to the Sylius checkout procedure and I am trying to add 1 text field per instance of an ordered item. Thus having put 3x itemA and 1x itemB in cart should spawn 4 text fields.

I have this code so far in the form builder (based on code from here: https://sf.khepin.com/2011/08/basic-usage-of-the-symfony2-collectiontype-form-field/)

        $builder->add('myCollection', CollectionType::class, $formOptions);

        $totalCounter = 0;
        /** @var OrderItem $item */
        foreach($order->getItems() as $item) {
            for($itemCounter = 0 ; $itemCounter < $item->getQuantity(); $itemCounter++ ) {
                $totalCounter++;
                $builder->get('myCollection')->add('item_' . $totalCounter, TextType::class, $formOptions);
            }
        }

First Question: Is this the right approach for the form builder for my particular scenario, and secondly: If yes, how do I read from this in the twig template?

form.children.myCollection does exist but does not seem to contain these children, so that I could use them with the form_row function. What I would have expected is something like this:

{% set totalCounter = 0 %}
{% for item in order.items %}
    {% for itemCounter in 1..item.quantity %}
        {% set totalCounter = totalCounter + 1 %}
        {{  form_row(form.children.myCollection['item_' ~ totalCounter ]) }}
    {% endfor %}
{% endfor %}

Any idea how to do this? Thanks for any hint in advance!

Authenticate a user by role

Viewing all 3924 articles
Browse latest View live