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

Symfony on AWS EB - Unable to write in the cache directory after cache clear

$
0
0

I am deploying a Symfony 4.4 app to AWS ElasticBeanstalk and noticed that the cache wasn't cleared after each deploy.

The app was running fine though, exception made to the stale cache.

To resolve the cache issue I added the following file:

/.ebextensions/deploy.config

container_commands:
    01-clear-cache:
        command: php bin/console cache:clear --no-warmup --env=prod

That seems to clear the cache but then somehow it changes permissions so that I then get the error when trying to access the app.

Fatal error: Uncaught RuntimeException: Unable to write in the cache directory (/var/app/current/var/cache/prod)

Why does running cache:clear changes permissions and is there a way to avoid that happening, or at least how to resolve afterwards, ie, in the same/another .ebextensions file?


Symfony collection forms

How write a Symfony Flex recipe for a new bundle?

$
0
0

I tried to find any documentation about using Symfony Flex but so far no luck.

Almost all docs point to installing a bundle that uses symfony Flex, not how to create a bundle that is using it.

I even tried to reverse engineer some of the packages but again, no luck.

My goal is to generate a default configuration file for my bundle in config/packages/my_bundle.yaml.

What I need to know is where do I need to put it and what env variables (if any) will I have available?

Symfony Collection Form [closed]

$
0
0

I have two entities with a ManyToOne relationship patient and tourismeRegion I want to add a form to add the two Enitity's at the same time but i doesn't work i followed the symfony documentation:httpenter image description heres://symfony.com/doc/current/form/form_collections.html

Tourism Entity

<?php
namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\TourismeRegionRepository")
 */
class TourismeRegion
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="date")
     */
    private $Arrival_date;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $estimate_period;



    /**
     * @ORM\Column(type="string", length=255)
     */
    private $Guide;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $Car;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\PatientInformations", mappedBy="tourismeRegion")
     */
    private $patient;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\MedicalCity", inversedBy="Region")
     */
    private $medicalCity;

    public function __construct()
    {
        $this->patient = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getArrivalDate(): ?\DateTimeInterface
    {
        return $this->Arrival_date;
    }

    public function setArrivalDate(\DateTimeInterface $Arrival_date): self
    {
        $this->Arrival_date = $Arrival_date;

        return $this;
    }

    public function getEstimatePeriod(): ?string
    {
        return $this->estimate_period;
    }

    public function setEstimatePeriod(string $estimate_period): self
    {
        $this->estimate_period = $estimate_period;

        return $this;
    }



    public function getGuide(): ?string
    {
        return $this->Guide;
    }

    public function setGuide(string $Guide): self
    {
        $this->Guide = $Guide;

        return $this;
    }

    public function getCar(): ?string
    {
        return $this->Car;
    }

    public function setCar(string $Car): self
    {
        $this->Car = $Car;

        return $this;
    }

    /**
     * @return Collection|PatientInformations[]
     */
    public function getPatient(): Collection
    {
        return $this->patient;
    }

    public function addPatient(PatientInformations $patient): self
    {
        if (!$this->patient->contains($patient)) {
            $this->patient[] = $patient;
            $patient->setTourismeRegion($this);
        }

        return $this;
    }

    public function removePatient(PatientInformations $patient): self
    {
        if ($this->patient->contains($patient)) {
            $this->patient->removeElement($patient);
            // set the owning side to null (unless already changed)
            if ($patient->getTourismeRegion() === $this) {
                $patient->setTourismeRegion(null);
            }
        }

        return $this;
    }

    public function getMedicalCity(): ?MedicalCity
    {
        return $this->medicalCity;
    }

    public function setMedicalCity(?MedicalCity $medicalCity): self
    {
        $this->medicalCity = $medicalCity;

        return $this;
    }
}

Patient entity

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\PatientInformationsRepository")
 */
class PatientInformations
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $Name;

    /**
     * @ORM\Column(type="integer", nullable=true)
     */
    private $Age;

    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     */
    private $Sexe;



    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Housing", inversedBy="patient")
     */
    private $housing;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Specialisation", inversedBy="patient")
     */
    private $specialisation;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\TourismeRegion", inversedBy="patient")
     */
    private $tourismeRegion;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $country;

    /**
     * @ORM\Column(type="integer")
     */
    private $phone;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $email;

    /**
     * @ORM\Column(type="text")
     */
    private $demande;




    public function getId(): ?int
    {
        return $this->id;
    }

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

    public function setName(string $Name): self
    {
        $this->Name = $Name;

        return $this;
    }

    public function getAge(): ?int
    {
        return $this->Age;
    }

    public function setAge(int $Age): self
    {
        $this->Age = $Age;

        return $this;
    }

    public function getSexe(): ?string
    {
        return $this->Sexe;
    }

    public function setSexe(string $Sexe): self
    {
        $this->Sexe = $Sexe;

        return $this;
    }

    public function getTourismRegion(): ?TourismRegion
    {
        return $this->tourismRegion;
    }

    public function setTourismRegion(?TourismRegion $tourismRegion): self
    {
        $this->tourismRegion = $tourismRegion;

        return $this;
    }

    public function getHousing(): ?Housing
    {
        return $this->housing;
    }

    public function setHousing(?Housing $housing): self
    {
        $this->housing = $housing;

        return $this;
    }

    public function getSpecialisation(): ?Specialisation
    {
        return $this->specialisation;
    }

    public function setSpecialisation(?Specialisation $specialisation): self
    {
        $this->specialisation = $specialisation;

        return $this;
    }

    public function getTourismeRegion(): ?TourismeRegion
    {
        return $this->tourismeRegion;
    }

    public function setTourismeRegion(?TourismeRegion $tourismeRegion): self
    {
        $this->tourismeRegion = $tourismeRegion;

        return $this;
    }

    public function getCountry(): ?string
    {
        return $this->country;
    }

    public function setCountry(string $country): self
    {
        $this->country = $country;

        return $this;
    }

    public function getPhone(): ?int
    {
        return $this->phone;
    }

    public function setPhone(int $phone): self
    {
        $this->phone = $phone;

        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    public function getDemande(): ?string
    {
        return $this->demande;
    }

    public function setDemande(string $demande): self
    {
        $this->demande = $demande;

        return $this;
    }



}

