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

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

<head>
    {{ encore_entry_link_tags('app') }}
    {{ encore_entry_script_tags('app') }}
    </head>
    <body>
    <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


sqlite: Fixtures load null instead of string - NOT NULL constraint failed

$
0
0

I have a simple Entity consisting of just one field "name":

/**
 * @ORM\Table(name="gender")
 * @ORM\Entity
 * @codeCoverageIgnore
 */
class Gender
{
    public const FEMALE = 'female';
    public const MALE = 'male';
    public const OTHER = 'other';

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=15, nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private string $name;

    public function getName(): string
    {
        return $this->name;
    }

    public function setName(string $name): Gender
    {
        $this->name = $name;

        return $this;
    }
}

For this class I try to generate fixtures and insert them into a sqlite db for testing:

use App\Entity\Gender; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Persistence\ObjectManager;

class GenderFixtures extends Fixture
{

    public function load(ObjectManager $manager)
    {
        $genders = [Gender::FEMALE, Gender::MALE, Gender::OTHER];

        foreach ($genders as $genderName) {
            echo $genderName . PHP_EOL;

            $gender = (new Gender())
                ->setName($genderName);
            $manager->persist($gender);
        }

        $manager->flush();
    }
}

When I call

 bin/console  doctrine:fixtures:load --env=test

I get this:

female
male
other

In AbstractSQLiteDriver.php line 39:

  An exception occurred while executing 'INSERT INTO gender (name) VALUES (null)':             

  SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: gender.name 

So as you can see there are the three strings I want to use as name. Why are they not used by the Fixture in the insert statement?

Symfony 4.4, PHP 7.4.1, Doctrine Fixtures 3.3.0

Symfony 4: How load config depending on host

$
0
0

Now for routing using config specified in annotations

controllers:
    resource: ../../src/Controller/Frontend
    type: annotation
    prefix:
        en: ''
        fr: '/fr'
        de: '/de'

For all domains language without prefix now is english. Now to set language without prefix depending on host? For example for a domain in Germany I want the config to be like this:

controllers:
    resource: ../../src/Controller/Frontend
    type: annotation
    prefix:
        de: ''
        fr: '/fr'
        en: '/en'

symfony does not work with multiple requests/responses at once

$
0
0

I have problem that that symfony can't solve multiple requests/responses over multiple pages/computers at the same time

Example 1 - when I open symfony page (that have slow loading due internet speed) and I open another page (even on the same or another computer), I will do not get any response until the first page is loaded.

Example 2 - when I sending some file to my raspberry over response, I can't open any page in my symfony, until the files is not send (because the response is not completed so it will not go on next request). And this can be up to 3 minutes due the speed of internet connection.

I am using XAMP | php CGI 7.1.13 | symfony 4.4.0 PHP | Debug - enabled

Using an "if" condition on "for"

$
0
0

I wanted to put into production my symfony 4 application, everything is going well but on some pages I have an error 500, I could find where the problem comes from but I don't understand how to solve it.

{% for articleUps in articleUp if articleUps.statut == "épinglé" %}
                    <div class="article">
                        <img src="{{ asset('assets/avatar/')~articleUps.user.image }}"
                             class="card-img-top photo rounded-circle">
                        <i class="fas fa-thumbtack"></i><a href="{{ path('forum_articles', {'id': articleUps.id , 'slug': articleUps.slug }) }}">{{ articleUps.sujet }}</a><br>
                        <strong>Crée le {{articleUps.createdAt|localizeddate('none', 'none', 'fr', null, 'EEEE d MMMM Y') }} • par<a href="{{ path('app_profil', {'username': articleUps.user.username}) }} ">{{ articleUps.user.username }}</a></strong>
                        {% if is_granted('ROLE_ADMIN') %}
                            <a href="{{ path('article_edit', {'id': articleUps.id}) }}" class="lien">editer</a>
                        {% endif %}
                    </div>
                    <hr>
                {% endfor %}

so I get this error in the symfony log:

[2020-01-05 17:26:49] php.INFO: User Deprecated: Using an "if" condition on "for" tag in "forum/categories.html.twig" at line 91 is deprecated since Twig 2.10.0, use a "filter" filter or an "if" condition inside the "for" body instead (if your condition depends on a variable updated inside the loop). {"exception":"[object] (ErrorException(code: 0): User Deprecated: Using an \"if\" condition on \"for\" tag in \"forum/categories.html.twig\" at line 91 is deprecated since Twig 2.10.0, use a \"filter\" filter or an \"if\" condition inside the \"for\" body instead (if your condition depends on a variable updated inside the loop). at /var/www/html/ara.issoire-web.fr/vendor/twig/twig/src/TokenParser/ForTokenParser.php:46)"} []

how can i do that there are no more bugs in production ?

I changed my condition, here is the news that still works in dev but not in production:

{% for articleUps in articleUp %}
                        {% if articleUps.statut == "épinglé"  %}
                        <div class="article">
                            <img src="{{ asset('assets/avatar/')~articleUps.user.image }}"
                                 class="card-img-top photo rounded-circle">
                            <i class="fas fa-thumbtack"></i><a href="{{ path('forum_articles', {'id': articleUps.id , 'slug': articleUps.slug }) }}">{{ articleUps.sujet }}</a><br>
                            <strong>Crée le {{articleUps.createdAt|localizeddate('none', 'none', 'fr', null, 'EEEE d MMMM Y') }} • par<a href="{{ path('app_profil', {'username': articleUps.user.username}) }} ">{{ articleUps.user.username }}</a></strong>
                            {% if is_granted('ROLE_ADMIN') %}
                                <a href="{{ path('article_edit', {'id': articleUps.id}) }}" class="lien">editer</a>
                            {% endif %}
                        </div>
                        <hr>
                        {% endif %}
                    {% endfor %}

Testing authorization on API Platform

$
0
0
  • I'm using Symfony 4.4 and api-platform/api-pack v1.2.1
  • I've created a custom voter that support string with prefix PERM_
  • I set an endpoint (/api/roles) to have security: 'is_granted("PERM_READ_USER")'
  • I create a test like below:
    /**
     * @depends testLoginRegularUser
     * @param $token
     * @return string JWT Token
     */
    public function testRegularUserReadRole($token)
    {
        $this->expectException(AccessDeniedHttpException::class);
        $this->expectExceptionCode(403);
        $response = static ::createClient()->request('GET', '/api/roles',[
            'json' => [
                'page' => 1
            ],
            'headers' => [
                'Authorization' => 'Bearer ' . $token,
            ]
        ]);
        return $token;
    }

And I always get error message:

Testing App\Tests\Functional\GroupRoleTest
.2020-01-06T00:49:48+00:00 [error] Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException: "Access Denied." at /home/vagrant/Code/wikaunting/vendor/symfony/security-http/Firewall/ExceptionListener.php line 137
FS                                                                 3 / 3 (100%)

Time: 14.27 seconds, Memory: 44.50 MB

There was 1 failure:

1) App\Tests\Functional\GroupRoleTest::testRegularUserReadRole
Failed asserting that exception of type "Symfony\Component\HttpClient\Exception\AccessDeniedHttpException" is thrown.

When I test using rest client (Insomenia), it return

