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

EasyAdmin 3 : Nested forms

$
0
0

I'm trying to embed forms into forms. In my case : I want to embed Period and Price form into Offer form into Poi form. The architecture :

  • Poi form
    • Offer form
      • Price form
      • Period form

Relations:

  • Poi entity has relation OneToMany with Offer entity
  • Offer entity has relation OneToMany with Price entity and ManyToMany with Periodentity.

I've been looking for solution for couple of days and I really need help, so if someone could help me it will be great.

1. First test : usage of CollectionFieldIn my PoiCrudController :

        public function configureFields(string $pageName): iterable{        $offers = CollectionField::new('offers')        ->setFormTypeOptions(['delete_empty' => true,'by_reference' => false,        ])        ->setEntryIsComplex(false)        ->setCustomOptions(['allowAdd' => true,'allowDelete' => true,'entryType' => 'App\Form\OfferType','showEntryLabel' => false,        ]),

In OfferType :

`class OfferType extends AbstractType {

public function buildForm(FormBuilderInterface $builder, array $options) {    $builder        ->add('description', CollectionType::class, array('allow_add' => true,'allow_delete' => true,'delete_empty' => true,'by_reference' => false,'entry_type' => TextEditorType::class,'entry_options' => ['label' => false,            ],'label' => 'Description',          ))        ->add('createdAt')        ->add('updatedAt')        ->add('periods')        ->add('poi')    ;}`

ERROR MESSAGE => The "App\Entity\Poi" entity has a repositoryClass set to "App\Entity\PoiRepository", but this is not a valid class. Check your class naming. If this is meant to be a service id, make sure this service exists and is tagged with "doctrine.repository_service".

If I replace 'entryType' => 'App\Form\OfferType', with 'entryType' => 'App\Form\PoiType' in PoiCrudController, and add this code in PoiType :

`class PoiType extends AbstractType {

public function buildForm(FormBuilderInterface $builder, array $options) {    $builder        ->add('offers', CollectionType::class, array('allow_add' => true,'allow_delete' => true,'delete_empty' => true,'by_reference' => false,'entry_type' => TextType::class, // cette ligne pose problème'entry_options' => ['label' => false,            ],'label' => 'Offres',          ))

Then the Poi form is nested into Poi form where the field 'offer' appears.If I replace 'entry_type' => TextType::class with 'entry_type' => TextEditorType::class, a new error appears :

ERROR MESSAGE : Impossible to access an attribute ("customOptions") on a null variable.in vendor\easycorp\easyadmin-bundle\src\Resources\views\crud\form_theme.html.twig (line 424){% set numOfRows = form.vars.ea_crud_form.ea_field.customOptions.get('numOfRows') %}

2. Second test : usage of CollectionField

In PoiCrudController :

CollectionField::new('offers', 'Offres')            ->allowAdd()             ->allowDelete()            ->setEntryIsComplex(true)            ->setEntryType(OfferCrudController::class)        ->setFormTypeOptions(['by_reference' => 'false'        ]),

ERROR MESSAGE => Could not load type "App\Controller\Admin\OfferCrudController": class does not implement "Symfony\Component\Form\FormTypeInterface.My forms implement AbstractType so...

3. Third test : usage of AssociationField

In PoiCrudController :

AssociationField::new('offers')            ->setFormTypeOptions(['by_reference' => false,'multiple' => true,'allow_add' => true            ]),

ERROR MESSAGE => An error has occurred resolving the options of the form "Symfony\Bridge\Doctrine\Form\Type\EntityType": The option "allow_add" does not exist=>Issue #3528 [https://github.com/EasyCorp/EasyAdminBundle/issues/3528][2]


Symfony Webpack-Encore minify Js and CSS

$
0
0

I want minify all css and js of my project in symfony.
in Symfony 3 I use Assetic for JS like this as simple:

{% javascripts'@AppBundle/Resources/public/js/*''@AcmeBarBundle/Resources/public/js/form.js''@AcmeBarBundle/Resources/public/js/calendar.js' %}<script src="{{ asset_url }}"></script>{% endjavascripts %}

and for CSS same.
But in symfony 4 recommended to use Webpack Encore but i have a few problems:

  1. The Webpack downloads all the dependencies while I have the JavaScript files of them And I do not want to download.
  2. Sometimes it does not have some libraries that occur failed to download. but I have a JS file of library and I do not want to download.

Now I just want to minify my JavaScript files without interference like Assetic. (like check and download dependency, ...).

Minify our external javascripts with webpack

$
0
0

I want to Miniy my JS Files with webpack-encore of Symfony 4.

../js/jquery.min.js../js/clickable.js../js/myscrips.min.js

just minified! not download dependency and not change files.
has any ways to do?!

How can I improve CSV import faster in Symfony?

$
0
0

I have to import CSV file of around 20,000 rows. This CSV is read from FTP Server which will update every 30 minutes. But the code I have written is already taking more than 45 mintues to import. This is very slow. Can anybody please help me.

foreach ($readers as $key => $row) {    $totalRecords +=1;    $filterArray = $this->entityManager->getRepository(Article::class)->findBy(['id' =>  $row['id']]);    if (empty($filterArray)) {        $notFoundRecords +=1;        continue;    }    $foundRecords +=1;    $this->processPriceRow($row);}protected function processPriceRow($row){    $existingRecord = $this->entityManager                           ->getRepository(WareHouse::class)                           ->findBy(['id' => $row['product_id']]);    if (empty($existingRecord)) {        return $this->fillArticleWareHouse($row);    }}protected function fillArticleWareHouse($row, $i, $batchSize){    $newWareHouse = new WareHouse();    ....    ....    ...    // Insert.    $this->entityManager->persist($newWareHouse);    $this->entityManager->flush();}

I am thinking of persist the data every based on the batchSize = 100. But as I have function inside function, I am not being able to implement that as well.

symfony 4.1 Unable to generate a URL

$
0
0

in my synfony app I have two controllers:The ActionController is supposed to simply render a template containing a form. Submitting the form, I want to send a GET request to the SpreadSheetControllers getSpreadSheet() method.

This is the ActionController:

namespace App\Controller;use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;use Symfony\Component\Routing\Annotation\Route;use Symfony\Component\Form\Extension\Core\Type\SubmitType;class ActionController extends AbstractController {  /**   * @Route("/action")   */  public function action() {    $form = $this->createFormBuilder()        ->setAction($this->generateUrl('/spreadSheet'))        ->setMethod('GET')        ->add('save', SubmitType::class, array('label' => 'Action'))        ->getForm();    return $this->render('action.html.twig', array('form' => $form->createView(),    ));  }}

And here is the SpreadSheetController:

namespace App\Controller;use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;use Symfony\Component\Routing\Annotation\Route;use Symfony\Component\HttpFoundation\Response;class SpreadSheetController extends AbstractController {  /**   * @Route("/spreadSheet")   */  public function getSpreadSheet() {    return new Response('<html><body>spreadSheet</body></html>'    );  }}

Still, when browsing http://localhost:8000/action I get a RouteNotFoundException:Unable to generate a URL for the named route "/spreadSheet" as such route does not exist.

Does anybody know why the route isn't found??

expects parameter to be string, object given, symfony4

$
0
0

I don't understand why he said object given when my parameter 2 is -> "somethtink"Maybe because i have 2 routes ?

enter image description here

enter image description here

Symfony Doctrine entity property with array of objects

$
0
0

I have a survey form that is mapped to an entity.Within this form, there is a multiple-choice field.Choices/Options are Entity Type.

Survey Form Entity property:

    /**     * @var App\Entity\Definition[]|ArrayCollection     *     * @ORM\Column(type="simple_array")     */    protected $dissatisfactionReasons;

What I want to do is save the selected choices without using the relation table (ManyToMany).I simply want to save $dissatisfactionReasons property into the table as an array of IDs.I also defined __toString() method for Definition entity:

/**     * @return string     */    public function __toString()    {        return (string)$this->getId();    }

Using this code I was able to save $dissatisfactionReasons property values as a string of IDs separated by a comma. However, on retrieving survey form Entity $dissatisfactionReasons property contains an array of integers and not converted/mapped back to an array of Definition entities.

Using @ORM\Column(type="array") instead of simple_array works as expected, but type array serializes whole Definition entity data whereas I only want to save IDs

Multiple EntityManagers in EventSubscriber

$
0
0

I can call default entity manager from EventSubscriber but now i want to check some value in second database.

My codde:

class AuthenticationSubscriber implements EventSubscriberInterface{    /**     * @var EntityManagerInterface     */    public $em;    public function __construct(EntityManagerInterface $em)    {        $this->em = $em;    }    public function onKernelRequest(RequestEvent $event)    {}    public function onKernelResponse(ResponseEvent $event)    {}    public static function getSubscribedEvents()    {        return [            KernelEvents::REQUEST => ['onKernelRequest', 40],            KernelEvents::RESPONSE => 'onKernelResponse',        ];    }}

What is necessary to do to call second database in my case?


Using pre-set data and changing the value

$
0
0

I am trying to recover datas and modify them according to a selector. This is how my application works: I have vendors associated with articles, several vendors can have the same product except that the reference is different depending on the vendor and I am looking for the possibility of being able to modify this reference depending on the vendor.

Entity supplier:

<?phpnamespace App\Entity;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Symfony\Component\HttpFoundation\File\File;use Vich\UploaderBundle\Mapping\Annotation as Vich;use Doctrine\ORM\Mapping as ORM;/** * @ORM\Entity(repositoryClass="App\Repository\FournisseursRepository") * @Vich\Uploadable */class Fournisseur{    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="string", length=255)     *     * @var string     */    private $category;    /**     * @ORM\Column(type="string", length=255)     *     * @var string     */    private $civility;    /**     * @ORM\Column(type="text")     *     */    private $name;    /**     * @ORM\Column(type="string", length=255, nullable=true)     *     * @var string     */    private $company;    /**     * @ORM\Column(type="string", length=255, nullable=true)     *     * @var string     */    private $named;    /**     * @ORM\Column(type="string", length=255)     *     * @var string     */    private $surname;    /**     * @ORM\Column(type="string", length=255, nullable=true)     *     * @var string     */    private $building;    /**     * @ORM\Column(type="string", length=255)     *     * @var string     */    private $street;    /**     * @ORM\Column(type="string", length=255, nullable=true)     *     * @var string     */    private $other;    /**     * @ORM\Column(type="integer", length=5)     *     * @var integer     */    private $zipcode;    /**     * @ORM\Column(type="string", length=255)     *     * @var string     */    private $city;    /**     * @ORM\Column(type="string", length=255)     *     * @var string     */    private $country;    /**     * @ORM\Column(type="string", length=255, nullable=true)     *     * @var string     */    private $url;    /**     * @ORM\Column(type="string", length=255, nullable=true)     *     * @var string     */    private $login;    /**     * @ORM\Column(type="string", length=255, nullable=true)     *     * @var string     */    private $passwordSite;    /**     * NOTE: This is not a mapped field of entity metadata, just a simple property.     *     * @Vich\UploadableField(mapping="fournisseur_image", fileNameProperty="imageName", size="imageSize")     *     * @var File     */    private $imageFile;    /**     * @ORM\Column(type="string", length=255)     *     * @var string     */    private $imageName;    /**     * @ORM\Column(type="integer")     *     * @var integer     */    private $imageSize;    /**     * @ORM\Column(type="string", length=255)     */    private $title;    /**     * @ORM\Column(type="string", length=255)     */    private $type;    /**     * @ORM\Column(type="string", length=255)     */    private $phone1;    /**     * @ORM\Column(type="string", length=255, nullable=true)     */    private $phone2;    /**     * @ORM\Column(type="string", length=255, nullable=true)     */    private $fax;    /**     * @ORM\Column(type="string", length=255)     */    private $email;    /**     * @ORM\Column(type="text")     */    private $note;    /**     * @ORM\OneToMany(targetEntity="Reference", mappedBy="fournisseur")     */    private $references;    public function __construct() {        $this->references = new ArrayCollection();    }    public function getId(): ?int    {        return $this->id;    }    /**     * @return string     */    public function getCategory(): ?string    {        return $this->category;    }    /**     * @param string $category     */    public function setCategory(string $category): void    {        $this->category = $category;    }    /**     * @return string     */    public function getCivility(): ?string    {        return $this->civility;    }    /**     * @param string $civility     */    public function setCivility(string $civility): void    {        $this->civility = $civility;    }    /**     * @return mixed     */    public function getName()    {        return $this->name;    }    /**     * @param mixed $name     */    public function setName($name): void    {        $this->name = $name;    }    /**     * @return string     */    public function getCompany(): ?string    {        return $this->company;    }    /**     * @param string $company     */    public function setCompany(string $company): void    {        $this->company = $company;    }    /**     * @return string     */    public function getNamed(): ?string    {        return $this->named;    }    /**     * @param string $named     */    public function setNamed(string $named): void    {        $this->named = $named;    }    /**     * @return string     */    public function getSurname(): ?string    {        return $this->surname;    }    /**     * @param string $surname     */    public function setSurname(string $surname): void    {        $this->surname = $surname;    }    /**     * @return string     */    public function getBuilding(): ?string    {        return $this->building;    }    /**     * @param string $building     */    public function setBuilding(string $building): void    {        $this->building = $building;    }    /**     * @return string     */    public function getStreet(): ?string    {        return $this->street;    }    /**     * @param string $street     */    public function setStreet(string $street): void    {        $this->street = $street;    }    /**     * @return string     */    public function getOther(): ?string    {        return $this->other;    }    /**     * @param string $other     */    public function setOther(string $other): void    {        $this->other = $other;    }    /**     * @return int     */    public function getZipcode(): ?int    {        return $this->zipcode;    }    /**     * @param int $zipcode     */    public function setZipcode(int $zipcode): void    {        $this->zipcode = $zipcode;    }    /**     * @return string     */    public function getCity(): ?string    {        return $this->city;    }    /**     * @param string $city     */    public function setCity(string $city): void    {        $this->city = $city;    }    /**     * @return string     */    public function getCountry(): ?string    {        return $this->country;    }    /**     * @param string $country     */    public function setCountry(string $country): void    {        $this->country = $country;    }    /**     * @return string     */    public function getUrl(): ?string    {        return $this->url;    }    /**     * @param string $url     */    public function setUrl(string $url): void    {        $this->url = $url;    }    /**     * @return string     */    public function getLogin(): ?string    {        return $this->login;    }    /**     * @param string $login     */    public function setLogin(string $login): void    {        $this->login = $login;    }    /**     * @return string     */    public function getPasswordSite(): ?string    {        return $this->passwordSite;    }    /**     * @param string $passwordSite     */    public function setPasswordSite(string $passwordSite): void    {        $this->passwordSite = $passwordSite;    }    /**     * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $imageFile     */    public function setImageFile(?File $imageFile = null): void    {        $this->imageFile = $imageFile;    }    public function getImageFile(): ?File    {        return $this->imageFile;    }    public function setImageName(?string $imageName): void    {        $this->imageName = $imageName;    }    public function getImageName(): ?string    {        return $this->imageName;    }    public function setImageSize(?int $imageSize): void    {        $this->imageSize = $imageSize;    }    public function getImageSize(): ?int    {        return $this->imageSize;    }    public function getTitle(): ?string    {        return $this->title;    }    public function setTitle(string $title): self    {        $this->title = $title;        return $this;    }    public function getType(): ?string    {        return $this->type;    }    public function setType(string $type): self    {        $this->type = $type;        return $this;    }    public function getPhone1(): ?string    {        return $this->phone1;    }    public function setPhone1(string $phone1): self    {        $this->phone1 = $phone1;        return $this;    }    public function getPhone2(): ?string    {        return $this->phone2;    }    public function setPhone2(string $phone2): self    {        $this->phone2 = $phone2;        return $this;    }    public function getFax(): ?string    {        return $this->fax;    }    public function setFax(string $fax): self    {        $this->fax = $fax;        return $this;    }    public function getEmail(): ?string    {        return $this->email;    }    public function setEmail(string $email): self    {        $this->email = $email;        return $this;    }    public function getNote(): ?string    {        return $this->note;    }    public function setNote(string $note): self    {        $this->note = $note;        return $this;    }}

Entity article:

<?phpnamespace App\Entity;use Doctrine\Common\Collections\ArrayCollection;use Doctrine\Common\Collections\Collection;use Doctrine\ORM\Mapping as ORM;/** * @ORM\Entity(repositoryClass="App\Repository\ArticlesRepository") */class Article{    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="string", length=255)     */    private $id_tactill;    /**     * @ORM\Column(type="string", length=255)     */    private $name;    /**     * @ORM\Column(type="float", nullable=true)     */    private $price;    /**     * @ORM\Column(type="string", length=255, nullable=true)     */    private $reference;    /**     * @ORM\Column(type="boolean")     */    private $in_stock;    /**     * @ORM\Column(type="string", length=255, nullable=true)     */    private $image;    /**     * @ORM\Column(type="string", length=255, nullable=true)     */    private $taxes;    /**     * Many Users have Many Groups.     * @ORM\ManyToMany(targetEntity="Fournisseur")     * @ORM\JoinTable(name="articles_fournisseurs",     *      joinColumns={@ORM\JoinColumn(name="article_id", referencedColumnName="id")},     *      inverseJoinColumns={@ORM\JoinColumn(name="fournisseur_id", referencedColumnName="id")}     *      )     */    private $fournisseurs;    public function getId(): ?int    {        return $this->id;    }    /**     * @return mixed     */    public function getIdTactill()    {        return $this->id_tactill;    }    /**     * @param mixed $id_tactill     */    public function setIdTactill($id_tactill): void    {        $this->id_tactill = $id_tactill;    }    public function getName(): ?string    {        return $this->name;    }    public function setName(string $name): self    {        $this->name = $name;        return $this;    }    public function getPrice(): ?float    {        return $this->price;    }    public function setPrice(float $price): self    {        $this->price = $price;        return $this;    }    public function getReference(): ?string    {        return $this->reference;    }    public function setReference(string $reference): self    {        $this->reference = $reference;        return $this;    }    public function getInStock(): ?bool    {        return $this->in_stock;    }    public function setInStock(bool $in_stock): self    {        $this->in_stock = $in_stock;        return $this;    }    public function getImage(): ?string    {        return $this->image;    }    public function setImage(string $image): self    {        $this->image = $image;        return $this;    }    public function getTaxes()    {        return $this->taxes;    }    public function setTaxes($taxes): void    {        $this->taxes = $taxes;    }    public function getFournisseurs()    {        return $this->fournisseurs;    }    public function setFournisseurs($fournisseurs): void    {        $this->fournisseurs = $fournisseurs;    }}

Entity reference:

<?phpnamespace App\Entity;use Doctrine\ORM\Mapping as ORM;/** * @ORM\Entity(repositoryClass="App\Repository\ReferenceRepository") */class Reference{    /**     * @ORM\Id()     * @ORM\GeneratedValue()     * @ORM\Column(type="integer")     */    private $id;    /**     * @ORM\Column(type="string", length=255)     */    private $refcode;    /**     * @ORM\OneToOne(targetEntity="Article", cascade={"remove"})     */    private $article;    /**     * @ORM\ManyToOne(targetEntity="Fournisseur", inversedBy="references")     * @ORM\JoinColumn(name="fournisseur_id", referencedColumnName="id")     */    private $fournisseur;    public function __toString()    {        return $this->refcode;    }    public function getId(): ?int    {        return $this->id;    }    public function getRefcode(): ?string    {        return $this->refcode;    }    public function setRefcode(string $refcode): self    {        $this->refcode = $refcode;        return $this;    }    public function getArticle()    {        return $this->article;    }    public function setArticle($article): void    {        $this->article = $article;    }}

FormType article:

<?phpnamespace App\Form;use App\Entity\Article;use App\Entity\Fournisseur;use App\Entity\Reference;use Symfony\Bridge\Doctrine\Form\Type\EntityType;use Symfony\Component\Form\AbstractType;use Symfony\Component\Form\Extension\Core\Type\CheckboxType;use Symfony\Component\Form\Extension\Core\Type\HiddenType;use Symfony\Component\Form\Extension\Core\Type\MoneyType;use Symfony\Component\Form\Extension\Core\Type\TextType;use Symfony\Component\Form\FormBuilderInterface;use Symfony\Component\OptionsResolver\OptionsResolver;use Vich\UploaderBundle\Form\Type\VichImageType;class ArticlesType extends AbstractType{    public function buildForm(FormBuilderInterface $builder, array $options)    {        $builder            ->add('id_tactill', HiddenType::class)            ->add('name', TextType::class, ['label' => 'Nom'            ])            ->add('price', MoneyType::class, ['label' => 'Prix'            ])            ->add('reference')            ->add('in_stock', CheckboxType::class, ['label' => 'En stock'            ])            ->add('image')            ->add('taxes', HiddenType::class)            ->add('fournisseurs', EntityType::class, ['class' => Fournisseur::class,'label' => 'Choisir un fournisseur','required' => false,'attr' => ['class' => 'js_fournisseur'],'choice_label' => function ($fournisseur) {                    return $fournisseur->getTitle();                }            ])            ;    }    public function configureOptions(OptionsResolver $resolver)    {        $resolver->setDefaults(['data_class' => Article::class,        ]);    }}

I block the design of the form that will allow me to display the reference according to the selection of the supplier in the article master and can modify it later.

Thank you for your help

API Platform Logging Headers from requests

$
0
0

I have an authentication issue on a production server, the issue is very likely to be non-code related but rather an IT configuration issue...

To prove this I would like to check if API Platform receives the Authorization header when trying to fetch data. I have not found anything about logs in the API Platform documentation. What is the right way of logging API requests and their headers using the Symfony logging systems, knowing that I don't have access to the actual controller code as it is purely configured using the APIRessource annotation on entities ?

To be clear, everything works fine in local, I'm not looking for a solution to my problem here, just a clean way to change the log format or add logs to incoming request using API Platform.

How to recover the user after login if you use jwt and stateless: true

$
0
0

Since I use jwt I have configured sateless = true and commented on the session configuration in framework.yalm

For user management I have used MakerBundle. I have the typical extending class of AbstractFormLoginAuthenticator:

supports(Request $request){...}getCredentials(Request $request){...}getUser($credentials, UserProviderInterface $userProvider){...}....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('mainPage'));}

To find out from the controller which user logged in to onAuthenticationSuccess I do:

$params = array('idUser' => $this->user->getId());return new RedirectResponse($this->urlGenerator->generate('mainPage', $params, true), 302, array('Content-Type' => 'text/plain'));

From the controller I retrieve idUser and send the jwt

The problem is that idUser appears as a parameter in the url on the next screen.Can I pass the idUser in another way that is not shown in the url?Do I have to set stateless = false to be able to retrieve the user after login? (with jwt I think you shouldn't have anything in session)Do I have to forget about AbstractFormLoginAuthenticator and do a manual login screen that calls a controller?

Thank

Inject service to EventSubscriber

$
0
0

I have problem with my code. I have EventSubscriber:

<?phpnamespace App\EventSubscriber;use App\Service\PostService;use Symfony\Component\EventDispatcher\EventSubscriberInterface;use Symfony\Component\HttpKernel\Event\RequestEvent;use Symfony\Component\HttpKernel\KernelEvents;class NewPostSubscriber implements EventSubscriberInterface{    /**     * @var PostService $postService     */    private $postService;    /**     * @param PostService $postService     */    public function constructor($postService)    {        $this->postService = $postService;    }    public static function getSubscribedEvents()    {        return [            KernelEvents::REQUEST => 'postNotification'        ];    }    public function postNotification(RequestEvent $event)    {        $request = $event->getRequest();        if ('app_post_createpost' != $request->get('_route')) {            return;        }        $post = $this->postService->deletePost(3);    }}

and i inject for him PostService, but when i send request to post endpoint then i receive exception witj code 500 and text

Call to a member function deletePost() on null

In my services.yaml i have

services:    # default configuration for services in *this* file    _defaults:        autowire: true             autoconfigure: true     App\:        resource: '../src/*'        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'    App\Controller\:        resource: '../src/Controller'        tags: ['controller.service_arguments']    app.post_service:        class: App\Service\PostService        arguments: ['@doctrine.orm.entity_manager']        autowire: true    app.new_post_subscriber:        class: App\EventSubscriber\NewPostSubscriber        arguments: ['@app.post_service']        autowire: false        tags:            - { name: kernel.event_subscriber }

I have method deletePost in my PostService. I don't know what is wrong, i have service and deletePost method, service is inject to subscriber but still not working.

Symfony 4 Custom Event Dispatcher not Working

$
0
0

I have followed the Symfony 4.3 docs to create a custom event, dispatch it, and listen for it. Tracing the execution of my controller, it looks like the event dispatcher does not find any subscribers, and I can't figure out what I'm doing wrong.

My event class is very basic:

namespace App\Event;use Symfony\Contracts\EventDispatcher\Event;class TestEvent extends Event{    public const NAME = 'test.event';    protected $data;    public function __construct(string $data)    {        $this->data = $data;    }    public function getData(): string    {        return $this->data;    }}

My controller instantiates and dispatches the event:

class TestController extends AbstractController{    private $eventDispatcher;    public function __construct(EventDispatcherInterface $eventDispatcher, LoggerInterface $logger)    {        $this->eventDispatcher = $eventDispatcher;    }    /**     * @Route("/event", name="event_test")     */    public function eventTest()    {        $event = new TestEvent('Event string');        $this->eventDispatcher->dispatch($event);        return $this->render('Test/TestEvent.html.twig', ['title' => 'Test Event',            ]);    }}

I set up a subscriber to listen for the event and log. To make sure the subscriber works, I also subscribed to a Kernel event (that works):

namespace App\EventSubscriber;use App\Event\TestEvent;use Psr\Log\LoggerInterface;use Symfony\Component\EventDispatcher\EventSubscriberInterface;use Symfony\Component\HttpKernel\KernelEvents;class TestSubscriber implements EventSubscriberInterface{    private $logger;    public function __construct(LoggerInterface $logger)    {        $this->logger = $logger;    }    public static function getSubscribedEvents()    {        return [            TestEvent::NAME => [['onTestEvent', 20]],            KernelEvents::REQUEST => 'onKernelRequest',        ];    }    public function onTestEvent(TestEvent $event)    {        $this->logger->info('Subscriber says: Found test event');        $this->logger->info('Subscriber says: Test event posted this data {data}', ['data' => $event->getData(),        ]);    }    public function onKernelRequest()    {        $this->logger->info('Got Kernel Request');    }}

When I visit the /event URL, I see the expected output, and the logs show the Kernel request, but they don't show the test.event log.

Per the docs, I ran

php bin/console debug:event-dispatcher test.event

at the console and got

Registered Listeners for "test.event" Event


Order Callable Priority


#1 App\EventSubscriber\TestSubscriber::onTestEvent() 20


That tells me the subscriber is registered, but for some reason it is not being called. Any help would be fantastic!

(BTW, I tried with an event listener as well, and got the same results.)

Thanks!

Change default sorting on product listing in shopware 6

$
0
0

I have created a new Sorting after this documentation .

<argument>a-sorting</argument><argument>New Sorting</argument><argument type="collection"><argument key="product.markAsTopseller">desc</argument><argument key="product.updatedAt">desc</argument></argument><tag name="shopware.sales_channel.product_listing.sorting" /></service>

You can select now the new Sorting in the frontend and it is working fine.But i don't know how to set this sorting as page default. I mean the product list should be sorted initially after the page is loaded.

I solved it with ProductListingCriteriaEvent and ProductListingResultEvent

<?php declare(strict_types=1);namespace MyPlugin\Storefront\Subscriber;use Shopware\Core\Content\Product\Events\ProductListingResultEvent;use Shopware\Core\Content\Product\Events\ProductListingCriteriaEvent;use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;use Symfony\Component\EventDispatcher\EventSubscriberInterface;class ProductSubscriber implements EventSubscriberInterface{    /**     * @inheritDoc     */    public static function getSubscribedEvents()    {        return [            ProductListingCriteriaEvent::class  => 'handleRequest',            ProductListingResultEvent::class    => 'handleResult'        ];    }    /**     * @param ProductListingResultEvent $event     */    public function handleResult(ProductListingResultEvent $event): void    {        $request = $event->getRequest();        /* Sorting is not selected in frontend */        if (!$request->get('order')) {            $event->getResult()->setSorting('a-sorting');        }    }    /**     * @param ProductListingCriteriaEvent $event     */    public function handleRequest(ProductListingCriteriaEvent $event): void    {        $request = $event->getRequest();        $criteria = $event->getCriteria();        /* Sorting is not selected in frontend */        if (!$request->get('order')) {            $criteria->resetSorting();            $criteria->addSorting(                new FieldSorting('markAsTopseller', 'DESC'),                new FieldSorting('updatedAt', 'DESC')            );        }    }}

Twig Error Unknown "format_number" filter on Symfony 4 project

$
0
0

format_number was introduced in 2.12, as far as I can tell I have 2.13, using {{ constant('Twig_Environment::VERSION') }} outputs The current version is 2.13.0

Here is my composer json, I just dont see a reason I should be getting an unknown filter in this symfony 4.4.* project.

"require": {"php": "^7.1.3","ext-ctype": "*","ext-iconv": "*","ext-json": "*","beberlei/doctrineextensions": "^1.2","friendsofsymfony/jsrouting-bundle": "^2.3","sensio/framework-extra-bundle": "^5.4","symfony/asset": "4.4.*","symfony/console": "4.4.*","symfony/dotenv": "4.4.*","symfony/flex": "^1.3.1","symfony/form": "4.4.*","symfony/framework-bundle": "4.4.*","symfony/orm-pack": "^1.0","symfony/security-bundle": "4.4.*","symfony/swiftmailer-bundle": "^3.2","symfony/twig-bridge": "4.*","symfony/twig-bundle": "4.4.*","symfony/validator": "4.4.*","symfony/web-server-bundle": "4.4.*","symfony/yaml": "4.4.*","twig/twig": "2.*"    },

Symfony 4: FOSUserBundle : Override Controller

$
0
0

I want to separate the admin login page and user login page. I did it this way with the codes I got from some sources, but I get an error.

// config/security.yamlsecurity:    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers    encoders: ...role_hierarchy: ...# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providersproviders:    fos_userbundle:        id: fos_user.user_provider.usernamefirewalls:    dev:        ...    admin:        pattern:            /admin(.*)        form_login:            provider:       fos_userbundle            login_path:     /admin/login            check_path:     /admin/login_check            default_target_path: /admin/        logout:            path:           /admin/logout            target:         /admin/login        anonymous:    true    main:        pattern: ^/        form_login:            provider: fos_userbundle            csrf_token_generator: security.csrf.token_manager        logout:       true        anonymous:    true# Easy way to control access for large sections of your site# Note: Only the *first* access control that matches will be usedaccess_control:    - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }    - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }    - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }    - { path: ^/admin/, role: ROLE_ADMIN }    - { path: ^/admin/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }    - { path: ^/admin/logout$, role: IS_AUTHENTICATED_ANONYMOUSLY }    - { path: ^/admin/login_check$, role: IS_AUTHENTICATED_ANONYMOUSLY }

The routes.yaml file is as follows.

admin_login:  path:  /admin/login  defaults: { _controller: App\UserBundle\Controller\SecurityController }

and The SecurityController file is as follows.

<?phpnamespace App\UserBundle\Controller;use FOS\UserBundle\Controller\SecurityController as BaseController;class SecurityController extends BaseController{    public function renderLogin(array $data)    {        $requestAttributes = $this->container->get('request')->attributes;        if ('admin_login' === $requestAttributes->get('_route')) {            $template = sprintf('admin/Security/login.html.twig');        } else {            $template = sprintf('@FOSUser/Security/login.html.twig');        }        return $this->container->get('templating')->renderResponse($template, $data);    }}

I wrote this way, but when I enter the admin / login page, I get an error like the one below.

This page isn’t working127.0.0.1 redirected you too many times.ERR_TOO_MANY_REDIRECTS

How can I fix this error.

Using senders independent in Symfony messenger component

$
0
0

I'm using Symfony 4.2 and have one message to dispatch via messenger component which is a notification that should be sent via a few channels (for example SMS and email). I'm wondering how to make these senders independent (for example first channel fails and throw an exception) - how to make a try to send independent via the second sender? Currently, when one of the senders in the chain fails the rest can't make a try of delivering notification.

Catching exception on the sender level seems not to be a good solution, because returning envelop causes that it will be stamped as sent what is not true.

I've started to make message per channel to keep sentStamp convention, but It seems that should be one message and few channels listening for one message (even configuration indicates to that with senders keyword):

routing:'App\Messenger\Command\Notification\SendSomeInformation':            senders:                - App\Messenger\Sender\Notification\EmailSender                - App\Messenger\Sender\Notification\SmsSender

There is some good approach for such problem?

Can't render dateTime

$
0
0

I make an entity "comment" with fields id, pseudo, email, comment and published_at.

My entity :

/*** @ORM\Column(type="datetime")*/private $published_at;public function __construct(){    $this->published_at= new \DateTime();}public function getPublishedAt(): ?\DateTimeInterface{    return $this->published_at;}public function setPublishedAt(\DateTime $published_at): self{    $this->published_at = $published_at;    return $this;}

My migration:

public function up(Schema $schema) : void{    // this up() migration is auto-generated, please modify it to your needs    $this->addSql('CREATE TABLE comment (id INT AUTO_INCREMENT NOT NULL, pseudo VARCHAR(25) NOT NULL, email VARCHAR(255) NOT NULL, comment LONGTEXT NOT NULL, published_at DATETIME NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB');} 

I make a controller :

$comments = $commentRepo->findBy([], ['published_at' => 'desc']);//        dd($comments);return $this->render('comment/comments.html.twig', ['commentForm' => $form->createView(),'comments' => $comments,]);

My render twig :

<div>                {% for comment in comments %}<div class="text-light">                        {{ comment.pseudo }}                        {{ comment.published_at|date('d/m/Y H:i:s')}}                        {{ comment.comment | raw }}</div>                {% endfor %}</div>

For {{comment.pseudo}} and {{comment.comment}} display wellBut for {{comment.published_at}} I have this error :

Neither the property "published_at" nor one of the methods "published_at()", "getpublished_at()"/"ispublished_at()"/"haspublished_at()" or "__call()" exist and have public access in class "App\Entity\Comment".

Inject symfony variables with array of Objects to a vue.js component from a twig template

$
0
0

I am using symfony5 and would like to integrate vue.js in one of my twig template views. I need to be able to pass 3 different Objects to vue.js. I have to pass on multiple Arrays which store normally multiple Objects to a vue component so I have done the following after installing vue.js

How would I access groups in the vue component and am I doing it the right way injecting the array to my component? do I have to use $jsonContent = $serializer->serialize($groups, 'json') in the controller or can I leave the array as it is?

// assets/js/app.js

import Vue from 'vue';import Example from './components/Example'new Vue({    el: '#app',    components: {Example}});

// assets/js/components/Example.vue

<template><div><h2 class="center">My Application</h2><div v-text="message"></div><pre>{{ groups }}</pre><ul><li :key="group.id" v-for="group in groups">{{ group }}</li></ul></div>
<script>export default {    data() {        return {            message: "A list of groups",            groups: [],        };    },    mounted() {        this.groups = this.$el.attributes['groups'].value;        console.log(this.groups);    }};</script><style>.center {    text-align: center;}</style> 

in my twig view I have the following

<div ref="groups"  v-bind:groups="{{ groups2|json_encode }}"></div><div id="app"><example></example></div>

groups normally looks like this:

  array:5 [▼  0 => App\Document\Group {#630 ▶}  1 => App\Document\Group {#627 ▶}  2 => App\Document\Group {#638 ▶}  3 => App\Document\Group {#641 ▶}  4 => App\Document\Group {#644 ▶}]so I used a serializer in the controller'groups2' => $jsonContent = $serializer->serialize($groups, 'json'),

Remove parameters from Symfony 4.4 HttpFoundation\Request and re-generate URL

$
0
0

I need to re-generate the URL of my page, removing the additional parameters. For example: when I receive:

https://example.com/bao1/bao2/?removeMe1=anything&keepMe1=anything&removeMe2=&keepMe2=anything

I want to show just this:

https://example.com/bao1/bao2/?keepMe1=anything&keepMe2=anything

I autowired the request (I love autowiring) :

    public function __construct(RequestStack $httpRequest)    {        $this->httpRequest                  = $httpRequest;    }

Then I'm playing around like this:

public function getCleanUrl(){     // HttpFoundation\Request      $currentHttpRequest = $this->httpRequest->getCurrentRequest();     // Trying to remove the parameters     currentHttpRequest->query->remove("removeMe1");     //     return $currentHttpRequest->getUri()}

The query->remove("removeMe1") works, but when I invoke getUri() I still get the full input url, as if remove() was never invoked. I think I'm probably missing to call some kind of $currentHttpRequest->regenerate()->getUri() but I cannot find anything.

Viewing all 3924 articles
Browse latest View live


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