Patient form

<?php

namespace App\Form;

use App\Entity\PatientInformations;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PatientInfo2Type extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('Age',NumberType::class)
            ->add('Sexe',ChoiceType::class,[
                'choices'  => [
                    'Women'=>'Women',
                    'Men'=>'Men' ,
                    'Other'=>'Other',
                ],
            ])
            ->add('tourismeRegion',CollectionType::class,[
                'entry_type' => RegiontourismType::class,
                'entry_options' => ['label' => false],
                'prototype' => true


            ])
            ->add('housing')
            ->add('specialisation')
            ->add('Save',SubmitType::class,[
                'attr' => [
                    'class' => 'btn-success'
                ]
            ])

        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => PatientInformations::class,
        ]);
    }
}

Tourism Form

<?php

namespace App\Form;

use App\Entity\TourismeRegion;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class RegiontourismType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('Arrival_date',DateType::class)
            ->add('estimate_period',TextType::class,[
                'choices'  => [
                    'Non prévue'=>'Non prévue',
                    '1 semaine'=>'1 semaine' ,
                    '2 semaine'=>'2 semaine',
                    '3 semaine'=>'3 semaine',
                    '1 Mois'=>'1 Mois',
                    'Plus de 1 mois '=>'Plus de 1 mois',
                ],
            ])
            ->add('Guide',TextType::class,[
                'choices'  => [
                    'Oui'=>'Oui' ,
                    'Non'=>'Non',

                ],
            ])
            ->add('Car',TextType::class,[
                'choices'  => [
                    'Sans Voiture'=>'Sans Voiture',
                    'Avec Voiture'=>'Avec Voiture' ,
                    'Voiture Avec Chauffeur'=>'Voiture Avec Chauffeur',
                ],
            ])
            ->add('medicalCity',TextType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => TourismeRegion::class,
        ]);
    }
}

the controller

<?php

namespace App\Controller;

use App\Entity\PatientInformations;
use App\Entity\Test;
use App\Entity\TourismeRegion;
use App\Form\PatientInfo2Type;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class PatientInfoController extends AbstractController
{
    /**
     * @Route("/patient/info", name="patient_info")
     */
    public function index(Request $request)
    {   $patient= new PatientInformations();

        $region= new TourismeRegion();
        $region->setArrivalDate(new \DateTime());
        $region->setGuide("Non");
        $region->setEstimatePeriod("2 semaine");
        $region->setCar("Sans Voiture");




        $form = $this->createForm(PatientInfo2Type::class,$patient);

        $form->handleRequest($request);
        $patient->setTourismeRegion($region);


        return $this->render('patient_info/index.html.twig', [
            'PatientInfo' => $form->createView(),
        ]);
    }
}

TWIG

{% extends 'base.html.twig' %}

{% block title %}Request{% endblock %}