{
  "@context": "\/api\/contexts\/Error",
  "@type": "hydra:Error",
  "hydra:title": "An error occurred",
  "hydra:description": "Access Denied.",
  "trace": [
  {
      "namespace": "",
      "short_class": "",
      "class": "",
      "type": "",
      "function": "",
      "file": "\/home\/vagrant\/Code\/wikaunting\/vendor\/symfony\/security-http\/Firewall\/ExceptionListener.php",
      "line": 137,
      "args": []
    },
    {
      "namespace": "Symfony\\Component\\Security\\Http\\Firewall",
      "short_class": "ExceptionListener",
      "class": "Symfony\\Component\\Security\\Http\\Firewall\\ExceptionListener",
      "type": "->",
      "function": "handleAccessDeniedException",
      "file": "\/home\/vagrant\/Code\/wikaunting\/vendor\/symfony\/security-http\/Firewall\/ExceptionListener.php",
      "line": 102,
      "args": [
        [
          "object",
          "Symfony\\Component\\HttpKernel\\Event\\ExceptionEvent"
        ],
        [
          "object",
          "Symfony\\Component\\Security\\Core\\Exception\\AccessDeniedException"
        ]
      ]
    },
    {
      "namespace": "Symfony\\Component\\Security\\Http\\Firewall",
      "short_class": "ExceptionListener",
      "class": "Symfony\\Component\\Security\\Http\\Firewall\\ExceptionListener",
      "type": "->",
      "function": "onKernelException",
      "file": "\/home\/vagrant\/Code\/wikaunting\/vendor\/symfony\/event-dispatcher\/Debug\/WrappedListener.php",
      "line": 126,
      "args": [
        [
          "object",
          "Symfony\\Component\\HttpKernel\\Event\\ExceptionEvent"
        ],
        [
          "string",
          "kernel.exception"
        ],
        [
          "object",
          "Symfony\\Component\\HttpKernel\\Debug\\TraceableEventDispatcher"
        ]
      ]
    },
    {
      "namespace": "Symfony\\Component\\EventDispatcher\\Debug",
      "short_class": "WrappedListener",
      "class": "Symfony\\Component\\EventDispatcher\\Debug\\WrappedListener",
      "type": "->",
      "function": "__invoke",
      "file": "\/home\/vagrant\/Code\/wikaunting\/vendor\/symfony\/event-dispatcher\/EventDispatcher.php",
      "line": 264,
      "args": [
        [
          "object",
          "Symfony\\Component\\HttpKernel\\Event\\ExceptionEvent"
        ],
        [
          "string",
          "kernel.exception"
        ],
        [
          "object",
          "Symfony\\Component\\HttpKernel\\Debug\\TraceableEventDispatcher"
        ]
      ]
    },
    {
      "namespace": "Symfony\\Component\\EventDispatcher",
      "short_class": "EventDispatcher",
      "class": "Symfony\\Component\\EventDispatcher\\EventDispatcher",
      "type": "->",
      "function": "doDispatch",
      "file": "\/home\/vagrant\/Code\/wikaunting\/vendor\/symfony\/event-dispatcher\/EventDispatcher.php",
      "line": 239,
      "args": [
        [
          "array",
          [
            [
              "object",
              "Symfony\\Component\\EventDispatcher\\Debug\\WrappedListener"
            ],
            [
              "object",
              "Symfony\\Component\\EventDispatcher\\Debug\\WrappedListener"
            ],
            [
              "object",
              "Symfony\\Component\\EventDispatcher\\Debug\\WrappedListener"
            ],
            [
              "object",
              "Symfony\\Component\\EventDispatcher\\Debug\\WrappedListener"
            ],
            [
              "object",
              "Symfony\\Component\\EventDispatcher\\Debug\\WrappedListener"
            ],
            [
              "object",
              "Symfony\\Component\\EventDispatcher\\Debug\\WrappedListener"
            ]
          ]
        ],
        [
          "string",
          "kernel.exception"
        ],
        [
          "object",
          "Symfony\\Component\\HttpKernel\\Event\\ExceptionEvent"
        ]
      ]
    },
    {
      "namespace": "Symfony\\Component\\EventDispatcher",
      "short_class": "EventDispatcher",
      "class": "Symfony\\Component\\EventDispatcher\\EventDispatcher",
      "type": "->",
      "function": "callListeners",
      "file": "\/home\/vagrant\/Code\/wikaunting\/vendor\/symfony\/event-dispatcher\/EventDispatcher.php",
      "line": 73,
      "args": [
        [
          "array",
          [
            [
              "object",
              "Symfony\\Component\\EventDispatcher\\Debug\\WrappedListener"
            ],
            [
              "object",
              "Symfony\\Component\\EventDispatcher\\Debug\\WrappedListener"
            ],
            [
              "object",
              "Symfony\\Component\\EventDispatcher\\Debug\\WrappedListener"
            ],
            [
              "object",
              "Symfony\\Component\\EventDispatcher\\Debug\\WrappedListener"
            ],
            [
              "object",
              "Symfony\\Component\\EventDispatcher\\Debug\\WrappedListener"
            ],
            [
              "object",
              "Symfony\\Component\\EventDispatcher\\Debug\\WrappedListener"
            ]
          ]
        ],
        [
          "string",
          "kernel.exception"
        ],
        [
          "object",
          "Symfony\\Component\\HttpKernel\\Event\\ExceptionEvent"
        ]
      ]
    },
    {
      "namespace": "Symfony\\Component\\EventDispatcher",
      "short_class": "EventDispatcher",
      "class": "Symfony\\Component\\EventDispatcher\\EventDispatcher",
      "type": "->",
      "function": "dispatch",
      "file": "\/home\/vagrant\/Code\/wikaunting\/vendor\/symfony\/event-dispatcher\/Debug\/TraceableEventDispatcher.php",
      "line": 168,
      "args": [
        [
          "object",
          "Symfony\\Component\\HttpKernel\\Event\\ExceptionEvent"
        ],
        [
          "string",
          "kernel.exception"
        ]
      ]
    },
    {
      "namespace": "Symfony\\Component\\EventDispatcher\\Debug",
      "short_class": "TraceableEventDispatcher",
      "class": "Symfony\\Component\\EventDispatcher\\Debug\\TraceableEventDispatcher",
      "type": "->",
      "function": "dispatch",
      "file": "\/home\/vagrant\/Code\/wikaunting\/vendor\/symfony\/http-kernel\/HttpKernel.php",
      "line": 207,
      "args": [
        [
          "object",
          "Symfony\\Component\\HttpKernel\\Event\\ExceptionEvent"
        ],
        [
          "string",
          "kernel.exception"
        ]
      ]
    },
    {
      "namespace": "Symfony\\Component\\HttpKernel",
      "short_class": "HttpKernel",
      "class": "Symfony\\Component\\HttpKernel\\HttpKernel",
      "type": "->",
      "function": "handleThrowable",
      "file": "\/home\/vagrant\/Code\/wikaunting\/vendor\/symfony\/http-kernel\/HttpKernel.php",
      "line": 79,
      "args": [
        [
          "object",
          "Symfony\\Component\\Security\\Core\\Exception\\AccessDeniedException"
        ],
        [
          "object",
          "Symfony\\Component\\HttpFoundation\\Request"
        ],
        [
          "integer",
          1
        ]
      ]
    },
    {
      "namespace": "Symfony\\Component\\HttpKernel",
      "short_class": "HttpKernel",
      "class": "Symfony\\Component\\HttpKernel\\HttpKernel",
      "type": "->",
      "function": "handle",
      "file": "\/home\/vagrant\/Code\/wikaunting\/vendor\/symfony\/http-kernel\/Kernel.php",
      "line": 201,
      "args": [
        [
          "object",
          "Symfony\\Component\\HttpFoundation\\Request"
        ],
        [
          "integer",
          1
        ],
        [
          "boolean",
          true
        ]
      ]
    },
    {
      "namespace": "Symfony\\Component\\HttpKernel",
      "short_class": "Kernel",
      "class": "Symfony\\Component\\HttpKernel\\Kernel",
      "type": "->",
      "function": "handle",
      "file": "\/home\/vagrant\/Code\/wikaunting\/public\/index.php",
      "line": 25,
      "args": [
        [
          "object",
          "Symfony\\Component\\HttpFoundation\\Request"
        ]
      ]
    }
  ]
}

