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

How to render Form from a db table and POST into another db table in Symfony 5

$
0
0

I have tables as below:

Table: data_set id   name 1    set1Table: data_set_options id   data_set_id   column_name   column_type   position1        1            color       text           1Table: product id    name 1     product Table: product_optionid    product_id    column_name   value 1        1            color       black

I have form for data_set_options that I can add data into database. This part also be using embedded form as One to Many relationship. This part is working nicely.

Second form product and product_option . product_option will be populated as embedded in the product form as it has One to Many relationship.

I have been trying to solve this way :

in Form/ProducType.php :

...       ->add('productOption',  ProductOptionType::class, ['data_class' => null,'attribute' => $options['attribute'],'label' => false            ])...

AND in Form/ProductOptionType.php

...         ->add('option', EntityType::class, ['class' => DataSetOption::class,'choice_label' => function ($option) {                    return $option->getColumnName();                },'label'     => false,'expanded'  => true,'multiple'  => true,            ])        ->add('value', null, ['row_attr' => ['class' => 'col-xs-12 col-sm-9',                ],            ])...

This solutions is not resolving my purpose as I want to set form from data_set_options and insert or update to product_option

I need your idea / help for this solution. Its open that I can modify database if you recommend better DB design.


UserPasswordEncoderInterface Autowiring Not Working Symfony 4.4

$
0
0

I have a super basic API endpoint with a fresh install of symfony 4.4 and I'm getting the following error:

Cannot autowire argument $passwordEncoder of"App\Controller\AuthenticationController::authenticateAction()": itreferences interface"Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface"but no such service exists.

My Controller:

<?phpnamespace App\Controller;use App\Entity\User;use FOS\RestBundle\Controller\AbstractFOSRestController;use FOS\RestBundle\Controller\Annotations as Rest;use FOS\RestBundle\Controller\Annotations\Route;use Lexik\Bundle\JWTAuthenticationBundle\Encoder\JWTEncoderInterface;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;/** * Class AuthenticationController * * @package App\Controller * @Route("/api/authentication") */class AuthenticationController extends AbstractFOSRestController {    /**     * @Rest\Get("/authenticate")     *     * @param Request                      $request     * @param UserPasswordEncoderInterface $passwordEncoder     * @param JWTEncoderInterface          $JWTEncoder     *     * @return Response     */    public function authenticateAction (Request $request, UserPasswordEncoderInterface $passwordEncoder, JWTEncoderInterface $JWTEncoder) {        exit;    }}

If I remove UserPasswordEncoderInterface $passwordEncoder I get a successful nothing (expected for now). My User Entity is nothing special, and extends UserInterface correctly.

services.yaml

# This file is the entry point to configure your own services.# Files in the packages/ subdirectory configure your dependencies.# Put parameters here that don't need to change on each machine where the app is deployed# https://symfony.com/doc/current/best_practices/configuration.html#application-related-configurationparameters:services:    # default configuration for services in *this* file    _defaults:        autowire: true      # Automatically injects dependencies in your services.        autoconfigure: true # Automatically registers your services as commands, event subscribers, etc.    # makes classes in src/ available to be used as services    # this creates a service per class whose id is the fully-qualified class name    App\:        resource: '../src/'        exclude:            - '../src/DependencyInjection/'            - '../src/Entity/'            - '../src/Kernel.php'            - '../src/Tests/'    # controllers are imported separately to make sure services can be injected    # as action arguments even if you don't extend any base controller class    App\Controller\:        resource: '../src/Controller/'        tags: ['controller.service_arguments']    # add more service definitions when explicit configuration is needed    # please note that last definitions always *replace* previous ones

Using Symfony 4.4 and php 7.2.20

Almost certain this is some sort of configuration issue, but I'm not following what I did wrong.

Export Object to XML file and save in folder with Symfony 5 in a AJAX call

$
0
0

I work with symfony 5 and have a page with Member details. I now want to be able to export the address data from the Member. For that I have a button on the page which calls a function in my Controller via AJAX. If I call the site up directly then I do get the "Save file" Window so I would assume that I do the right thing in my Controller even if I am not 100% sure. I actually do want to force it to save the file in a specific folder. automatically and not me doing it manually and I do want this just on a button click with AJAX, but that does not seem to work. Where am I goin wrong with this?

myjs.js

 $('#exportaddress').on("click", function(){    $.ajax({        type: 'post',        url: "/export-address",        success: function (response) {        }    });});

mycontroller.php

/** * @Route("/export-address", name="export_address") */public function memberExport(){    $memberId= '123';    $em = $this->getDoctrine()->getManager();    $memberData = $em->getRepository(Member::class)->getAddressData($memberId);    $encoders = [new XmlEncoder(), new JsonEncoder()];    $normalizers = [new ObjectNormalizer()];    $serializer = new Serializer($normalizers, $encoders);    $jsonContent = $serializer->serialize($order, 'xml',['groups' => 'address_data']);    return new Response($jsonContent, 200, array('Content-Type' => 'application/force-download','Content-Disposition' => 'attachment; filename="export.xml"'    )); }

GenerateUrl does not respect Localized Routes in Symfony4.4

$
0
0

Introduction

I am using: Symfony v4.4.13 on Windows 10 Pro host (development machine).

In my project i am writing search module.

I have set Localized Routes: en/ru

Requirement

I want to switch locale from english to russian if user inputs search term in russian.

Problem

At the moment i get an error:

No route found for "GET /ru/search/%D1%82%D0%B5%D1%81%D1%82" (from "https://127.0.0.1:8000/en/search")

As seen in error - it happens because it does not translate search keyword to поиск keyword.

Only user's inputed search term is forwarded to next pageroute goods_searchfrom goods_search_no_term and localized route is, seemingly, not taken into account.

The URL shoud be: "/ru/%D0%BF%D0%BE%D0%B8%D1%81%D0%BA/%D1%82%D0%B5%D1%81%D1%82"

witch translates to utf8 "/ru/поиск/тест" instead of "/ru/search/тест"!

Code

/** * @Route({ *     "en": "/search", *     "ru": "/поиск" * }, name="goods_search_no_term", utf8=true) * @Route({ *     "en": "/search/{term}", *     "ru": "/поиск/{term}" * }, name="goods_search", utf8=true) * * @param $term * @param Request $request * @param TranslatorInterface $translator * @param UltraHelpers $ultraHelpers * @return RedirectResponse|Response */public function search(    $term = '',    Request $request,    TranslatorInterface $translator,    UltraHelpers $ultraHelpers){    if ($request->getMethod() === 'GET')    {        $term = $request->get('term');        if (($term !== null) && ($term !== ''))        {            $lang = $request->getLocale();            if ($lang === 'en')            {                if ($ultraHelpers->isRussianText($term))                {                    $link_redirect = $this->generateUrl('goods_search', ['_locale' => 'ru', 'term' => $term]);                    return $this->redirect($link_redirect);                }                $search_items = $repo_item->searchEn($term);            }            elseif ($lang === 'ru')            {                $search_items = $repo_item->searchRu($term);            }        }        return $this->render('search/search.html.twig',            ['search_items' => null,'msg' => null,'term' => $term,'form' => $form->createView()            ]        );    }}public function isRussianText($text){    return preg_match('/[А-Яа-яЁё]/u', $text);}

Finally

Am i hitting a bug (edge case) or is it misconfiguration on my part?

Thank you for suggestions!

Uploads in symfony4

$
0
0

I would like to know the best practices for uploading sensitive documents. To date, my documents are saved in the folder: Public / uploads / passport.Is it secure or should they be saved in another private folder ?Should we encrypt them? what are the securities to take ?Do you have a good tutorial because all explains uploads to the public folder ?

Thanks for your help

Individual column search in table with Symfony and Omines bundle

$
0
0

There is a question about searching by columns in a table. I use Symfony 4 and Omines bundle.

I want to do a individual column search, but it doesn't work. More precisely, it works on the full occurrence of the string. For example, there is a value Donald Trump and a search for "donald trump" will find it. But I would like the search to work on substring as well: ex. "nald".

In this case, the request in the url is formed, but on the server side it does not find matches by the substring. Global search (for the whole table, it add in DOM) works fine. Searches both by full match and by substring.

Do I need to do server side request processing? Or is there a ready-made column search solution in Omines?

Code:

public function list(Request $request, DataTableFactory $dataTableFactory)    {        $table = $dataTableFactory->create()            ->add('firstName', TextColumn::class, ['label' => 'Имя', 'field' => 'c.firstName', 'searchable' => true])            ->add('phone', TextColumn::class, ['label' => 'Телефон', 'field' => 'c.phone', 'searchable' => true])            ->add('email', TextColumn::class, ['label' => 'E-mail', 'field' => 'c.email', 'searchable' => true])            ->add('total', NumberColumn::class, ['label' => 'Суммазаказов', 'field' => 'total.ordersTotal', 'searchable' => false])            ->add('accessCount', NumberColumn::class, ['label' => 'Кол-вовизитов', 'field' => 'c.accessCount', 'searchable' => true])            ->add('firstAccess', DateTimeColumn::class, ['label' => 'Первыйвизит', 'format' => 'd-m-Y h:i', 'field' => 'c.firstAccess', 'searchable' => true])            ->add('lastAccess', DateTimeColumn::class, ['label' => 'Последнийвизит', 'format' => 'd-m-Y h:i', 'field' => 'c.lastAccess', 'searchable' => true])            ->createAdapter(ORMAdapter::class, ['hydrate' => Query::HYDRATE_ARRAY,'entity' => Customer::class,'query' => function (QueryBuilder $builder) {                    $builder                        ->distinct()                        ->select('c.firstName, c.phone, c.email, c.accessCount, c.firstAccess, c.lastAccess, SUM(o.total) AS ordersTotal')                        ->from(Customer::class, 'c')                        ->join('c.orders', 'o')                        ->groupBy('c.id')                        ->getQuery()                        ->getResult()                    ;                },            ])            ->handleRequest($request);        if ($table->isCallback()) {            return $table->getResponse();        }        return $this->render('admin/customer/index.html.twig', ['customers' => $table,        ]);    }

JS:

<script>        $(function () {            $('#customersTable').initDataTables({{ datatable_settings(customers) }}, {                searching: true,                initComplete: function () {                    this.api().columns().every(function () {                        let that = this;                        $('input', this.footer()).on('keyup change clear', function () {                            if (that.search() !== this.value) {                                that                                    .search(this.value)                                    .draw();                            }                        });                        $('option.toggle-vis').on('click', function (e) {                            e.preventDefault();                            let column = that.column($(this).attr('data-column'));                            column.visible(!column.visible());                        });                    });                    let r = $('tfoot tr');                    r.find('th').each(function () {                        $(this).css('padding', 8);                    });                    $('thead').append(r);                    $('#search_0').css('text-align', 'center');                },            }).then(function (dt) {                $('tfoot th').each(function () {                    let title = $(this).text();                    $(this).html('<input type="search" class="form-control form-control-sm" placeholder="Поискпополю'+ title +'" />');                })            });        });</script>

Visual:

Global search

Individual column search

Individual column search with full value

I would be grateful for your help!

Sending "Server Params" through Postman :

$
0
0

Thanks to Symfony HttpFoundation component , we can retrieve the server params like the following script :

   // retrieves SERVER variables    $request->server->get('HTTP_HOST')

So, i have the following construct and i'd like to have the server parameters :

public function __construct(RequestStack $requestStack){$request = $requestStack->getCurrentRequest();$this->country = self::DEFAULT_COUNTRY;$this->lang = self::DEFAULT_LANG;$this->brand = self::DEFAULT_BRAND;$this->jobBrand = $this->brand;if ($request) {    if (!empty($request->server->get(self::ENV_COUNTRY_CODE))) {        $this->country = $request->server->get(self::ENV_COUNTRY_CODE);    }    if (!empty($request->server->get(self::ENV_LANG_CODE))) {        $this->lang = $request->server->get(self::ENV_LANG_CODE);    }    if (!empty($request->server->get(self::ENV_BRAND))) {        $this->jobBrand = $request->server->get(self::ENV_BRAND);        $this->brand = str_replace('pro', '', $this->jobBrand);    }    if (empty($this->country) || empty($this->lang)) {        throw new NoApacheLocaleException();    }}}

For information, during the testing phase, I used Postman as an http client.

So my question is: how can I send my parameters via Postman in order to get it through $request->server->get('param') ?

Custom relation table Symfony 4 and Doctrine

$
0
0

I need help to solve some task about Doctrine Relation Table.

I have two entities:

PropertyGroup

  • ID
  • Name

Property

  • ID
  • Name

This entities have a custom Many To Many relation table with extra column

PropertyAndGroupRel

  • ID
  • PropertyGroupId
  • PropertyId
  • SortKey

How can I select PropertyGroup with QueryBuilder or NativeQuery with using LIMIT and OFFSET in this view:

{  { // PropertyGroup    id: 1,    name: 'XXX',    properties: { // Properties Collection      {        id: 11,        sortKey: 1 // SORT KEY FROM PROPERTY_AND_GROUP_REL,        name: 'XXX'      },      ...    }  }  ...}

Thanks in advance!)


Use Action class instead of Controller in Symfony

$
0
0

I am adherent of Action Class approach using instead of Controller. The explanation is very simple: very often Controller includes many actions, when following the Dependency Injection principle we must pass all required dependencies to a constructor and this makes a situation when the Controller has a huge number of dependencies, but in the certain moment of time (e.g. request) we use only some dependencies. It's hard to maintain and test that spaghetti code.

To clarify, I've already used to work with that approach in Zend Framework 2, but there it's named Middleware. I've found something similar in API-Platform, where they also use Action class instead of Controller, but the problem is that I don't know how to cook it.

UPD:How can I obtain the next Action Class and replace standard Controller and which configuration I should add in regular Symfony project?

<?phpdeclare(strict_types=1);namespace App\Action\Product;use App\Entity\Product;use Doctrine\ORM\EntityManager;use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\Routing\Annotation\Route;class SoftDeleteAction{    /**     * @var EntityManager     */    private $entityManager;    /**     * @param EntityManager $entityManager     */    public function __construct(EntityManager $entityManager)    {        $this->entityManager = $entityManager;    }    /**     * @Route(     *     name="app_product_delete",     *     path="products/{id}/delete"     * )     *     * @Method("DELETE")     *     * @param Product $product     *     * @return Response     */    public function __invoke(Request $request, $id): Response    {        $product = $this->entityManager->find(Product::class, $id);        $product->delete();        $this->entityManager->flush();        return new Response('', 204);    }}

Why my symfony captcha always return valid?

$
0
0

I followed this tutorial to add a captcha to my form.

First I install it using

composer require captcha-com/symfony-captcha-bundle:"4.*"

After I Install it, I got an error on a file called captcha.html.twigError:

captcha Unexpected "spaceless" tag (expecting closing tag for the"block" tag defined near line 2).

So I changed {% spaceless %} to {% apply spaceless %}And the error is gone.

But My captcha bot always returns True (even when I don't even fill it.Here is the ->add() function of my form:

->add('captchaCode', CaptchaType::class, ['captchaConfig' => 'ExampleCaptchaUserRegistration','constraints' => [        new ValidCaptcha(['message' => 'Invalid captcha, please try again',        ]),    ],]);

Code of Routes.yaml :

captcha_routing:    resource: "@CaptchaBundle/Resources/config/routing.yml"

Code of captcha.php :

<?php // app/config/packages/captcha.phpif (!class_exists('CaptchaConfiguration')) { return; }// BotDetect PHP Captcha configuration optionsreturn [    // Captcha configuration for example form'ExampleCaptchaUserRegistration' => ['UserInputID' => 'captchaCode','ImageWidth' => 250,'ImageHeight' => 50,    ],];

Captcha field on the User.php entity:

protected $captchaCode;public function getCaptchaCode(){  return $this->captchaCode;}public function setCaptchaCode($captchaCode){  $this->captchaCode = $captchaCode;}

Code in the View (twig)

<span class="txt1 p-b-11">    Are You a Robot?</span><div class="wrap-input100 m-b-36">    {{ form_widget(form.captchaCode, {'attr': {'class': 'input100'} }) }}       <span class="focus-input100"></span></div><div class="error">{{ form_errors(form.captchaCode) }} </div>

Controlleur function:

/** * @Route("/register", name="user_register", methods={"GET","POST"}) */public function register(Request $request,UserPasswordEncoderInterface $encoder): Response{    $user = new User();    $form = $this->createForm(UserType::class, $user, ['validation_groups' => ['register'], ]);    $form ->remove("description");    $form ->remove("phone");    $form ->remove("website");    $form ->remove("facebook");    $form ->remove("picture");    $form->handleRequest($request);    if ($form->isSubmitted() && $form->isValid()) {        $hash = $encoder->encodePassword($user,$user->getPassword());        $user->setPassword($hash);        // defaults values (user can edit them later)        $user->setDescription("Apparently, this User prefers to keep an air of mystery about them.");        $user->setPhone(null);        $user->setPicture("default.png");        $user->setWebsite(null);        $user->setFacebook(null);        $user->setRoles(["ROLE_USER"]);        // end default values        $entityManager = $this->getDoctrine()->getManager();        $entityManager->persist($user);        $entityManager->flush();        return $this->redirectToRoute('user_login');}    return $this->render('authentication/register.html.twig', ['user' => $user,'form' => $form->createView(),    ]);}

Export Object to XML file and and force file download with Symfony 5 in a AJAX call

$
0
0

I work with symfony 5 and have a page with Member details. I now want to be able to export the address data from the Member. For that I have a button on the page which calls a function in my Controller via AJAX. If I call the site up directly then I do get the "Save file" Window so I would assume that I do the right thing in my Controller even if I am not 100% sure. I actually do want to force it to save the file in a specific folder on the client side automatically and not me doing it manually and I do want this just on a button click with AJAX, but that does not seem to work. Where am I going wrong with this?

myjs.js

 $('#exportaddress').on("click", function(){    $.ajax({        type: 'post',        url: "/export-address",        success: function (response) {        }    });});

mycontroller.php

/** * @Route("/export-address", name="export_address") */public function memberExport(){    $memberId= '123';    $em = $this->getDoctrine()->getManager();    $memberData = $em->getRepository(Member::class)->getAddressData($memberId);    $encoders = [new XmlEncoder(), new JsonEncoder()];    $normalizers = [new ObjectNormalizer()];    $serializer = new Serializer($normalizers, $encoders);    $jsonContent = $serializer->serialize($order, 'xml',['groups' => 'address_data']);    return new Response($jsonContent, 200, array('Content-Type' => 'application/force-download','Content-Disposition' => 'attachment; filename="export.xml"'    )); }

My profiler toolbar isn't showing up in symfony 4.3.1

$
0
0

In my .env file, I have specified my app environment to be dev and debug to be true like so:

APP_ENV=devAPP_DEBUG=true

In my config/packages/dev/web_profiler.yaml file I have the following:

web_profiler:    toolbar: true    intercept_redirects: falseframework:    profiler: { only_exceptions: false }

The routing within config/routes/dev/web_profiler.yaml seems to be fine:

web_profiler_wdt:    resource: '@WebProfilerBundle/Resources/config/routing/wdt.xml'    prefix: /_wdtweb_profiler_profiler:    resource: '@WebProfilerBundle/Resources/config/routing/profiler.xml'    prefix: /_profiler

So when I run the server with symfony server:start everything is fine, but the profiler doesn't appear. Did I miss something that enables that feature within Symfony?

To clarify, the page is outputting a proper HTML page with the appropriate content. There is just no profiler showing up.


My base twig template:

<!DOCTYPE html><html lang="en" dir="ltr"><head><meta charset="utf-8"><title>{% block title %} {% endblock %}</title>        {{ encore_entry_script_tags('base') }}<link rel="icon" type="image/x-icon" href="{{ asset('build/images/favicon.ico') }}" /><link href="https://fonts.googleapis.com/css?family=IBM+Plex+Sans:400,500|Playfair+Display:400,700&display=swap" rel="stylesheet">        {{ encore_entry_link_tags("base") }}        {% block stylesheet %}{% endblock %}</head><body {% if app.request.get('_route') == 'home' %} class='homepage' {% endif %} ><header><div id='top-navigation' class='padding-lg__left-md padding-lg__right-md padding-lg__top-sm padding-lg__bottom-sm row row__align-center row__justify-start'><span class='text-color__white text-size__small text-weight__bold margin-lg__right-lg'>Our Mission</span><span class='text-color__white text-size__small text-weight__bold margin-lg__right-lg'>Our Team</span><span class='text-color__white text-size__small text-weight__bold margin-lg__right-lg'>Where the Money Goes</span><span class='text-color__white text-size__small text-weight__bold margin-lg__right-lg'>Community Leadership</span><span class='text-color__white text-size__small text-weight__bold'>Policies</span><span class='text-color__white text-size__small text-weight__bold margin-lg__left-auto icon-set'> <span class='icon size__small color__white margin-lg__right-xsm'>{{ source('@public_path'~asset('build/images/icons/feedback.svg')) }}</span>Submit Feedback</span></div><nav class="padding-lg__top-md padding-lg__bottom-md padding-lg__left-md padding-lg__right-md row row__align-center row__justify-start {% if app.request.get('_route') == 'home' %} homepage {% endif %}"><div id='logo'><a href="{{ url('home') }}"><img src="{{ asset('build/images/logo_placeholder.png') }}" alt="logo"></a></div>                {% if app.request.get('_route') == 'creator-register' %}                {% else %}                    {% if not is_granted('IS_AUTHENTICATED_FULLY') %}<div class='margin-lg__left-auto'><a href="{{ url('login') }}"><div class='icon-set'><span class='icon margin-lg__right-xsm'>                                        {{ source('@public_path'~asset('build/images/icons/user.svg')) }}</span><span class='nav-item'>Login</span></div></a></div>                    {% endif %}                {% endif %}</nav></header>        {% if app.request.get('_route') != 'home' %} <div class='container is_top'> {% endif %}            {% block body %} {% endblock %}        {% if app.request.get('_route') != 'home' %} </div> {% endif %}</body></html>

Security.yaml firewall:

    firewalls:            dev:                pattern: ^/(_(profiler|wdt)|css|images|js)/                security: false            main:                anonymous: true                guard:                    authenticators:                        - App\Security\LoginFormAuthenticator                logout:                    path : logout                remember_me:                    secret: '%kernel.secret%'                    lifetime: 2592000 #<- 30 days in seconds - defaults to one year if you take this out!

Results on php bin/console debug:router | grep _profiler:

  _profiler_home             ANY      ANY      ANY    /_profiler/                          _profiler_search           ANY      ANY      ANY    /_profiler/search                    _profiler_search_bar       ANY      ANY      ANY    /_profiler/search_bar                _profiler_phpinfo          ANY      ANY      ANY    /_profiler/phpinfo                   _profiler_search_results   ANY      ANY      ANY    /_profiler/{token}/search/results    _profiler_open_file        ANY      ANY      ANY    /_profiler/open                      _profiler                  ANY      ANY      ANY    /_profiler/{token}                   _profiler_router           ANY      ANY      ANY    /_profiler/{token}/router            _profiler_exception        ANY      ANY      ANY    /_profiler/{token}/exception         _profiler_exception_css    ANY      ANY      ANY    /_profiler/{token}/exception.css 

Lastly homepage controller:

<?phpnamespace App\Controller;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\Routing\Annotation\Route;use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;class HomepageController extends AbstractController{    /**    * @Route("/", name="home")    */    public function output(){        return $this->render('homepage/home.html.twig',['title' => 'yo',        ]);    }}?>

Added public/index.php:

<?phpuse App\Kernel;use Symfony\Component\Debug\Debug;use Symfony\Component\HttpFoundation\Request;require dirname(__DIR__).'/config/bootstrap.php';if ($_SERVER['APP_DEBUG']) {    umask(0000);    Debug::enable();}if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? $_ENV['TRUSTED_PROXIES'] ?? false) {    Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST);}if ($trustedHosts = $_SERVER['TRUSTED_HOSTS'] ?? $_ENV['TRUSTED_HOSTS'] ?? false) {    Request::setTrustedHosts([$trustedHosts]);}$kernel = new Kernel($_SERVER['APP_ENV'], (bool) $_SERVER['APP_DEBUG']);$request = Request::createFromGlobals();$response = $kernel->handle($request);$response->send();$kernel->terminate($request, $response);

Symfony 4 serialize entity wihout relations

$
0
0

I've have to log changes of each entities. I've Listener which listen for doctrine's events on preRemove, postUpdate and postDelete.My enity AccessModule has relations:

App\Entity\AccessModule.php

/** * @ORM\OneToMany(targetEntity="App\Entity\AccessModule", mappedBy="parent") * @ORM\OrderBy({"id" = "ASC"}) */private $children;/** * @ORM\ManyToOne(targetEntity="App\Entity\AccessModule", inversedBy="children") * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", nullable=true) */private $parent;/** * @ORM\ManyToMany(targetEntity="App\Entity\AccessModuleRoute", inversedBy="access_modules") * @ORM\JoinTable(name="access_routes", *     joinColumns={@ORM\JoinColumn(name="access_module_id", referencedColumnName="id")}, *     inverseJoinColumns={@ORM\JoinColumn(name="route_id", referencedColumnName="id")}) * */private $routes;

in listener:App\EventListener\EntityListener.php

use Symfony\Component\Serializer\Encoder\JsonEncoder;use Symfony\Component\Serializer\Encoder\XmlEncoder;use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;    $encoders = [new XmlEncoder(), new JsonEncoder()];    $normalizer = new ObjectNormalizer();        $normalizer->setCircularReferenceHandler(function ($object) {            return $object->getId();        });    $this->serializer = new Serializer([$normalizer], $encoders);public function createLog(LifecycleEventArgs $args, $action){    $em = $args->getEntityManager();    $entity = $args->getEntity();    if ($this->tokenStorage->getToken()->getUser()) {        $username = $this->tokenStorage->getToken()->getUser()->getUsername();    } else {        $username = 'anon'; // TODO Remove anon. set null value    }    $log = new Log();//      $log->setData('dddd')        $log->setData($this->serializer->serialize($entity, ''json)            ->setAction($action)            ->setActionTime(new \DateTime())            ->setUser($username)            ->setEntityClass(get_class($entity));        $em->persist($log);        $em->flush();    }

I've problem with serializationWhen I use $log->setData($entity) I get problem with Circular.Whan I do serialization $log->setData($this->serializer->serialize($entity, ''json) I get full of relations, with parent's children, with children children. In a result I get full tree :/I'd like to get

Expect

['id' => ID,'name' => NAME,'parent' => parent_id // ManyToOne, I'd like get its id'children' => [$child_id, $child_id, $child_id] // array of $id of children array collection]

(ofcourse this is draft before encode it to json)

How can I get expected data without full relations?

Symfony 4: Conflict between two firewalls

$
0
0

I currently have two login systems on my Symfony (4.4) application.

Separately (when I comment on one of the two associated firewalls), the two forms work well. But when they are together, the second one doesn't work. (nothing happens, the page simply reloads after submitting the form)

Here is my security.yaml file :

security:    encoders:        App\Entity\User:            algorithm: auto    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers    providers:        # used to reload user from session & other features (e.g. switch_user)        app_user_provider:            entity:                class: App\Entity\User                property: username        app_kit_provider:            entity:                class: App\Entity\Kit                property: serial_number    firewalls:        dev:            pattern: ^/(_(profiler|wdt)|css|images|js)/            security: false        ecert:            pattern: ^/(en|fr)/            anonymous: lazy            provider: app_kit_provider            guard:                authenticators:                    - App\Security\EcertAuthenticator            logout:                path: ecert_logout                target: ecert_login        main:            pattern: ^/(en|fr)/security/            anonymous: lazy            provider: app_user_provider            guard:                authenticators:                    - App\Security\LoginFormAuthenticator            logout:                path: app_logout                target: security_home

LoginFormAuthenticator:

<?phpnamespace App\Security;use App\Entity\User;use Doctrine\ORM\EntityManagerInterface;use Symfony\Component\HttpFoundation\RedirectResponse;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\Routing\Generator\UrlGeneratorInterface;use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;use Symfony\Component\Security\Core\Security;use Symfony\Component\Security\Core\User\UserInterface;use Symfony\Component\Security\Core\User\UserProviderInterface;use Symfony\Component\Security\Csrf\CsrfToken;use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;use Symfony\Component\Security\Http\Util\TargetPathTrait;class LoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface{    use TargetPathTrait;    public const LOGIN_ROUTE = 'app_login';    private $entityManager;    private $urlGenerator;    private $csrfTokenManager;    private $passwordEncoder;    public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)    {        $this->entityManager = $entityManager;        $this->urlGenerator = $urlGenerator;        $this->csrfTokenManager = $csrfTokenManager;        $this->passwordEncoder = $passwordEncoder;    }    public function supports(Request $request)    {        return self::LOGIN_ROUTE === $request->attributes->get('_route')&& $request->isMethod('POST');    }    public function getCredentials(Request $request)    {        $credentials = ['username' => $request->request->get('username'),'password' => $request->request->get('password'),'csrf_token' => $request->request->get('_csrf_token'),        ];        $request->getSession()->set(            Security::LAST_USERNAME,            $credentials['username']        );        return $credentials;    }    public function getUser($credentials, UserProviderInterface $userProvider)    {        $token = new CsrfToken('authenticate', $credentials['csrf_token']);        if (!$this->csrfTokenManager->isTokenValid($token)) {            throw new InvalidCsrfTokenException();        }        $user = $this->entityManager->getRepository(User::class)->findOneBy(['username' => $credentials['username']]);        if (!$user) {            // fail authentication with a custom error            throw new CustomUserMessageAuthenticationException('Username could not be found.');        }        return $user;    }    public function checkCredentials($credentials, UserInterface $user)    {        return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);    }    /**     * Used to upgrade (rehash) the user's password automatically over time.     */    public function getPassword($credentials): ?string    {        return $credentials['password'];    }    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)    {        if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {            return new RedirectResponse($targetPath);        }        return new RedirectResponse($this->urlGenerator->generate('create_kit'));    }    protected function getLoginUrl()    {        return $this->urlGenerator->generate(self::LOGIN_ROUTE);    }}

EcertAuthenticator:

<?phpnamespace App\Security;use App\Entity\Kit;use Doctrine\ORM\EntityManagerInterface;use Symfony\Component\HttpFoundation\RedirectResponse;use Symfony\Component\HttpFoundation\Request;use Symfony\Component\Routing\Generator\UrlGeneratorInterface;use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;use Symfony\Component\Security\Core\Security;use Symfony\Component\Security\Core\User\UserInterface;use Symfony\Component\Security\Core\User\UserProviderInterface;use Symfony\Component\Security\Csrf\CsrfToken;use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;use Symfony\Component\Security\Http\Util\TargetPathTrait;class EcertAuthenticator extends AbstractFormLoginAuthenticator{    use TargetPathTrait;    public const LOGIN_ROUTE = 'ecert_login';    private $entityManager;    private $urlGenerator;    private $csrfTokenManager;    public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager)    {        $this->entityManager = $entityManager;        $this->urlGenerator = $urlGenerator;        $this->csrfTokenManager = $csrfTokenManager;    }    public function supports(Request $request)    {        return self::LOGIN_ROUTE === $request->attributes->get('_route')&& $request->isMethod('POST');    }    public function getCredentials(Request $request)    {        $credentials = ['serial_number' => $request->request->get('serial_number'),'random_key' => $request->request->get('random_key'),'csrf_token' => $request->request->get('_csrf_token'),        ];        $request->getSession()->set(            Security::LAST_USERNAME,            $credentials['serial_number']        );        return $credentials;    }    public function getUser($credentials, UserProviderInterface $userProvider)    {        $token = new CsrfToken('authenticate', $credentials['csrf_token']);        if (!$this->csrfTokenManager->isTokenValid($token)) {            throw new InvalidCsrfTokenException();        }        $user = $this->entityManager->getRepository(Kit::class)->findOneBy(['serial_number' => $credentials['serial_number']]);        if (!$user) {            // fail authentication with a custom error            throw new CustomUserMessageAuthenticationException('Serial_number could not be found.');        }        return $user;    }    public function checkCredentials($credentials, UserInterface $user)    {        if ($this->entityManager->getRepository(Kit::class)->findOneBy(['serial_number' => $credentials['serial_number'], 'random_key' => $credentials['random_key']])) {            return true;        }        return false;    }    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)    {        if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {            return new RedirectResponse($targetPath);        }        return new RedirectResponse($this->urlGenerator->generate('ecert'));    }    protected function getLoginUrl()    {        return $this->urlGenerator->generate(self::LOGIN_ROUTE);    }}

Do you know why?

Thanks

ApiPltaform - GraphQL Issue - Null value in DatetimeType field throw "Resource \"DateTime\" not found"

$
0
0

API Platform version(s) affected: v2.5.7 (symfony v4.4.13 on PHP 7.4)

Description
I have an Entity with a field typed with a custom type.

It works great if the field isn't null.

If there is an item with a null value, it throw a "Resource \"DateTime\" not found

I created a custom DateTimeType, I have some item with null values on field typed by that custom type.

If there is a null value in the result I get such error :

{"errors": [    {"debugMessage": "Resource \"DateTime\" not found.","message": "Internal server error","extensions": {"category": "internal"      },"locations": [        {"line": 6,"column": 9        }      ],"path": ["users","edges",        1,"node","sampleNullableDate"      ],"trace": [        {"file": "/var/www/app/vendor/api-platform/core/src/Metadata/Resource/Factory/AnnotationResourceFilterMetadataFactory.php","line": 55,"call": "ApiPlatform\\Core\\Metadata\\Resource\\Factory\\AnnotationResourceFilterMetadataFactory::handleNotFound(null, 'DateTime')"        },        {"file": "/var/www/app/vendor/api-platform/core/src/Metadata/Resource/Factory/OperationResourceMetadataFactory.php","line": 57,"call": "ApiPlatform\\Core\\Metadata\\Resource\\Factory\\AnnotationResourceFilterMetadataFactory::create('DateTime')"        },        {"file": "/var/www/app/vendor/api-platform/core/src/Metadata/Resource/Factory/FormatsResourceMetadataFactory.php","line": 53,"call": "ApiPlatform\\Core\\Metadata\\Resource\\Factory\\OperationResourceMetadataFactory::create('DateTime')"        },        {"file": "/var/www/app/vendor/api-platform/core/src/Metadata/Resource/Factory/CachedResourceMetadataFactory.php","line": 47,"call": "ApiPlatform\\Core\\Metadata\\Resource\\Factory\\FormatsResourceMetadataFactory::create('DateTime')"        },        {"file": "/var/www/app/vendor/api-platform/core/src/Cache/CachedTrait.php","line": 44,"call": "ApiPlatform\\Core\\Metadata\\Resource\\Factory\\CachedResourceMetadataFactory::ApiPlatform\\Core\\Metadata\\Resource\\Factory\\{closure}()"        },        {"file": "/var/www/app/vendor/api-platform/core/src/Metadata/Resource/Factory/CachedResourceMetadataFactory.php","line": 48,"call": "ApiPlatform\\Core\\Metadata\\Resource\\Factory\\CachedResourceMetadataFactory::getCached('resource_metadata_8cf10d2341ed01492506085688270c1e', instance of Closure)"        },        {"file": "/var/www/app/vendor/api-platform/core/src/GraphQl/Resolver/Stage/ReadStage.php","line": 60,"call": "ApiPlatform\\Core\\Metadata\\Resource\\Factory\\CachedResourceMetadataFactory::create('DateTime')"        },        {"file": "/var/www/app/vendor/api-platform/core/src/GraphQl/Resolver/Factory/ItemResolverFactory.php","line": 70,"call": "ApiPlatform\\Core\\GraphQl\\Resolver\\Stage\\ReadStage::__invoke('DateTime', 'App\\Entity\\User', 'item_query', array(5))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 630,"call": "ApiPlatform\\Core\\GraphQl\\Resolver\\Factory\\ItemResolverFactory::ApiPlatform\\Core\\GraphQl\\Resolver\\Factory\\{closure}(array(4), array(0), null, instance of GraphQL\\Type\\Definition\\ResolveInfo)"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 557,"call": "GraphQL\\Executor\\ReferenceExecutor::resolveFieldValueOrError(instance of GraphQL\\Type\\Definition\\FieldDefinition, instance of GraphQL\\Language\\AST\\FieldNode, instance of Closure, array(4), instance of GraphQL\\Type\\Definition\\ResolveInfo)"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 1200,"call": "GraphQL\\Executor\\ReferenceExecutor::resolveField(GraphQLType: User, array(4), instance of ArrayObject(1), array(5))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 1147,"call": "GraphQL\\Executor\\ReferenceExecutor::executeFields(GraphQLType: User, array(4), array(4), instance of ArrayObject(2))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 1106,"call": "GraphQL\\Executor\\ReferenceExecutor::collectAndExecuteSubfields(GraphQLType: User, instance of ArrayObject(1), array(4), array(4))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 796,"call": "GraphQL\\Executor\\ReferenceExecutor::completeObjectValue(GraphQLType: User, instance of ArrayObject(1), instance of GraphQL\\Type\\Definition\\ResolveInfo, array(4), array(4))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 662,"call": "GraphQL\\Executor\\ReferenceExecutor::completeValue(GraphQLType: User, instance of ArrayObject(1), instance of GraphQL\\Type\\Definition\\ResolveInfo, array(4), array(4))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 564,"call": "GraphQL\\Executor\\ReferenceExecutor::completeValueCatchingError(GraphQLType: User, instance of ArrayObject(1), instance of GraphQL\\Type\\Definition\\ResolveInfo, array(4), array(4))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 1200,"call": "GraphQL\\Executor\\ReferenceExecutor::resolveField(GraphQLType: UserEdge, array(2), instance of ArrayObject(1), array(4))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 1147,"call": "GraphQL\\Executor\\ReferenceExecutor::executeFields(GraphQLType: UserEdge, array(2), array(3), instance of ArrayObject(1))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 1106,"call": "GraphQL\\Executor\\ReferenceExecutor::collectAndExecuteSubfields(GraphQLType: UserEdge, instance of ArrayObject(1), array(3), array(2))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 796,"call": "GraphQL\\Executor\\ReferenceExecutor::completeObjectValue(GraphQLType: UserEdge, instance of ArrayObject(1), instance of GraphQL\\Type\\Definition\\ResolveInfo, array(3), array(2))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 662,"call": "GraphQL\\Executor\\ReferenceExecutor::completeValue(GraphQLType: UserEdge, instance of ArrayObject(1), instance of GraphQL\\Type\\Definition\\ResolveInfo, array(3), array(2))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 895,"call": "GraphQL\\Executor\\ReferenceExecutor::completeValueCatchingError(GraphQLType: UserEdge, instance of ArrayObject(1), instance of GraphQL\\Type\\Definition\\ResolveInfo, array(3), array(2))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 764,"call": "GraphQL\\Executor\\ReferenceExecutor::completeListValue(GraphQLType: UserEdge, instance of ArrayObject(1), instance of GraphQL\\Type\\Definition\\ResolveInfo, array(2), array(2))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 662,"call": "GraphQL\\Executor\\ReferenceExecutor::completeValue(GraphQLType: UserEdge, instance of ArrayObject(1), instance of GraphQL\\Type\\Definition\\ResolveInfo, array(2), array(2))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 564,"call": "GraphQL\\Executor\\ReferenceExecutor::completeValueCatchingError(GraphQLType: UserEdge, instance of ArrayObject(1), instance of GraphQL\\Type\\Definition\\ResolveInfo, array(2), array(2))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 1200,"call": "GraphQL\\Executor\\ReferenceExecutor::resolveField(GraphQLType: UserConnection, array(3), instance of ArrayObject(1), array(2))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 1147,"call": "GraphQL\\Executor\\ReferenceExecutor::executeFields(GraphQLType: UserConnection, array(3), array(1), instance of ArrayObject(1))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 1106,"call": "GraphQL\\Executor\\ReferenceExecutor::collectAndExecuteSubfields(GraphQLType: UserConnection, instance of ArrayObject(1), array(1), array(3))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 796,"call": "GraphQL\\Executor\\ReferenceExecutor::completeObjectValue(GraphQLType: UserConnection, instance of ArrayObject(1), instance of GraphQL\\Type\\Definition\\ResolveInfo, array(1), array(3))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 662,"call": "GraphQL\\Executor\\ReferenceExecutor::completeValue(GraphQLType: UserConnection, instance of ArrayObject(1), instance of GraphQL\\Type\\Definition\\ResolveInfo, array(1), array(3))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 564,"call": "GraphQL\\Executor\\ReferenceExecutor::completeValueCatchingError(GraphQLType: UserConnection, instance of ArrayObject(1), instance of GraphQL\\Type\\Definition\\ResolveInfo, array(1), array(3))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 1200,"call": "GraphQL\\Executor\\ReferenceExecutor::resolveField(GraphQLType: Query, null, instance of ArrayObject(1), array(1))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 258,"call": "GraphQL\\Executor\\ReferenceExecutor::executeFields(GraphQLType: Query, null, array(0), instance of ArrayObject(1))"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/ReferenceExecutor.php","line": 209,"call": "GraphQL\\Executor\\ReferenceExecutor::executeOperation(instance of GraphQL\\Language\\AST\\OperationDefinitionNode, null)"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/Executor/Executor.php","line": 155,"call": "GraphQL\\Executor\\ReferenceExecutor::doExecute()"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/GraphQL.php","line": 162,"call": "GraphQL\\Executor\\Executor::promiseToExecute(instance of GraphQL\\Executor\\Promise\\Adapter\\SyncPromiseAdapter, instance of GraphQL\\Type\\Schema, instance of GraphQL\\Language\\AST\\DocumentNode, null, null, array(0), null, null)"        },        {"file": "/var/www/app/vendor/webonyx/graphql-php/src/GraphQL.php","line": 94,"call": "GraphQL\\GraphQL::promiseToExecute(instance of GraphQL\\Executor\\Promise\\Adapter\\SyncPromiseAdapter, instance of GraphQL\\Type\\Schema, 'query {\n  users (first: 2) {\n    edges {\n      node {\n        username,\n        sampleNullableDate\n      }\n    }\n  }\n}', null, null, array(0), null, null, null)"        },        {"file": "/var/www/app/vendor/api-platform/core/src/GraphQl/Executor.php","line": 34,"call": "GraphQL\\GraphQL::executeQuery(instance of GraphQL\\Type\\Schema, 'query {\n  users (first: 2) {\n    edges {\n      node {\n        username,\n        sampleNullableDate\n      }\n    }\n  }\n}', null, null, array(0), null, null, null)"        },        {"file": "/var/www/app/vendor/api-platform/core/src/GraphQl/Action/EntrypointAction.php","line": 78,"call": "ApiPlatform\\Core\\GraphQl\\Executor::executeQuery(instance of GraphQL\\Type\\Schema, 'query {\n  users (first: 2) {\n    edges {\n      node {\n        username,\n        sampleNullableDate\n      }\n    }\n  }\n}', null, null, array(0), null)"        },        {"file": "/var/www/app/vendor/symfony/http-kernel/HttpKernel.php","line": 158,"call": "ApiPlatform\\Core\\GraphQl\\Action\\EntrypointAction::__invoke(instance of Symfony\\Component\\HttpFoundation\\Request)"        },        {"file": "/var/www/app/vendor/symfony/http-kernel/HttpKernel.php","line": 80,"call": "Symfony\\Component\\HttpKernel\\HttpKernel::handleRaw(instance of Symfony\\Component\\HttpFoundation\\Request, 1)"        },        {"file": "/var/www/app/vendor/symfony/http-kernel/Kernel.php","line": 201,"call": "Symfony\\Component\\HttpKernel\\HttpKernel::handle(instance of Symfony\\Component\\HttpFoundation\\Request, 1, true)"        },        {"file": "/var/www/app/public/index.php","line": 25,"call": "Symfony\\Component\\HttpKernel\\Kernel::handle(instance of Symfony\\Component\\HttpFoundation\\Request)"        }      ]    }  ],"data": {"users": {"edges": [        {"node": {"username": "user OK with date not null","sampleNullableDate": "07-09-2020 09:09:03"          }        },        {"node": {"username": "user NOK with null date","sampleNullableDate": null          }        }      ]    }  }}

How to reproduce

Following that documentation: https://api-platform.com/docs/core/graphql/#custom-types

And this one : https://api-platform.com/docs/core/graphql/#custom-types

And having at least a field with a null value.

Here is a test project to reproduce : https://github.com/bastoune/api-platform-test-project/tree/issue/DateTimeType


Want to create a query to get all questions for each test

$
0
0

I have a problem to get some data : I'm using Symfony version 4.19.0

Ihave 2 entities : Question and TestTechnique

--> I have a ManyToOne relation, a question is onnected by one and only one testTechnique, and a testTechnique can be composed by some many questions.

ENTITY Question

<?phpnamespace App\Entity;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Doctrine\ORM\Mapping as ORM;/** * @ORM\Entity(repositoryClass=QuestionRepository::class) */class Question{    /**     * @ORM\Id     * @ORM\GeneratedValue     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="string")     */    private $enonce;    /**     * @ORM\Column(type="boolean")     */    private $estEliminatoire;    /**     * @ORM\Column(type="boolean")     */    private $estActif;    /**     * @ORM\ManyToOne(targetEntity=Domaine::class, inversedBy="questions")     * @ORM\JoinColumn(nullable=false)     */    private $domaine;    /**     * @ORM\ManyToOne(targetEntity=Niveau::class, inversedBy="questions")     * @ORM\JoinColumn(nullable=false)     */    private $niveau;    /**     * @ORM\OneToMany(targetEntity=ReponsePossible::class, mappedBy="question", orphanRemoval=true)     */    private $reponsesPossibles;    /**     * @ORM\ManyToMany(targetEntity=Administrateur::class, mappedBy="questions")     */    private $administrateurs;    /**     * @ORM\ManyToOne(targetEntity=TestTechnique::class, inversedBy="questions")     */    private $testTechnique;    public function __construct()    {        $this->reponsesPossibles = new ArrayCollection();        $this->administrateurs = new ArrayCollection();    }    public function getId(): ?int    {        return $this->id;    }    public function getEnonce(): ?string    {        return $this->enonce;    }    public function setEnonce(string $enonce): self    {        $this->enonce = $enonce;        return $this;    }    public function getEstEliminatoire(): ?bool    {        return $this->estEliminatoire;    }    public function setEstEliminatoire(bool $estEliminatoire): self    {        $this->estEliminatoire = $estEliminatoire;        return $this;    }    public function getEstActif(): ?bool    {        return $this->estActif;    }    public function setEstActif(bool $estActif): self    {        $this->estActif = $estActif;        return $this;    }    public function getDomaine(): ?Domaine    {        return $this->domaine;    }    public function setDomaine(?Domaine $domaine): self    {        $this->domaine = $domaine;        return $this;    }    public function getNiveau(): ?Niveau    {        return $this->niveau;    }    public function setNiveau(?Niveau $niveau): self    {        $this->niveau = $niveau;        return $this;    }    /**     * @return Collection|ReponsePossible[]     */    public function getReponsesPossibles(): Collection    {        return $this->reponsesPossibles;    }    public function addReponsesPossible(ReponsePossible $reponsesPossible): self    {        if (!$this->reponsesPossibles->contains($reponsesPossible)) {            $this->reponsesPossibles[] = $reponsesPossible;            $reponsesPossible->setQuestion($this);        }        return $this;    }    public function removeReponsesPossible(ReponsePossible $reponsesPossible): self    {        if ($this->reponsesPossibles->contains($reponsesPossible)) {            $this->reponsesPossibles->removeElement($reponsesPossible);            // set the owning side to null (unless already changed)            if ($reponsesPossible->getQuestion() === $this) {                $reponsesPossible->setQuestion(null);            }        }        return $this;    }    /**     * @return Collection|Administrateur[]     */    public function getAdministrateurs(): Collection    {        return $this->administrateurs;    }    public function addAdministrateur(Administrateur $administrateur): self    {        if (!$this->administrateurs->contains($administrateur)) {            $this->administrateurs[] = $administrateur;            $administrateur->addQuestion($this);        }        return $this;    }    public function removeAdministrateur(Administrateur $administrateur): self    {        if ($this->administrateurs->contains($administrateur)) {            $this->administrateurs->removeElement($administrateur);            $administrateur->removeQuestion($this);        }        return $this;    }    public function __toString()    {    return (string) $this->getId(). " - " .$this->getEnonce();    }    public function getTestTechnique(): ?TestTechnique    {        return $this->testTechnique;    }    public function setTestTechnique(?TestTechnique $testTechnique): self    {        $this->testTechnique = $testTechnique;        return $this;    }}

ENTITY TestTechnique

<?phpnamespace App\Entity;use App\Repository\TestTechniqueRepository;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Doctrine\ORM\Mapping as ORM;/** * @ORM\Entity(repositoryClass=TestTechniqueRepository::class) */class TestTechnique{    /**     * @ORM\Id     * @ORM\GeneratedValue     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\OneToMany(targetEntity=InfoCo::class, mappedBy="testTechnique")     */    private $infoCos;    /**     * @ORM\ManyToOne(targetEntity=Administrateur::class, inversedBy="testsTechniques")     */    private $administrateur;    /**     * @ORM\Column(type="datetime", nullable=true)     */    private $date;    /**     * @ORM\Column(type="string", length=255, nullable=true)     */    private $intitule;    /**     * @ORM\OneToMany(targetEntity=Question::class, mappedBy="testTechnique")     */    private $questions;    public function __construct()    {        $this->infoCos = new ArrayCollection();        $this->questions = new ArrayCollection();    }    public function getId(): ?int    {        return $this->id;    }    /**     * @return Collection|InfoCo[]     */    public function getInfoCos(): Collection    {        return $this->infoCos;    }    public function addInfoCo(InfoCo $infoCo): self    {        if (!$this->infoCos->contains($infoCo)) {            $this->infoCos[] = $infoCo;            $infoCo->setTestTechnique($this);        }        return $this;    }    public function removeInfoCo(InfoCo $infoCo): self    {        if ($this->infoCos->contains($infoCo)) {            $this->infoCos->removeElement($infoCo);            // set the owning side to null (unless already changed)            if ($infoCo->getTestTechnique() === $this) {                $infoCo->setTestTechnique(null);            }        }        return $this;    }    public function getAdministrateur(): ?Administrateur    {        return $this->administrateur;    }    public function setAdministrateur(?Administrateur $administrateur): self    {        $this->administrateur = $administrateur;        return $this;    }    public function __toString()    {    return (string) $this->getIntitule();    }    public function getDate(): ?\DateTimeInterface    {        return $this->date;    }    public function setDate(?\DateTimeInterface $date): self    {        $this->date = $date;        return $this;    }    public function getIntitule(): ?string    {        return $this->intitule;    }    public function setIntitule(?string $intitule): self    {        $this->intitule = $intitule;        return $this;    }    /**     * @return Collection|Question[]     */    public function getQuestions(): Collection    {        return $this->questions;    }    public function addQuestion(Question $question): self    {        if (!$this->questions->contains($question)) {            $this->questions[] = $question;            $question->setTestTechnique($this);        }        return $this;    }    public function removeQuestion(Question $question): self    {        if ($this->questions->contains($question)) {            $this->questions->removeElement($question);            // set the owning side to null (unless already changed)            if ($question->getTestTechnique() === $this) {                $question->setTestTechnique(null);            }        }        return $this;    }}

I want to get all questions for each TestTechnique :

So I tried, on my TestTechniqueController:

/**     * @IsGranted("ROLE_ADMIN")     * @Route("/{id}", name="test_technique_show", methods={"GET"})     */    public function show(Request $request, TestTechnique $testTechnique, QuestionRepository $questionRepository): Response    {        $id = $request->query->get('id');        $questions = $questionRepository->findQuestionsForEachTest($id);        return $this->render('test_technique/show.html.twig', ['test_technique' => $testTechnique,'questions' => $questions,            ]);    }

and this is the QuestionRepository :

public function findQuestionsForEachTest($id)    {        return $this->createQueryBuilder('q')            ->innerJoin('q.testTechnique', 'testTechnique')            ->andWhere('q.testTechnique = :val')            ->setParameter('val', $id)            ->orderBy('q.id', 'ASC')            ->getQuery()            ->getResult()            ;    }

and this my view, for each TestTechnique, I want to display all questions who composed this Test:

{% for question in questions %}<tr><td>{{ question.id }}</td><td>{{ question.enonce }}</td>            </tr>        {% endfor %}

My difficulty is there, I need to get the id of the TestTechnique to display only the questions for this test.

Sorry for my bad english, and thank you I need your help ^^

How can I customize form fields IDs in Symfony 4?

$
0
0

I'm building a web page in Symfony that is built with multiple instances of the same form, but with different POST urls. I want to intercept the submit with javascript, and do a simple AJAX POST.

The structure of this page is this:

<h1>Title</h1>{% for document in documents %}<div id="form_{{ document.id }}">        {{ form(document.form) }}<input type="submit">Submit button</input></div>{% endfor %}<hr />

If I have 4 documents in the documents array, 4 forms will be rendered. The problem is that all the documents fields will have the same ID: there will be 4 document_csrf, 4 document_title title, and so, because all documents are views of the DocumentType form.

What I want is to add something to the generation of the form, so each form field is rendered with unique fieldnames: document_csrf1, document_title_1, document_csrf2, document_title_2, etc.

I've been looking around StackOverflow and the Symfony Documentation, but I can't find anything. I can pass an ['attr'] => ['id' => $id]] then calling the createForm function, but this ID is only used for the <form> tag, not the other fields...

Is there any way to automatically add an ID to the form, or should I render the form adding the id to each element ({{ form_widget(form.name, {'attr': {'id': 'document_name' ~ document.id}}) }})?

Thank you for your help!

Symfony $form->getData() return empty Object with values concatenated

$
0
0

This is my controller

/** * @Route("/offre/add", name="offre_add") * @param Request $request * @return RedirectResponse|Response * @throws \Exception */public function addOffre(Request $request) {    $offre = new Offre();    $em = $this->getDoctrine()->getManager();    $formOffre = $this->createForm(OffreType::class, $offre);    $formOffre->handleRequest($request);    if ($formOffre->isSubmitted() && $formOffre->isValid()) {        $offre = $formOffre->getData();        dd($offre);    }    return $this->render('admin/offre/add_offre.html.twig', ['form' => $formOffre->createView()    ]);}

And this is my OffreType

<?phpnamespace App\Form;use Symfony\Component\Form\AbstractType;use Symfony\Component\Form\Extension\Core\Type\SubmitType;use Symfony\Component\Form\Extension\Core\Type\TextareaType;use Symfony\Component\Form\FormBuilderInterface;use Symfony\Component\Form\Extension\Core\Type\TextType;use Symfony\Component\Form\Extension\Core\Type\ChoiceType;use Symfony\Component\OptionsResolver\OptionsResolver;class OffreType extends AbstractType {    /**     * @param FormBuilderInterface $builder     * @param array $options     */    public function buildForm(FormBuilderInterface $builder, array $options) {        $builder            ->add('numeroOffre', TextType::class)            ->add('version', TextType::class)            ->add('statut', TextType::class)            ->add('signature', TextType::class)            ->add('prixTotal', TextType::class)            ->add('commentaire', TextareaType::class)            ->add('visibilite', ChoiceType::class, array('choices' => array('Oui' => 'Oui','Non' => 'Non')            ))            ->add('save', SubmitType::class)        ;    }    /**     * @param OptionsResolver $resolver     */    public function configureOptions(OptionsResolver $resolver) {        $resolver->setDefaults(array('data_class' => 'App\Entity\Offre'        ));    }}

When I try to validate my form like this :

enter image description here

The result is an empty Object, and the values I inserted in my form are concatenated to my object (with the same Key/Value)

enter image description here

If I print the $_POST variable, the form seems to works fine

enter image description here

Why is the method getData() not working ?

edit:

This is my Offre Class

<?phpnamespace App\Entity;use DateTime;use Doctrine\ORM\Mapping as ORM;/** * Offre * * @ORM\Table(name="offre") * @ORM\Entity(repositoryClass="App\Repository\OffreRepository") */class Offre{    /**     * @var int     *     * @ORM\Column(name="id", type="integer")     * @ORM\Id     * @ORM\GeneratedValue(strategy="AUTO")     */    private $id;    /**     * @var string     *     * @ORM\Column(name="numero_offre", type="string", length=50)     */    private $numeroOffre;    /**     * @var string     *     * @ORM\Column(name="statut", type="string", length=255, nullable=true)     */    private $statut;    /**     * @var string     *     * @ORM\Column(name="version", type="string", length=255, nullable=true)     */    private $version;    /**     * @var string     *     * @ORM\Column(name="signature", type="string", length=255, nullable=true)     */    private $signature;    /**     * @var string     *     * @ORM\Column(name="commentaire", type="string", length=255, nullable=true)     */    private $commentaire;    /**     * @var string     *     * @ORM\Column(name="visibilite", type="string", length=255)     */    private $visibilite;    /**     * @var string     *     * @ORM\Column(name="prix_total", type="string", length=255)     */    private $prixTotal;    /**     * @var DateTime     *     * @ORM\Column(name="date_create", type="date", nullable=true)     */    private $dateCreate;    /**     * @var string     *     * @ORM\Column(name="user_create", type="string", length=255)     */    private $userCreate;    /**     * @var DateTime     *     * @ORM\Column(name="date_change", type="date", nullable=true)     */    private $dateChange;    /**     * @var string     *     * @ORM\Column(name="user_change", type="string", length=255, nullable=true)     */    private $userChange;    /**     * @var boolean     *     * @ORM\Column(name="active", type="boolean")     */    private $active = true;    /**     * @ORM\ManyToOne(targetEntity=Client::class, inversedBy="offres")     */    private $client;    /**     * @return int     */    public function getId()    {        return $this->id;    }    /**     * @param int $id     */    public function setId($id)    {        $this->id = $id;    }    /**     * @return string     */    public function getNumeroOffre()    {        return $this->numeroOffre;    }    /**     * @param string $numeroOffre     */    public function setNumeroOffre($numeroOffre)    {        $this->$numeroOffre = $numeroOffre;    }    /**     * @return string     */    public function getPrixTotal()    {        return $this->prixTotal;    }    /**     * @param string $prixTotal     */    public function setPrixTotal($prixTotal)    {        $this->$prixTotal = $prixTotal;    }    /**     * @return string     */    public function getStatut()    {        return $this->statut;    }    /**     * @param string $statut     */    public function setStatut($statut)    {        $this->$statut = $statut;    }    /**     * @return string     */    public function getVersion()    {        return $this->version;    }    /**     * @param string $version     */    public function setVersion($version)    {        $this->$version = $version;    }    /**     * @return string     */    public function getSignature()    {        return $this->signature;    }    /**     * @param string $signature     */    public function setSignature($signature)    {        $this->$signature = $signature;    }    /**     * @return string     */    public function getCommentaire()    {        return $this->commentaire;    }    /**     * @param string $commentaire     */    public function setCommentaire($commentaire)    {        $this->$commentaire = $commentaire;    }    /**     * @return string     */    public function getVisibilite()    {        return $this->visibilite;    }    /**     * @param string $visibilite     */    public function setVisibilite($visibilite)    {        $this->$visibilite = $visibilite;    }    /**     * @return DateTime     */    public function getDateCreate()    {        return $this->dateCreate;    }    /**     * @param DateTime $dateCreate     */    public function setDateCreate($dateCreate)    {        $this->dateCreate = $dateCreate;    }    /**     * @return string     */    public function getUserCreate()    {        return $this->userCreate;    }    /**     * @param string $userCreate     */    public function setUserCreate($userCreate)    {        $this->userCreate = $userCreate;    }    /**     * @return DateTime     */    public function getDateChange()    {        return $this->dateChange;    }    /**     * @param DateTime $dateChange     */    public function setDateChange($dateChange)    {        $this->dateChange = $dateChange;    }    /**     * @return string     */    public function getUserChange()    {        return $this->userChange;    }    /**     * @param string $userChange     */    public function setUserChange(string $userChange)    {        $this->userChange = $userChange;    }    /**     * @return bool     */    public function isActive()    {        return $this->active;    }    /**     * @param bool $active     */    public function setActive(bool $active)    {        $this->active = $active;    }    public function getClient()    {        return $this->client;    }    public function setClient(?Client $client)    {        $this->client = $client;        return $this;    }}

how to select an element inside FormType symfony?

$
0
0

this works fine

  $(document).ready(function () {        $('#banner_description').on('keyup', function () {            alert( this.value );        })    });

and when i need to catch the change event when i do upload images its doesn't work i would like to allow to upload just 4 images there is any solution ?

    $('#banner_images').on('upload', function () {        alert( this.value.length );    })

Form Type inspecct

Want to create a query to get all questions for each test

$
0
0

I have a problem to get some data : I'm using Symfony version 4.19.0

Ihave 2 entities : Question and TestTechnique

--> I have a ManyToOne relation, a question is onnected by one and only one testTechnique, and a testTechnique can be composed by some many questions.

ENTITY Question

<?phpnamespace App\Entity;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Doctrine\ORM\Mapping as ORM;/** * @ORM\Entity(repositoryClass=QuestionRepository::class) */class Question{    /**     * @ORM\Id     * @ORM\GeneratedValue     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="string")     */    private $enonce;    /**     * @ORM\Column(type="boolean")     */    private $estEliminatoire;    /**     * @ORM\Column(type="boolean")     */    private $estActif;    /**     * @ORM\ManyToOne(targetEntity=Domaine::class, inversedBy="questions")     * @ORM\JoinColumn(nullable=false)     */    private $domaine;    /**     * @ORM\ManyToOne(targetEntity=Niveau::class, inversedBy="questions")     * @ORM\JoinColumn(nullable=false)     */    private $niveau;    /**     * @ORM\OneToMany(targetEntity=ReponsePossible::class, mappedBy="question", orphanRemoval=true)     */    private $reponsesPossibles;    /**     * @ORM\ManyToMany(targetEntity=Administrateur::class, mappedBy="questions")     */    private $administrateurs;    /**     * @ORM\ManyToOne(targetEntity=TestTechnique::class, inversedBy="questions")     */    private $testTechnique;    public function __construct()    {        $this->reponsesPossibles = new ArrayCollection();        $this->administrateurs = new ArrayCollection();    }    public function getId(): ?int    {        return $this->id;    }    public function getEnonce(): ?string    {        return $this->enonce;    }    public function setEnonce(string $enonce): self    {        $this->enonce = $enonce;        return $this;    }    public function getEstEliminatoire(): ?bool    {        return $this->estEliminatoire;    }    public function setEstEliminatoire(bool $estEliminatoire): self    {        $this->estEliminatoire = $estEliminatoire;        return $this;    }    public function getEstActif(): ?bool    {        return $this->estActif;    }    public function setEstActif(bool $estActif): self    {        $this->estActif = $estActif;        return $this;    }    public function getDomaine(): ?Domaine    {        return $this->domaine;    }    public function setDomaine(?Domaine $domaine): self    {        $this->domaine = $domaine;        return $this;    }    public function getNiveau(): ?Niveau    {        return $this->niveau;    }    public function setNiveau(?Niveau $niveau): self    {        $this->niveau = $niveau;        return $this;    }    /**     * @return Collection|ReponsePossible[]     */    public function getReponsesPossibles(): Collection    {        return $this->reponsesPossibles;    }    public function addReponsesPossible(ReponsePossible $reponsesPossible): self    {        if (!$this->reponsesPossibles->contains($reponsesPossible)) {            $this->reponsesPossibles[] = $reponsesPossible;            $reponsesPossible->setQuestion($this);        }        return $this;    }    public function removeReponsesPossible(ReponsePossible $reponsesPossible): self    {        if ($this->reponsesPossibles->contains($reponsesPossible)) {            $this->reponsesPossibles->removeElement($reponsesPossible);            // set the owning side to null (unless already changed)            if ($reponsesPossible->getQuestion() === $this) {                $reponsesPossible->setQuestion(null);            }        }        return $this;    }    /**     * @return Collection|Administrateur[]     */    public function getAdministrateurs(): Collection    {        return $this->administrateurs;    }    public function addAdministrateur(Administrateur $administrateur): self    {        if (!$this->administrateurs->contains($administrateur)) {            $this->administrateurs[] = $administrateur;            $administrateur->addQuestion($this);        }        return $this;    }    public function removeAdministrateur(Administrateur $administrateur): self    {        if ($this->administrateurs->contains($administrateur)) {            $this->administrateurs->removeElement($administrateur);            $administrateur->removeQuestion($this);        }        return $this;    }    public function __toString()    {    return (string) $this->getId(). " - " .$this->getEnonce();    }    public function getTestTechnique(): ?TestTechnique    {        return $this->testTechnique;    }    public function setTestTechnique(?TestTechnique $testTechnique): self    {        $this->testTechnique = $testTechnique;        return $this;    }}

ENTITY TestTechnique

<?phpnamespace App\Entity;use App\Repository\TestTechniqueRepository;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Doctrine\ORM\Mapping as ORM;/** * @ORM\Entity(repositoryClass=TestTechniqueRepository::class) */class TestTechnique{    /**     * @ORM\Id     * @ORM\GeneratedValue     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\OneToMany(targetEntity=InfoCo::class, mappedBy="testTechnique")     */    private $infoCos;    /**     * @ORM\ManyToOne(targetEntity=Administrateur::class, inversedBy="testsTechniques")     */    private $administrateur;    /**     * @ORM\Column(type="datetime", nullable=true)     */    private $date;    /**     * @ORM\Column(type="string", length=255, nullable=true)     */    private $intitule;    /**     * @ORM\OneToMany(targetEntity=Question::class, mappedBy="testTechnique")     */    private $questions;    public function __construct()    {        $this->infoCos = new ArrayCollection();        $this->questions = new ArrayCollection();    }    public function getId(): ?int    {        return $this->id;    }    /**     * @return Collection|InfoCo[]     */    public function getInfoCos(): Collection    {        return $this->infoCos;    }    public function addInfoCo(InfoCo $infoCo): self    {        if (!$this->infoCos->contains($infoCo)) {            $this->infoCos[] = $infoCo;            $infoCo->setTestTechnique($this);        }        return $this;    }    public function removeInfoCo(InfoCo $infoCo): self    {        if ($this->infoCos->contains($infoCo)) {            $this->infoCos->removeElement($infoCo);            // set the owning side to null (unless already changed)            if ($infoCo->getTestTechnique() === $this) {                $infoCo->setTestTechnique(null);            }        }        return $this;    }    public function getAdministrateur(): ?Administrateur    {        return $this->administrateur;    }    public function setAdministrateur(?Administrateur $administrateur): self    {        $this->administrateur = $administrateur;        return $this;    }    public function __toString()    {    return (string) $this->getIntitule();    }    public function getDate(): ?\DateTimeInterface    {        return $this->date;    }    public function setDate(?\DateTimeInterface $date): self    {        $this->date = $date;        return $this;    }    public function getIntitule(): ?string    {        return $this->intitule;    }    public function setIntitule(?string $intitule): self    {        $this->intitule = $intitule;        return $this;    }    /**     * @return Collection|Question[]     */    public function getQuestions(): Collection    {        return $this->questions;    }    public function addQuestion(Question $question): self    {        if (!$this->questions->contains($question)) {            $this->questions[] = $question;            $question->setTestTechnique($this);        }        return $this;    }    public function removeQuestion(Question $question): self    {        if ($this->questions->contains($question)) {            $this->questions->removeElement($question);            // set the owning side to null (unless already changed)            if ($question->getTestTechnique() === $this) {                $question->setTestTechnique(null);            }        }        return $this;    }}

I want to get all questions for each TestTechnique :

So I tried, on my TestTechniqueController:

/**     * @IsGranted("ROLE_ADMIN")     * @Route("/{id}", name="test_technique_show", methods={"GET"})     */    public function show(Request $request, TestTechnique $testTechnique, QuestionRepository $questionRepository): Response    {        $id = $request->query->get('id');        $questions = $questionRepository->findQuestionsForEachTest($id);        return $this->render('test_technique/show.html.twig', ['test_technique' => $testTechnique,'questions' => $questions,            ]);    }

and this is the QuestionRepository :

public function findQuestionsForEachTest($id)    {        return $this->createQueryBuilder('q')            ->innerJoin('q.testTechnique', 'testTechnique')            ->andWhere('q.testTechnique = :val')            ->setParameter('val', $id)            ->orderBy('q.id', 'ASC')            ->getQuery()            ->getResult()            ;    }

and this my view, for each TestTechnique, I want to display all questions who composed this Test:

{% for question in questions %}<tr><td>{{ question.id }}</td><td>{{ question.enonce }}</td>            </tr>        {% endfor %}

My difficulty is there, I need to get the id of the TestTechnique to display only the questions for this test.

Sorry for my bad english, and thank you I need your help ^^

Viewing all 3925 articles
Browse latest View live


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