{% block body %}

    <div class="container">
        <h1>Informations Patient</h1>
        {{ form_start(PatientInfo) }}
        {# iterate over each existing tag and render its only field: name #}
                {{ dump(PatientInfo) }}
        <div>
            {% for row in PatientInfo.tourismeRegion %}
               {{ form_row(row.estimate_period) }}
            {% endfor %}
                </div>


        {{ form_end(PatientInfo) }}
    </div>


{% endblock %}

What is the right way to override Twig extension in SF4.4+

$
0
0

In SF4.3 I could override a twig extension with a decorate like approach

...
    App\Twig\Extension\TranslationExtension:
        arguments: ['@twig.extension.trans']
        tags:
            - { name: twig.extension, priority: 100 }
...

But this is not working with SF4.4

It yells that App\Twig\Extension\TranslationExtension is already registered.

I tried to use decorate key without success...

In fact I just need to override the trans() filter.

Invalid mapping file BaseMedia.mongodb.xml

$
0
0

I have installed Sonata Media Bundle ^3.23, when installing doctrine-mongodb-bundle ^4.1, i receive the below error:

In MappingException.php line 236 The mapping file vendor/sonata-project/media-bundle/src/Resources/config/doctrine/BaseMedia.mongodb.xml is invalid.

How i can fix this?

Symfony 4 Collection form

$
0
0

I'm stuck in this for hours :( first the reuslt that i wanna reach is this form

The form Exemple

So first I started making the entity's Patient and TourismeRegion With ManyToOne relation it means : a patient can have only 1 tourismeRegion and TourismeRegion can have multiple patients

<?php



 namespace App\Entity;

    use Doctrine\Common\Collections\ArrayCollection;
    use Doctrine\Common\Collections\Collection;
    use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\PatientInformationsRepository")
 */
class PatientInformations
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $Name;

    /**
     * @ORM\Column(type="integer", nullable=true)
     */
    private $Age;

    /**
     * @ORM\Column(type="string", length=50, nullable=true)
     */
    private $Sexe;



    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Housing", inversedBy="patient")
     */
    private $housing;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Specialisation", inversedBy="patient")
     */
    private $specialisation;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\TourismeRegion", inversedBy="patient")
     */
    private $tourismeRegion;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $country;

    /**
     * @ORM\Column(type="integer")
     */
    private $phone;

    /**
     * @ORM\Column(type="string", length=50)
     */
    private $email;

    /**
     * @ORM\Column(type="text")
     */
    private $demande;




    public function getId(): ?int
    {
        return $this->id;
    }

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

    public function setName(string $Name): self
    {
        $this->Name = $Name;

        return $this;
    }

    public function getAge(): ?int
    {
        return $this->Age;
    }

    public function setAge(int $Age): self
    {
        $this->Age = $Age;

        return $this;
    }

    public function getSexe(): ?string
    {
        return $this->Sexe;
    }

    public function setSexe(string $Sexe): self
    {
        $this->Sexe = $Sexe;

        return $this;
    }

    public function getTourismRegion(): ?TourismRegion
    {
        return $this->tourismRegion;
    }

    public function setTourismRegion(?TourismRegion $tourismRegion): self
    {
        $this->tourismRegion = $tourismRegion;

        return $this;
    }

    public function getHousing(): ?Housing
    {
        return $this->housing;
    }

    public function setHousing(?Housing $housing): self
    {
        $this->housing = $housing;

        return $this;
    }

    public function getSpecialisation(): ?Specialisation
    {
        return $this->specialisation;
    }

    public function setSpecialisation(?Specialisation $specialisation): self
    {
        $this->specialisation = $specialisation;

        return $this;
    }

    public function getTourismeRegion(): ?TourismeRegion
    {
        return $this->tourismeRegion;
    }

    public function setTourismeRegion(?TourismeRegion $tourismeRegion): self
    {
        $this->tourismeRegion = $tourismeRegion;

        return $this;
    }

    public function getCountry(): ?string
    {
        return $this->country;
    }

    public function setCountry(string $country): self
    {
        $this->country = $country;

        return $this;
    }

    public function getPhone(): ?int
    {
        return $this->phone;
    }

    public function setPhone(int $phone): self
    {
        $this->phone = $phone;

        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    public function getDemande(): ?string
    {
        return $this->demande;
    }

    public function setDemande(string $demande): self
    {
        $this->demande = $demande;

        return $this;
    }



}


**Tourism Region entity**

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\TourismeRegionRepository")
 */
class TourismeRegion
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="date")
     */
    private $Arrival_date;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $estimate_period;



    /**
     * @ORM\Column(type="string", length=255)
     */
    private $Guide;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $Car;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\PatientInformations", mappedBy="tourismeRegion")
     */
    private $patient;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\MedicalCity", inversedBy="Region")
     */
    private $medicalCity;

    public function __construct()
    {
        $this->patient = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getArrivalDate(): ?\DateTimeInterface
    {
        return $this->Arrival_date;
    }

    public function setArrivalDate(\DateTimeInterface $Arrival_date): self
    {
        $this->Arrival_date = $Arrival_date;

        return $this;
    }

    public function getEstimatePeriod(): ?string
    {
        return $this->estimate_period;
    }

    public function setEstimatePeriod(string $estimate_period): self
    {
        $this->estimate_period = $estimate_period;

        return $this;
    }



    public function getGuide(): ?string
    {
        return $this->Guide;
    }

    public function setGuide(string $Guide): self
    {
        $this->Guide = $Guide;

        return $this;
    }

    public function getCar(): ?string
    {
        return $this->Car;
    }

    public function setCar(string $Car): self
    {
        $this->Car = $Car;

        return $this;
    }

    /**
     * @return Collection|PatientInformations[]
     */
    public function getPatient(): Collection
    {
        return $this->patient;
    }

    public function addPatient(PatientInformations $patient): self
    {
        if (!$this->patient->contains($patient)) {
            $this->patient[] = $patient;
            $patient->setTourismeRegion($this);
        }

        return $this;
    }

    public function removePatient(PatientInformations $patient): self
    {
        if ($this->patient->contains($patient)) {
            $this->patient->removeElement($patient);
            // set the owning side to null (unless already changed)
            if ($patient->getTourismeRegion() === $this) {
                $patient->setTourismeRegion(null);
            }
        }

        return $this;
    }

    public function getMedicalCity(): ?MedicalCity
    {
        return $this->medicalCity;
    }

    public function setMedicalCity(?MedicalCity $medicalCity): self
    {
        $this->medicalCity = $medicalCity;

        return $this;
    }
}

After that I made the tourismregion form:

<?php

namespace App\Form;

use App\Entity\TourismeRegion;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class RegiontourismType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('Arrival_date',DateType::class)
            ->add('estimate_period',TextType::class,[
                'choices'  => [
                    'Non prévue'=>'Non prévue',
                    '1 semaine'=>'1 semaine' ,
                    '2 semaine'=>'2 semaine',
                    '3 semaine'=>'3 semaine',
                    '1 Mois'=>'1 Mois',
                    'Plus de 1 mois '=>'Plus de 1 mois',
                ],
            ])
            ->add('Guide',TextType::class,[
                'choices'  => [
                    'Oui'=>'Oui' ,
                    'Non'=>'Non',

                ],
            ])
            ->add('Car',TextType::class,[
                'choices'  => [
                    'Sans Voiture'=>'Sans Voiture',
                    'Avec Voiture'=>'Avec Voiture' ,
                    'Voiture Avec Chauffeur'=>'Voiture Avec Chauffeur',
                ],
            ])
            ->add('medicalCity',TextType::class)
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => TourismeRegion::class,
        ]);
    }
}