I thought it might return AccessDeniedException, not AccessDeniedHttpException so I change the test to

$this->expectException(\Symfony\Component\Security\Core\Exception\AccessDeniedException::class);

But it still return similar error

1) App\Tests\Functional\GroupRoleTest::testRegularUserReadRole
Failed asserting that exception of type "Symfony\Component\Security\Core\Exception\AccessDeniedException" is thrown.

Question

  • Is it supposed to return an exception?
  • The [error] Uncaught PHP Exception ... message always appear. How to make it dissappear?

React Native can't handle subscription to Mercure Component Update value object

$
0
0

I'm working on a notifications system with React Native and Symfony. I configured Mercure with docker to handle front subscription to real time updates : the .env file :

###> symfony/mercure-bundle ###
# See https://symfony.com/doc/current/mercure.html#configuration
MERCURE_PUBLISH_URL=http://mercure.localhost/.well-known/mercure
# The default token is signed with the secret key: !ChangeMe!
MERCURE_JWT_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXJjdXJlIjp7InB1Ymxpc2giOlsiKiJdfX0.9-LscFk3QfdDtZ4nyg6BiH4_qDm6pbYHydURBMsDgEc
###< symfony/mercure-bundle ###

mercure.yaml:

mercure:
    enable_profiler: '%kernel.debug%'
    hubs:
        default:
            url: '%env(MERCURE_PUBLISH_URL)%'
            jwt: '%env(MERCURE_JWT_TOKEN)%'

I created a Notifications component in my React Native application and i use the code in the official documentation of symfony mercure: https://symfony.com/doc/4.3/mercure.html#subscribing Notifications.js code :

import React, { Component } from 'react';
import { View, Text } from 'react-native';

export default class Notifications extends Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }

    componentDidMount() {
        const url = new URL('http://mercure.localhost/.well-known/mercure');
        url.searchParams.append('topic', 'http://dev.api.partage-mandats.proprietes-privees.com/mandate_shares/{id}');

        url.searchParams.append('topic', 'http://example.com/books/1');
        const eventSource = new EventSource(url);

        eventSource.onmessage = e => console.log(e);
    }

    render() {
        return (
            <View>
                <Text> Notifications </Text>
            </View>
        );
    }
}

I tested with Postan and i get a valid response : Postman test mercure

And i tried the javaScript code in a html file for testing :

<script type="text/javascript">

const url = new URL('http://mercure.localhost/.well-known/mercure');
url.searchParams.append('topic', 'http://dev.api.partage-mandats.proprietes-privees.com/mandate_shares/{id}');

url.searchParams.append('topic', 'http://example.com/books/1');
const eventSource = new EventSource(url);

eventSource.onmessage = e => console.log(e); 
</script>
</html>

And i get a real time response when i run request with Postman : console log in html file My problem is that URL, searchParams and eventSource are not compatible with react native. How can i transform this javaScript code to react native valid code ? I tried to install some librairies : whatwg-url, buffer, react-native-event-source and my current code is :

import React, { Component } from 'react';
import { View, Text } from 'react-native';

import { URL, URLSearchParams } from 'whatwg-url';
import { Buffer } from 'buffer';
import RNEventSource from 'react-native-event-source';

export default class Notifications extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }

  componentDidMount() {
    global.Buffer = Buffer;
    global.URL = URL;
    global.URLSearchParams = URLSearchParams;
    global.EventSource = RNEventSource;

    const url = new global.URL('http://mercure.localhost/.well-known/mercure');
    url.global.URLSearchParams.append('topic', 'http://dev.api.partage-mandats.proprietes-privees.com/mandate_shares/{id}');

    url.global.URLSearchParams.append('topic', 'http://example.com/books/1');
    const eventSource = new global.EventSource(url);

    eventSource.onmessage = e => console.log(e); 
  }

  render() {
    return (
      <View>
        <Text> Notifications </Text>
      </View>
    );
  }
}

I got this error : undefined is not an object (evaluating 'url.global.URLSearchParams')

Using Symfony HttpClient to access to API Platform inside controller and display result in twig

$
0
0

I'm using Symfony4 and API Platform, I'd like to know if is it possible using Symfony HttpClient to access to API Platform inside controller and display result in twig or not.

This is how I tried to do and the error I got it:

enter image description here

This is the action inside the controller:

/**
 * Class BookController
 * @package App\Controller\Admin
 * @Route("/admin/books")
 */
class BookController extends AbstractController
{

    /**
     * @Route("/", name="admin_book_index", methods={"GET"})
     */
    public function index()
    {

        $client = HttpClient::create();
        $response = $client->request('GET', 'http://127.0.0.1:8000/api/books');

        $contents = $response->getContent();


        return $this->render('admin/book/index.html.twig', array(
            'content'=> json_decode($contents)
        ));
    }

}

But when I change the url by the url in the Symfony documention it works fine :

// no problem with this url
$response = $client->request('GET', 'https://api.github.com/repos/symfony/symfony-docs');

The API Platform works fine also :

enter image description here


linux - should be a file pdo_mysql.so under php/modules? i have only pdo.so and pdo_sqlite

$
0
0

After updating PHP to 7.3 (linux).

I get error:

An exception occurred in driver: could not find driver.

Could it be because of PDO?

In my folder php/modules I don't find pdo_mysql.so. Should it be there?

How do Symfony Flex recipes know what packages to install?

$
0
0

I am trying to understand how Symfony recipes know what packages to install along the way.

Reading the source code, it seems to me that when I run

composer require twig

the composer, having flex as a plugin,

  1. looks for an alias called twig
  2. sees that it is registered for the recipe symfony/twig-pack
  3. downloads the recipe and reads its manifest.json
  4. executes all the actions defined in manifest.json, like creating extra files or appending stuff to files

But nowhere do I see in the manifest.json to install the actual package symfony/twig-pack.

Is it just implicit that all recipes have to share their name with the package they are installing and that this is the way how composer knows what package to install?

I.e. a developer can not just create a recipe invented_company/nonexisting_package that just adds a few files here and appends a few lines there, but not actually corresponds to a package on packagist?

Symfony 4 Match method like tinder

$
0
0

first of all sorry for my bad english i'm not a native speaker.

I work on a website for my last school project, it's a website where (as a normal user) you can match with a coach and once you two have matched together, you can share a page where the coach can update your daily workout program).

I'm stucked at the matching method, my entity User has a propriety idCoach wich is an array who can contains other Users. The idea is when you are on the coach's profile page, and you press on the match button, it adds the coach on your idCoach propriety. This is my propriery from my User entity:

/**
 * @ORM\OneToMany(targetEntity="App\Entity\User", mappedBy="idSportif")
 */
private $idCoach;

this is what i tried on the controller :

/**
 * @Route("/user/match/{id}", name="match")
 */
public function matchCoach(ObjectManager $om, User $user) {
    $currentUser = $this->getUser();
    $currentUser->addIdCoach($user);
    $om->persist($currentUser);
    $om->flush();

    return $this->render('profile/index.html.twig', [
        'user' => $currentUser,
    ]);



}

but it gives me an error message : Call to a member function addIdCoach() on null

I have only 2 days left to success, please help me.

UserProvider from custom composer package [Symfony 4]

$
0
0

I got a tricky question today,

Is it possible to have a custom UserProvider from a vendor in symfony 4 ? For the moment I got this error :

The service "security.context_listener.0" has a dependency on a non-existent service "Hello\UserProvider".

Symfony : Unknown database type geometry requested

$
0
0
 php bin/console doctrine:mapping:import "App\Entity" annotation --path=src/Entity

In AbstractPlatform.php line 436:
                                                                                                               
  Unknown database type geometry requested, Doctrine\DBAL\Platforms\PostgreSQL100Platform may not support it.  
                                                                                                               

doctrine:mapping:import [--em [EM]] [--shard SHARD] [--filter FILTER] [--force] [--path PATH] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--] <command> <name> [<mapping-type>]

Symfony 5 cache:clear php.CRITICAL: Fatal error: Allowed memory size

$
0
0

I am encoutering the following error with Symfony 5 when trying to

bin/console cache:clear

I know how I could patch that (memory_limit=-1) but I want know why I have this error.

Error :

PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32230840 bytes) in /Applications/MAMP/htdocs/Toile./vendor/twig/twig/src/Lexer.php on line 157

15:50:13 CRITICAL [php] Fatal Error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32230840 bytes)

[
  "exception" => Symfony\Component\ErrorHandler\Error\OutOfMemoryError {
    -error: [
      "type" => 1,
      "message" => "Allowed memory size of 134217728 bytes exhausted (tried to allocate 32230840 bytes)",
      "file" => "/Applications/MAMP/htdocs/Toile./vendor/twig/twig/src/Lexer.php",
      "line" => 157
    ]
    #message: "Error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32230840 bytes)"
    #code: 0
    #file: "./vendor/twig/twig/src/Lexer.php"
    #line: 157
  }
]

In Lexer.php line 157: Error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32230840 bytes)

I am unable to track from where this error comes from.

I removed all twig templates from my project, I clearing the cache manually but nothing .. Any idea?

Thanks

How can I load web profiler debug toolbar in Symfony?

$
0
0

My web profiler debug toolbar is showing the error:

An error occurred while loading the web debug toolbar.

I followed all the steps written in this answer:

My profiler toolbar isn't showing up in symfony 4.3.1

Still the same error. Next thing I tried was:

composer require symfony/apache-pack

Also not working. Finally I tried:

chmod -R 777 var/cache

Still not working. Hope someone can help me!

When I make this:

composer require --dev profiler

Update:

php bin/console security:check:

No packages have known vulnerabilities.

Testing bin/console debug:event-dispatcher kernel.response gives me the following output:

     ------- -------------------------------------------------------------------------------------------- ----------
  Order   Callable                                                                                     Priority
 ------- -------------------------------------------------------------------------------------------- ----------
  #1      Symfony\Bridge\Monolog\Handler\FirePHPHandler::onKernelResponse()                            0
  #2      Symfony\Bridge\Monolog\Handler\ChromePhpHandler::onKernelResponse()                          0
  #3      Symfony\Component\HttpKernel\EventListener\ResponseListener::onKernelResponse()              0
  #4      Symfony\Component\HttpKernel\DataCollector\RequestDataCollector::onKernelResponse()          0
  #5      Symfony\Component\WebLink\EventListener\AddLinkHeaderListener::onKernelResponse()            0
  #6      Symfony\Component\Security\Http\RememberMe\ResponseListener::onKernelResponse()              0
  #7      Sensio\Bundle\FrameworkExtraBundle\EventListener\HttpCacheListener::onKernelResponse()       0
  #8      Symfony\Component\HttpKernel\EventListener\ProfilerListener::onKernelResponse()              -100
  #9      Symfony\Bundle\WebProfilerBundle\EventListener\WebDebugToolbarListener::onKernelResponse()   -128
  #10     Symfony\Component\HttpKernel\EventListener\DisallowRobotsIndexingListener::onResponse()      -255
  #11     Symfony\Component\HttpKernel\EventListener\SessionListener::onKernelResponse()               -1000
  #12     Symfony\Component\HttpKernel\EventListener\StreamedResponseListener::onKernelResponse()      -1024
 ------- -------------------------------------------------------------------------------------------- ----------

Web Profiler.yaml:

web_profiler:
    toolbar: true
    intercept_redirects: false

framework:
    profiler: { only_exceptions: false }

How could i use ResetType to delete filters in symfony 4 without using javascript?

$
0
0

I used this code:

$builder->add('clear',ResetType::class,['attr' => ['class' => 'clear'],]);

For price and type I used: EntityType. The filters work perfectly for price and type.

The only problem is that i don't know how to delete the filters by pressing the button "clear filters"

Previously executed migration are not registered migrations

$
0
0

I'm trying to update my database with those commands

php bin/console make:migration

this return success

But when I try

php bin/console doctrine:migrations:migrate

I have this error:

WARNING! You have 5 previously executed migrations in the database >>that are not registered migrations.

>> 2018-12-17 10:42:04 (20181217104204)
>> 2018-12-17 13:19:24 (20181217131924)
>> 2018-12-17 13:40:58 (20181217134058)
>> 2018-12-18 10:41:38 (20181218104138)
>> 2018-12-18 13:15:49 (20181218131549)

Thing is, the database listed here are not in my migrations table from my database and they are not in my Migrations folder either.

How can I remove those wrong migrations ? Thanks.

react native can't subscribe to mercure backend notifications

$
0
0

I'm working on a notifications system with React Native and Symfony. I configured Mercure with docker to handle front subscription to real time updates : the .env file :

###> symfony/mercure-bundle ###
# See https://symfony.com/doc/current/mercure.html#configuration
MERCURE_PUBLISH_URL=http://mercure.localhost/.well-known/mercure
# The default token is signed with the secret key: !ChangeMe!
MERCURE_JWT_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXJjdXJlIjp7InB1Ymxpc2giOlsiKiJdfX0.9-LscFk3QfdDtZ4nyg6BiH4_qDm6pbYHydURBMsDgEc
###< symfony/mercure-bundle ###

mercure.yaml:

mercure:
    enable_profiler: '%kernel.debug%'
    hubs:
        default:
            url: '%env(MERCURE_PUBLISH_URL)%'
            jwt: '%env(MERCURE_JWT_TOKEN)%'

I created a Notifications component in my React Native application and i use the code in the official documentation of symfony mercure: https://symfony.com/doc/4.3/mercure.html#subscribing Notifications.js code :

import React, { Component } from 'react';
import { View, Text } from 'react-native';

export default class Notifications extends Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }

    componentDidMount() {
        const url = new URL('http://mercure.localhost/.well-known/mercure');
        url.searchParams.append('topic', 'http://dev.api.partage-mandats.proprietes-privees.com/mandate_shares/{id}');

        url.searchParams.append('topic', 'http://example.com/books/1');
        const eventSource = new EventSource(url);

        eventSource.onmessage = e => console.log(e);
    }

    render() {
        return (
            <View>
                <Text> Notifications </Text>
            </View>
        );
    }
}