**Then I made the Patient form :**

<?php

namespace App\Form;

use App\Entity\PatientInformations;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;

class PatientInfo2Type extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('Age',NumberType::class)
            ->add('Sexe',ChoiceType::class,[
                'choices'  => [
                    'Women'=>'Women',
                    'Men'=>'Men' ,
                    'Other'=>'Other',
                ],
            ])
            ->add('tourismeRegion',CollectionType::class,[
                'entry_type' => RegiontourismType::class,
                'entry_options' => ['label' => false],
                'prototype' => true


            ])
            ->add('housing')
            ->add('specialisation')
            ->add('Save',SubmitType::class,[
                'attr' => [
                    'class' => 'btn-success'
                ]
            ])

        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => PatientInformations::class,
        ]);
    }
}

I made the Controller and the twig finally and i followed the symfony collection form documentation but it doesn't work :(

Controller

<?php

namespace App\Controller;

use App\Entity\PatientInformations;
use App\Entity\Test;
use App\Entity\TourismeRegion;
use App\Form\PatientInfo2Type;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

class PatientInfoController extends AbstractController
{
    /**
     * @Route("/patient/info", name="patient_info")
     */
    public function index(Request $request)
    {   $patient= new PatientInformations();

        $region= new TourismeRegion();
        $region->setArrivalDate(new \DateTime());
        $region->setGuide("Non");
        $region->setEstimatePeriod("2 semaine");
        $region->setCar("Sans Voiture");




        $form = $this->createForm(PatientInfo2Type::class,$patient);

        $form->handleRequest($request);
        $patient->setTourismeRegion($region);


        return $this->render('patient_info/index.html.twig', [
            'PatientInfo' => $form->createView(),
        ]);
    }
}


**TWIG**

{% extends 'base.html.twig' %}

{% block title %}Request{% endblock %}

{% block body %}

    <div class="container">
        <h1>Informations Patient</h1>
        {{ form_start(PatientInfo) }}
        {# iterate over each existing tag and render its only field: name #}
                {{ dump(PatientInfo) }}
        <div>
            {% for row in PatientInfo.tourismeRegion %}
               {{ form_row(row.estimate_period) }}
            {% endfor %}
                </div>


        {{ form_end(PatientInfo) }}
    </div>


{% endblock %}

I just made ony patient and tourismregion cause I wanna see if it works i'll make the others the same way I think that I have a problem in The Controllor part help please i've been stuck in the for hours.

Enlight_Controller_Action_PreDispatch_Frontend is not working in Plugin.php class

$
0
0

I am creating a shopware 5 plugin. I want to display something after the categories on every page. I am using this code to do my task as suggested in this video, but the event is not getting recognized.

Here is my code

<?php
namespace MyPlugin;

use Shopware\Components\Plugin;

class MyPlugin extends Plugin{
    public static function getSubscribedEvents()
    {
        return [
            'Enlight_Controller_Action_PreDispatch_Frontend' => 'onPreDispatch'
        ];
    }

    public function onPreDispatch(\Enlight_Event_EventArgs $args)
    {
        $controller = $args->getSubject();
        $view = $controller->View();

        $view->addTemplateDir(__DIR__.'/Resources/views');
    }
}

frontend/index/index.tpl

{extends file="parent:frontend/index/index.tpl"}
{block name="frontend_index_navigation_categories_top" append}
    <div>my items here</div>
{/block}

Any help would be much appreciated.


How to create your own customized DQL just like Symfony's DQL

$
0
0

This is my customized DQL.

DQL.php

class DQL {
    protected $select;
    protected $from;

    public function select($string)
    {
        $this->stmt .= $string;
    }

    public function from($table, $alias)
    {
        $this->stmt .= " FROM " . $table . " AS " . $alias;
    }

    public function getQuery()
    {
        $this->query = $this->conn->prepare($this->stmt);
    }

     public function getResult()
     {
        $this->query->execute();
        return json_encode($this->query->fetchAll());
     }

 }

I call it like this.

Student.php

$em = new DQL();
$em->select('*');
$em->from('student_credentials', 'sc');
$em->getQuery();
$em->getResult();

Putting $em each line is quite a work. So how can I implement the code below. This is how "Symfony" uses it.

$em = new DQL();
$em->select('*')
   ->from('student_credentials', 'sc')
   ->getQuery()
   ->getResult();

I know that this returns Call to a member function from() on null.

How can I make this work or is there any way to use DQL plug ins etc.

isGranted returns false for logged in user JWT - Symfony API-Platform AWS-EB

$
0
0

I have deployed an API-Platform app using JWT token to ElasticBeanstalk which, as usual, works fine in my local server.

On EB though it is denying access to logged in users despite the correct BearerToken being provided.

This is the error thrown:

{
 "errors": [
    {
        "message": "Access Denied.",
        "extensions": {
            "category": "graphql"
        },
        "locations": [
            {
                "line": 6,
                "column": 9
            }
        ],
        "path": [
            "retrievedQueryUser"
        ]
    }
],
"data": {
    "retrievedQueryUser": null
}
}

The query in question attempts to retrieve user profile info through the below graphql config:

*          "retrievedQuery"={
*              "item_query"=UserProfileResolver::class,
*              "normalization_context"={"groups"={"get-owner"}},
*              "security"="is_granted('IS_AUTHENTICATED_FULLY') and object == user"
*          },

So, it should be a simple matter of checking if the users IS_AUTHENTICATED_FULLY and if it is the user him/herself trying to execute the query.

Far as I could tell, by dump below on /vendor/symfony/security-core/Authorization/AuthorizationChecker.php, it's failing to retrieve a token.

 var_dump($this->tokenStorage->getToken()->getUser()->getUsername());

I did a cursory comparison of phpinfo() between my local installation and the one at AWS-EB and could not find any obvious mismatch.

This is the config for JWT at /config/packages/lexik_jwt_authentication.yaml.

lexik_jwt_authentication:
   secret_key: '%env(resolve:JWT_SECRET_KEY)%'
   public_key: '%env(resolve:JWT_PUBLIC_KEY)%'
   pass_phrase: '%env(JWT_PASSPHRASE)%'
   user_identity_field: email
   token_ttl: 1800

Just to confirm that the users are able to login. It's passing through the isGranted() check that fails.

Any ideas?

EDIT - add `/config/packages/security.yaml

security:
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
encoders:
    App\Entity\User:
        algorithm: auto
        #algorithm: bcrypt
        #algorithm: argon2i
        cost: 12
providers:
    database:
        entity:
            class: App\Entity\User
            property: email
firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    refresh:
        pattern:  ^/api/token/refresh
        stateless: true
        anonymous: true
    api:
        pattern:  ^/api
        stateless: true
        anonymous: true
        json_login:
            check_path:               /api/login_check
            success_handler:          lexik_jwt_authentication.handler.authentication_success
            failure_handler:          lexik_jwt_authentication.handler.authentication_failure
        guard: 
            authenticators: 
                - app.google_login_authenticator
                - App\Security\TokenAuthenticator
            entry_point: App\Security\TokenAuthenticator
        user_checker: App\Security\UserEnabledChecker
     access_control:
    - { path: ^/login,     roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/admin,     roles: ROLE_SUPERADMIN }
    - { path: ^/api/token/refresh, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/api,       roles: IS_AUTHENTICATED_ANONYMOUSLY }
role_hierarchy:
    ROLE_PROVIDER: ROLE_USER
    ROLE_ADMIN: [ROLE_PROVIDER, ROLE_EDITOR]
    ROLE_SUPERADMIN: ROLE_ADMIN

how fix script cache:clear returned error code 255 in symfony 4

$
0
0

I get a project by command-line git clone on bitbucket. I run php ../composer.phar install and I had after installing all these dependencies the following error:

Executing script cache:clear [KO] [KO] Script cache:clear returned with error code 255 !! !! Warning: require(... PHP Fatal error: require(): Failed opening required 'C:\xampp\htdocs\aksymfony4\myProjetSf4\vendor\composer/../symfony/validator/Resources/functions/dump.php' (include_path='C:\xampp\php\PEAR')

enter image description here

How fix this error?

Thanks

I use:

Xampp v3.2.4, Symfony 4.4, php: 7.3.15

__construct() must implement interface Symfony\Component\HttpKernel\KernelInterface

$
0
0

I want to use KernelInterface in an AbstractAdmin class of sonata admin, using symfony 4.

use Symfony\Component\HttpKernel\KernelInterface;

class LocationsAdmin extends AbstractAdmin
{
  private $kernel;

public function __construct(string $code, string $class, string $baseControllerName, KernelInterface $appKernel)
{
    parent::__construct($code, $class, $baseControllerName);

    $this->kernel = $appKernel;
}

But i got that

Argument 4 passed to App\Admin\XXXAdmin::__construct() must implement interface Symfony\Component\HttpKernel\KernelInterface, null given, called in /Users/ugolaf/gcg/rentil/var/cache/de_/Container8jI612X/getAdmin_LocationsService.php on line 26

So I tried to set autowire in my services.yaml like this :

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.
    public: false       # Allows optimizing the container by removing unused services; this also means
                        # fetching services directly from the container via $container->get() won't work.
                        # The best practice is to be explicit about your dependencies anyway.

admin.XXX:
    class: App\Admin\XXXAdmin
    arguments: [~, App\Entity\XXX, App\Controller\CRUDController, ~]
    tags:
    - { name: sonata.admin, manager_type: orm, group: "Locations", label: Locations, on_top: true, icon: "<i class=\"fa fa-key\"></i>" }
    autowire: true
    public: true

But I still have the same issue after clearing cache.

How to set user in security token_storage symfony 4 jwt token

$
0
0

How to set user in security token_storage symfony 4 jwt token

I can't find the current user

dump($this->get('security.token_storage'));
die;

result:

enter image description here

Symfony 4 : How to edit entity and related entity with relation one-to-one

$
0
0

I have two entities (page and slug) with relation one to one Unidirectional

  • The problem appears when I leave the field slug empty
  • because i want to update the Slug object by title if it is empty

Error : Expected argument of type "string", "null" given at property path "name".

and here is my code

MY : CONTOLLER

public function edit(Page $page, Request $request, EntityManagerInterface $entityManager)
   {
       $form = $this->createForm(PageType::class, $page);
       $form->handleRequest($request);
       if ($form->isSubmitted() && $form->isValid()) {
           $entityManager->flush();
           $this->addFlash(
               'success',
               "Page  <strong>{$page->getTitle()}</strong> Updated successfully. "
           );
           return $this->redirectToRoute("backoffice_page_edit", ["id" => $page->getId()]);
       }
       return $this->render('back_office/page/edit.html.twig', [
           'form' => $form->createView(),
       ]);
   }

ENTITY PAGE :

class Page extends EntityBase
{
   /**
    * @ORM\Id()
    * @ORM\GeneratedValue()
    * @ORM\Column(type="integer")
    */
   private $id;

   /**
    * @ORM\Column(type="string", length=255)
    */
   private $title;

   /**
    * @ORM\Column(type="text")
    */
   private $content;

   /**
    * @ORM\Column(type="boolean")
    */
   private $status;

   /**
    * @ORM\OneToOne(targetEntity="App\Entity\Slug", inversedBy="page", cascade={"persist", "remove"})
    * @ORM\JoinColumn(nullable=false)
    * @Assert\Valid
    */
   private $slug;

   public function getId(): ?int
   {
       return $this->id;
   }

   public function getTitle(): ?string
   {
       return $this->title;
   }

   public function setTitle(string $title): self
   {
       $this->title = $title;

       return $this;
   }

   public function getContent(): ?string
   {
       return $this->content;
   }

   public function setContent(string $content): self
   {
       $this->content = $content;

       return $this;
   }

   public function getStatus(): ?bool
   {
       return $this->status;
   }

   public function setStatus(bool $status): self
   {
       $this->status = $status;

       return $this;
   }

   public function getSlug(): ?Slug
   {

       return $this->slug;
   }

   public function setSlug(Slug $slug): self
   {

       $this->slug = $slug;
       return $this;
   }
   /**
    * Set the Slug object by title if it is empty
    * @ORM\PrePersist
    * @ORM\PreUpdate
    */
   public function setSlugByTitle(): void
   {
       if (null === $this->getSlug()) {
           $slug = new Slug();
           $slug->setName($this->getTitle());
           $this->setSlug($slug);
       }

   }
}

ENTITY SLug:

class Slug  extends EntityBase
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\OneToOne(targetEntity="App\Entity\Page", mappedBy="slug", cascade={"persist", "remove"})
     */
    private $page;

    public function getId(): ?int
    {
        return $this->id;
    }

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

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

        return $this;
    }

    public function getPage(): ?Page
    {
        return $this->page;
    }

    public function setPage(Page $page): self
    {
        $this->page = $page;

        // set the owning side of the relation if necessary
        if ($page->getSlug() !== $this) {
            $page->setSlug($this);
        }

        return $this;
    }

    /**
     * @ORM\PreUpdate()
     * @ORM\PrePersist()
     */
    public function initializeSlug()
    {
        $slugify = new Slugify();
        $this->name = $slugify->slugify($this->name);
    }
}


FORM PAGE

class PageType extends ApplicationType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', TextType::class, $this->getConfiguration("Title", "Type a title for this page"))
            ->add('slug', SlugType::class, $this->getConfiguration(false, false, [
                'required' => false,
            ]))
            ->add('content', CKEditorType::class, $this->getConfiguration("Content", ""))
            ->add('status', CheckboxType::class, $this->getConfiguration("Published", "", [
                'attr' => ['checked' => 'checked'],
                'required' => false,
            ]));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Page::class,
        ]);
    }
}

FORM Slug

class SlugType extends ApplicationType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class, $this->getConfiguration("Slug", "Type a slug valid for this page"));
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Slug::class,
        ]);
    }
}

webpack encore and jquery ui (dateRangeSlider)

$
0
0

I'm having trouble integrating a jquery-ui plugin with my Symfony app using Webpack Encore. You can see the error (TypeError: t(...).dateRangeSlider is not a function[Learn More]) in the console:

https://date-range-demo.herokuapp.com/en/blog/search

enter image description here

Source code for this is at https://github.com/tacman/range-slider-demo, it's simply the symfony demo with a date range slider on the search page, via the following changes:

add the libraries to package.json from the command line

yarn add jquery-ui jqrangeslider

add to /blog/search.html

<div id="slider">Slider Placeholder</div>

added to assets/js/search.js

import 'jquery-ui'; 
import 'jqrangeslider';

$('#slider').dateRangeSlider();

Assets are build with 'yarn run encore dev', I'm sure it's a simple configuration error but I can't figure out what it is.

Deployment to heroku added a few more things, but are unrelated to the plugin not loading. To see this error locally, simply clone the repo, run composer install && yarn install && yarn run encore dev, then start the server and go to /en/blog/search.

Thanks for any help on this!


Symfony 4 post requests are too slow [closed]

$
0
0

I'm making a website in Symfony 4. My problem is that forms take a long time to be submit.

When I submit one of them, I wait between 5 and 20 seconds before the form ends.

I have this problem in local and prod. But in dev, forms submit instantly.

Prod and dev are in the same server (Debian 10, PHP 7.2, MariaDB 10.3) and have the same code, currently. I copied the prod database in dev to get the same amount of data.

When I watch the DOM Network of my browsers (Chrome or Firefox), I can see a post request that takes a long time to complete with 302 response.

Do you know what test I can do? Or have you had the same problem and how to solve it?

Unittesting a Symfony 4.2 process runs infinite loop (than times out), wihout unittest it works fine

$
0
0

Lets say I have the following Symfony 4 command:

class Command1  extends Command {
    protected static $defaultName = 'app:command1';

    protected function execute(InputInterface $input, OutputInterface $output){
        $process = new Process('bin/console list', getcwd());
        $process->start(); // or even $process->run() does not matter if its async or not
        // ... where we handle if its finished, etc...
    }
}

If I simply call bin/console app:command1 it will return the expected command list. Basically works as I expect.

But if I have a phpunit test which uses the Symfony\Component\Console\Application::run() to start this command, I end up in an "infinite loop" (well, actually not, it times out after 60 sec) in the Symfony\Component\Process::wait() in the

do {
    $this->checkTimeout();
    $running = '\\' === \DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
    $this->readPipes($running, '\\' !== \DIRECTORY_SEPARATOR || !$running);
} while ($running);

where the $this->processPipes->areOpen() will be always open.

It seems to me, if I use any Symfony console command in a Process through phpunit, there will be always two pipes open like these:

1 = {resource} resource id='x' type='stream'
2 = {resource} resource id='z' type='stream'

but I don't know what are these actually. I also saw in htop, that the start()'s proc_open actually starts up a new process, but it just hangs (does absolutely nothing, cant even debug it), until times out. Nothing in error logs (other than the timeout).

Form Handler don't work well createVew() based on Null

$
0
0

i never work with symfony before, and i have an error in my code. a friend explain me i could create an handler for use my forms,

the error is : when i call route 'create' i have error 500 ==> Call to a member function createView() on null.

the error seems to be located here :

return $this->render("admin/trick/create.html.twig", [
            "form" => $handler->createView()
        ]); 

someone could just explain me why ?

here : my controller

<?php

namespace App\Controller;

use App\Entity\Comment;
use App\Entity\Trick;
use App\Form\CommentType;
use App\Form\TrickType;
use App\Handler\TrickHandler;
use App\Repository\CommentRepository;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use App\Repository\TrickRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class TrickController extends AbstractController
{
    private $trickRepository;

    public function __construct(TrickRepository $trickRepository, CommentRepository $commentRepository)
    {
        $this->trickRepository = $trickRepository;
        $this->commentRepository = $commentRepository;

    }

    /**
     * @Route("/trick", name="trick.list")
     * @return Response
     */
    public function index(): Response
    {
        return new Response('listing des tricks');
    }

    /**
     * @Route("/trick/{slug}", name="trick.show", requirements={"slug": "[a-z0-9\-]*"})
     * @return Response
     */
    public function show(Trick $trick, Request $request): Response
    {
        $comment = new Comment();
        $form = $this->createForm(CommentType::class, $comment)->handleRequest($request);
        $user = $this->getUser();
        $displayedcomments = $this->commentRepository->getAllComments(1);

        if ($form->isSubmitted() && $form->isValid()) {
            $comment->setTrick($trick);
            $comment->setAuthor($user);
            $this->getDoctrine()->getManager()->persist($comment);
            $this->getDoctrine()->getManager()->flush();
            $slug = $trick->getSlug();

            return $this->redirectToRoute("trick.show",array('slug' => $slug));

        }
        return $this->render('pages/trick/show.html.twig',[
                'trick' => $trick,
                'displayedcomments' => $displayedcomments,
                'current_menu'=>'home',
                "form" => $form->createView()
            ]
        );
    }

    /**
     * @Route("/morecomments", name="morecomments")
     *
     * @param $page
     * @return Response
     */
    public function moreComments(Request $request): Response
    {
        $page = $request->query->getInt("page");
        $displayedcomments = $this->commentRepository->getAllComments($page);
        $limit = 5;

        return $this->render('parts/forcomments.html.twig', [
                'displayedcomments' => $displayedcomments,
            ]
        );
    }

    /**
     * @Route("/delete/{slug}", name="trick.delete", requirements={"slug": "[a-z0-9\-]*"})
     * @return Response
     */
    public function delete( Trick $trick): Response
    {
        $this->getDoctrine()->getManager()->remove($trick);
        $this->getDoctrine()->getManager()->flush();
        return $this->redirectToRoute('home');
    }

    /**
     * @Route("/create", name="trick_create")
     * @param Request $request
     * @param TrickHandler $handler
     * @return Response
     */
    public function create(Request $request,TrickHandler $handler): Response
    {
        if($handler->handle($request, new Trick(), ["validation_groups" => ["Default", "add"]        ]
        )) {
            return $this->redirectToRoute("trick_create");
        }
        dump($handler);
        return $this->render("admin/trick/create.html.twig", [
            "form" => $handler->createView()
        ]);
    }

    /**
     * @Route("/{id}/update", name="trick_update")
     * @param Request $request
     * @param Trick $trick
     * @param TrickHandler $handler
     * @return Response
     */
    public function update(Request $request, Trick $trick,TrickHandler $handler): Response
    {
        if($handler->handle($request, $trick)) {
            return $this->redirectToRoute("trick_update",array('id' => $trick->getId()));
        }
        return $this->render("admin/trick/update.html.twig", [
            "form" => $handler->createView()
        ]);
    }
}

here : my AbstractHandler

<?php

namespace App\Handler;


use Symfony\Component\Form\FormView;
use Symfony\Component\Form\Test\FormInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\FormFactoryInterface;

abstract class AbstractHandler
{
    /**
    * @var FormFactoryInterface
     */

    private $formFactory;

    /**
     * @var FormInterface
     */
    private $form;

    /**
     * @return string
     */
    abstract protected function getForm() : string;

    /**
     * @param $data
     */
    abstract protected function process($data) : void;

    /**
     * @required
     * @param FormFactoryInterface $formFactory
     */
    public function setFormFactory(FormFactoryInterface $formFactory) :void
    {
        $this->formFactory = $formFactory;
    }

    /**
     * @param Request $request
     * @param $data
     * @param array $options
     * @return bool
     */
    public function handle(Request $request, $data, array $options = []) :bool
    {
        $form = $this->formFactory->create($this->getForm(), $data, $options)->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $this->process($data);
            return true;
        }
        return false;
    }
    public function createView() :FormView
    {
        return $this->form->createView();
    }
}

here : my TrickHandler

<?php

namespace App\Handler;

use App\Form\TrickType;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\UnitOfWork;

class TrickHandler extends AbstractHandler
{
    /**
     * @var EntityManagerInterface
     */
    private $entityManager;

    /**
     * TrickHandler constructor.
     * @param EntityManagerInterface $entityManager
     */
    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    protected function getForm(): string
    {
        // TODO: Implement getForm() method.
        return TrickType::class;
    }

    protected function process($data): void
    {
        // TODO: Implement process() method.
        if ($this->entityManager->getUnitOfWork()->getEntityState($data) === UnitOfWork::STATE_NEW) {
            $this->entityManager->persist($data);
        }
        $this->entityManager->flush();

    }

}

Thanks a lot

Symfony handle Api request by form

$
0
0

I'm using Symfony 4.4 as a restful API with no views at all. I want to avoid annoying code like this:


        $email = $request->get('email');
        $password = $request->get('password');
        $newUser = new User();
        $newUser->setEmail($email)->setPassword($password));

Because if one entity has a lot of properties I have to spend a lot of time getting every variable from the request->get('property'). So I decided to try to use Symfony forms.

But I always get this error:

Expected argument of type \"array\", \"null\" given at property path \"roles\"."

My user class

<?php

namespace App\Entity;

use DateTime;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * @Groups({"public"})
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=180, unique=true)
     * @Assert\Email
     * @Assert\NotBlank
     * @Assert\NotNull
     * @Groups({"public"})
     */
    private $email;

    /**
     * @ORM\Column(type="json")
     * @Groups({"public"})
     */
    private $roles = [];

    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     * @Assert\Type("string")
     * @Assert\NotBlank
     * @Assert\NotNull
     */
    private $password;

    /**
     * @ORM\Column(type="datetime")
     * @Groups({"public"})
     */
    private $createdAt;

    /**
     * @ORM\Column(type="datetime")
     * @Groups({"public"})
     */
    private $updatedAt;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Log", mappedBy="user")
     */
    private $logs;

    /**
     * User constructor.
     */
    public function __construct()
    {
        $this->createdAt = new DateTime();
        $this->updatedAt = new DateTime();
        $this->logs = new ArrayCollection();
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = strtolower($email);

        return $this;
    }

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUsername(): string
    {
        return (string) $this->email;
    }

    /**
     * @see UserInterface
     */
    public function getRoles(): array
    {
        $roles = $this->roles;
        // guarantee every user at least has ROLE_USER
        $roles[] = 'ROLE_USER';

        return array_unique($roles);
    }

    public function setRoles(array $roles): self
    {
        $this->roles = $roles;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getPassword(): string
    {
        return (string) $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;
        $this->updatedAt = new DateTime(); // updates the updatedAt field

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getSalt()
    {
        // not needed when using the "bcrypt" algorithm in security.yaml
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials()
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }

    /**
     * Get the value of createdAt
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set the value of createdAt
     *
     * @return  self
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    public function getUpdatedAt(): ?\DateTimeInterface
    {
        return $this->updatedAt;
    }

    public function setUpdatedAt(\DateTimeInterface $updatedAt): self
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * @return Collection|Log[]
     */
    public function getLogs(): Collection
    {
        return $this->logs;
    }

    public function addLog(Log $log): self
    {
        if (!$this->logs->contains($log)) {
            $this->logs[] = $log;
            $log->setUser($this);
        }

        return $this;
    }

    public function removeLog(Log $log): self
    {
        if ($this->logs->contains($log)) {
            $this->logs->removeElement($log);
            // set the owning side to null (unless already changed)
            if ($log->getUser() === $this) {
                $log->setUser(null);
            }
        }

        return $this;
    }
}

The form that I've created simply using the makerbundle

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options):void
    {
        $builder
            ->add('email')
            ->add('roles')
            ->add('password')
            ->add('createdAt')
            ->add('updatedAt')
        ;
    }

    public function configureOptions(OptionsResolver $resolver):void
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }

And my controller

    public function postUsersAction(Request $request): View
    {

        $data = json_decode($request->getContent(), true);
        $user = new User();
        $form = $this->createForm(UserType::class);
        $form->handleRequest($request);
        $form->submit($data);

        return $this->view(['message' => $form->isValid()], Response::HTTP_OK); // for testing purposes

The data that I'm sending through postman is something like:

email=duuuu@gmail.com&password=1234

Updating field inside a repository [closed]

$
0
0

I'm creating a CRON in my Symfony 4 App (command) to archive news that is older than 60 days. How should this be done?

My first instinct was to add a method to my NewsRepository to retrieve all news that needs to be archive and update their isArchived boolean method from false to true if it's the case.

Then, I had this idea of adding the logic for archiving the news inside the repository so that it's usable outside the Command. I could also put the logic (MySQL Updates) inside the Command and just have the ''find'' query inside the repository.

Which of these approaches is preferable, and why? Should my repository method be findNewsToArchive and do the update logic inside the command, or should it be archiveAllNewsThatNeedsToBeArchived and do all the logic in the repository?

Viewing all 3918 articles
Browse latest View live


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