I tested with Postan and i get a valid response : Postman test mercure

And i tried the javaScript code in a html file for testing :

<script type="text/javascript">

const url = new URL('http://mercure.localhost/.well-known/mercure');
url.searchParams.append('topic', 'http://dev.api.partage-mandats.proprietes-privees.com/mandate_shares/{id}');

url.searchParams.append('topic', 'http://example.com/books/1');
const eventSource = new EventSource(url);

eventSource.onmessage = e => console.log(e); 
</script>
</html>

And i get a real time response when i run request with Postman : console log in html file My problem is that URL, searchParams and eventSource are not compatible with react native. How can i transform this javaScript code to react native valid code ? I tried to install some librairies : whatwg-url, buffer, react-native-event-source and my current code is :

import React, { Component } from 'react';
import { View, Text } from 'react-native';

import { URL, URLSearchParams } from 'whatwg-url';
import { Buffer } from 'buffer';
import RNEventSource from 'react-native-event-source';

export default class Notifications extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }

  componentDidMount() {
    global.Buffer = Buffer;
    global.URL = URL;
    global.URLSearchParams = URLSearchParams;
    global.EventSource = RNEventSource;

    const url = new global.URL('http://mercure.localhost/.well-known/mercure');
    url.global.URLSearchParams.append('topic', 'http://dev.api.partage-mandats.proprietes-privees.com/mandate_shares/{id}');

    url.global.URLSearchParams.append('topic', 'http://example.com/books/1');
    const eventSource = new global.EventSource(url);

    eventSource.onmessage = e => console.log(e); 
  }

  render() {
    return (
      <View>
        <Text> Notifications </Text>
      </View>
    );
  }
}

I got this error : undefined is not an object (evaluating 'url.global.URLSearchParams')

Symfony 4 Add Collection entity => erreur on submit : "Expected App\Entity\xxxx, array given"

$
0
0

Hello everyone and happy new year, I am asked to migrate a symfony 2 project to symfony 4. Everything worked very well until the moment when I approached the collections ... The principle is in theory simple, it is acts of repair sheets (Fichesrep) which contains a list of operations (Operationsrep), a OneToMany relation which worked very well on symfony 2. Indeed, once integrated several forms of operations in js in the form of the sheet, it all it took was one click (submit) for the form and its operations to be integrated into the database with their relationship. Now, on symfony 4, with a code very little different, the submit of the form returns me an error in particular at the level of the function addOperationsrep (Operationsrep $ operationsrep) which is in App \ Entity \ Fichesrep: "Expected App \ Entity \ Operationsrep , array given "...

Voici App\Entity\Fichesrep.php :

namespace App\Entity;

use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Fichesrep
 *
 * @ORM\Table(name="fichesrep", indexes={@ORM\Index(name="id", columns={"id"}), @ORM\Index(name="Date", columns={"created", "modified"}), @ORM\Index(name="IDX_6F8F29F019EB6921", columns={"client_id"})})
 * @ORM\Entity(repositoryClass="App\Repository\FichesrepRepository")
 */
class Fichesrep
{

    public function __construct()
    {
        $this->created         = new \Datetime();
        $this->modified        = new \Datetime();
        $this->operationsrep = new ArrayCollection();
    }

    /**
     * @var Collection
     *
     * @ORM\OneToMany(targetEntity="Operationsrep", cascade={"persist","remove"},orphanRemoval=true, mappedBy="fichesrep")
     * @ORM\OrderBy({"id" = "ASC"}) 

    * @ORM\JoinColumn(nullable=false)
     * 
     */
    protected $operationsrep;

    /**
     * @return Collection|Operationsrep[]
     */
    public function getOperationsrep(): Collection
    {
        return $this->operationsrep;
    }

    public function addOperationsrep(Operationsrep $operationsrep): self
    {
        if (!$this->operationsrep->contains($operationsrep)) {
            $this->operationsrep[] = $operationsrep;
            $operationsrep->setFichesrep($this);
        }

        return $this;
    }

    public function removeOperationsrep(Operationsrep $operationsrep): self
    {
        if ($this->operationsrep->contains($operationsrep)) {
            $this->operationsrep->removeElement($operationsrep);

            if ($operationsrep->getFichesrep() === $this) {
                $operationsrep->setFichesrep(null);
            }
        }

        return $this;
    }



}

Voici App\Form\FichesrepType.php :


namespace App\Form;

use App\Entity\Fichesrep;
use App\Entity\Operationsrep;
use App\Form\OperationsrepType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\OptionsResolver\OptionsResolver;


class FichesrepType extends AbstractType
{
    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('modele',TextareaType::class,['required' => false])
            ->add('nota',TextareaType::class,['required' => false])
            ->add('signatureclient', ChoiceType::class, [
                'choices' => ['Visible sur la fiche'=>1,'Pas visible'=>2],
                'placeholder' => 'Choix'
            ])
            ->add('acompte',TextType::class,['required' => false])
            ->add('delai',DateType::class,[
                    'widget' => 'single_text',
                    'input' => 'datetime',
                    'format' => 'dd/MM/yyyy',
                    'attr' => ['readonly' => true]
                    ])
            ->add('rv',DateType::class,[
                    'widget' => 'single_text',
                    'input' => 'datetime',
                    'format' => 'dd/MM/yyyy',
                    'attr' => ['readonly' => true]
                    ])
            ->add('operationsrep', CollectionType::class, [
                    'entry_type'   => OperationsrepType::class,
                    'allow_add'    => true,
                    'allow_delete' => true,
                    'prototype'=>'__fdata__',
                    'by_reference' => false
                    ])   
            ->add('enregistrer',SubmitType::class,array('attr'=>array('class'=>'btn btn-primary btn-sm')))
        ;
    }


     /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Fichesrep::class
        ]);
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'Fichesrep';
    }
}

Voici App\Repository\FichesrepRepository.php :

namespace App\Repository;

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

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


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

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

Voici App\Controller\Fichesrep.php :


namespace App\Controller;

use App\Entity\Operationsrep;
use App\Entity\Operations;
use App\Entity\Clients;
use App\Entity\Fournituresrep;
use App\Entity\Fichesrep;
use App\Form\FichesrepType;
use App\Form\OperationsrepType;
use App\Form\FournituresrepType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\FormType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Knp\Component\Pager\PaginatorInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Doctrine\ORM\EntityRepository;

class FichesrepController extends AbstractController
{

    public function add(Request $request, $idclient){        

        $ficherep = new Fichesrep();
        $form = $this->createForm(FichesrepType::class, $ficherep);
        $form->handleRequest($request);

        $client = $this->getDoctrine()
                    ->getManager()
                    ->getRepository(Clients::class)
                    ->find($idclient)
    ;

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($ficherep
                    ->setClient($client)
                    );
            $em->flush();

            $this->addFlash('success', "La fiche a été ajoutée!");

            return $this->redirect($this->generateUrl('fichesrep_index'));
        }       

        return $this->render('fichesrep/add.html.twig', array(
            'form' => $form->createView(),
            'client'=> $client
        ));
    }

}

Voici composer.json :

{
    "type": "project",
    "license": "proprietary",
    "require": {
        "php": "^7.1.3",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "friendsofsymfony/user-bundle": "~2.0",
        "knplabs/knp-paginator-bundle": "^5.0",
        "sensio/framework-extra-bundle": "^5.5",
        "symfony/asset": "4.3.*",
        "symfony/console": "4.3.*",
        "symfony/dotenv": "4.3.*",
        "symfony/expression-language": "4.3.*",
        "symfony/flex": "^1.3.1",
        "symfony/form": "4.3.*",
        "symfony/framework-bundle": "4.3.*",
        "symfony/http-client": "4.3.*",
        "symfony/intl": "4.3.*",
        "symfony/monolog-bundle": "^3.1",
        "symfony/orm-pack": "^1.0",
        "symfony/process": "4.3.*",
        "symfony/security-bundle": "4.3.*",
        "symfony/serializer-pack": "*",
        "symfony/swiftmailer-bundle": "^3.1",
        "symfony/templating": "4.3.*",
        "symfony/translation": "4.3.*",
        "symfony/twig-bundle": "4.3.*",
        "symfony/twig-pack": "^1.0",
        "symfony/validator": "4.3.*",
        "symfony/web-link": "4.3.*",
        "symfony/yaml": "4.3.*"
    },
    "require-dev": {
        "symfony/debug-pack": "*",
        "symfony/maker-bundle": "^1.14",
        "symfony/profiler-pack": "*",
        "symfony/test-pack": "*",
        "symfony/web-server-bundle": "4.3.*"
    },
    "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.3.*"
        }
    }
}

Et une illustration à toutes fins utiles : Capture Merci d'avance pour votre aide !! Bonne journée

Sylius: How to inject data variable of it's own record in a grid rendering

$
0
0

I want to add something to the displaying of the channel of an order grid in admin view depending on some of the products within that order. I would need a way to inject the data of the record into the twig template in example.

Can't figure it out. The grid looks like this:

sylius_grid:
    grids:
        sylius_admin_order:
            driver:
                name: doctrine/orm
                options:
                    class: "%sylius.model.order.class%"
                    repository:
                        method: createListQueryBuilder
            sorting:
                number: desc
            fields:
                ...
                channel:
                    type: twig
                    label: sylius.ui.channel
                    sortable: channel.code
                    options:
                        template: "@SyliusAdmin/Order/Grid/Field/channel.html.twig"

I see that in other columns they add vars: under options: in example like this:

                    options:
                        template: ...
                        vars: 
                            labels: "@SyliusAdmin/Order/Label/State"

but how to do it with itself, I mean with the rest of the data from the record? I would need something like this:

                    options:
                        template: "@SyliusAdmin/Order/Grid/Field/channel.html.twig"
                        vars: 
                            order: self

Does anyone know a way to do that?

Viewing all 3919 articles
Browse latest View live


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