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

Symfony 4 EasyAdmin Bundle Create Entities Linked by a ManyToMany Relationship

$
0
0

I am working on a small project to manage the pay slips of a small enterprise with Symfony4 and I use easyAdmin as a beginner. I have three classes (Employe, Lot and Bulletin) linked by ManyToOne - OneToMany relationships to say that an "Employe" has multiple "Bulletin", a "Lot" can have multiple Bulletin and a "Bulletin" belongs to a single "Lot" and a single "Employe": The "Employe" class:

<?php

class Employe
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;
      /**
     * @ORM\Column(type="string", length=255)
     */
    private $fullName;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Bulletin", mappedBy="employe", orphanRemoval=true)
     */
    private $bulletins;

    public function __construct()
    {
        $this->elements = new ArrayCollection();
        $this->liaisons = new ArrayCollection();
        $this->bulletins = new ArrayCollection();
    }
    /**
     * @return Collection|Bulletin[]
     */
    public function getBulletins(): Collection
    {
        return $this->bulletins;
    }

    public function addBulletin(Bulletin $bulletin): self
    {
        if (!$this->bulletins->contains($bulletin)) {
            $this->bulletins[] = $bulletin;
            $bulletin->setEmploye($this);
        }

        return $this;
    }

    public function removeBulletin(Bulletin $bulletin): self
    {
        if ($this->bulletins->contains($bulletin)) {
            $this->bulletins->removeElement($bulletin);
            // set the owning side to null (unless already changed)
            if ($bulletin->getEmploye() === $this) {
                $bulletin->setEmploye(null);
            }
        }

        return $this;
    }
    // getters and setters
}

//La classe Lot :

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

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

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Bulletin", mappedBy="lot", orphanRemoval=true, cascade={"persist"})
     */
    private $bulletins;

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

    }

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

    public function getLibelle(): ?string
    {
        return $this->libelle;
    }

    public function setLibelle(string $libelle): self
    {
        $this->libelle = $libelle;

        return $this;
    }
    /**
     * @return Collection|Bulletin[]
     */
    public function getBulletins(): Collection
    {
        return $this->bulletins;
    }

    public function addBulletin(Bulletin $bulletin): self
    {
        if (!$this->bulletins->contains($bulletin)) {
            $this->bulletins[] = $bulletin;
            $bulletin->setLot($this);
        }

        return $this;
    }

    public function removeBulletin(Bulletin $bulletin): self
    {
        if ($this->bulletins->contains($bulletin)) {
            $this->bulletins->removeElement($bulletin);
            // set the owning side to null (unless already changed)
            if ($bulletin->getLot() === $this) {
                $bulletin->setLot(null);
            }
        }

        return $this;
    }

    public function __toString(){

        return $this->libelle;
    }
}


//La classe bulletin

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

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Employe", inversedBy="bulletins")
     * @ORM\JoinColumn(nullable=false)
     */
    private $employe;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Lot", inversedBy="bulletins",cascade={"persist"})
     * @ORM\JoinColumn(nullable=false)
     */
    private $lot;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Figurer", mappedBy="bulletin", orphanRemoval=true)
     */
    private $figurations;

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

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

    public function getEmploye(): ?Employe
    {
        return $this->employe;
    }

    public function setEmploye(?Employe $employe): self
    {
        $this->employe = $employe;

        return $this;
    }

    public function getLot(): ?Lot
    {
        return $this->lot;
    }

    public function setLot(?Lot $lot): self
    {
        $this->lot = $lot;

        return $this;
    }

    /**
     * @return Collection|Figurer[]
     */
    public function getFigurations(): Collection
    {
        return $this->figurations;
    }

    public function addFiguration(Figurer $figuration): self
    {
        if (!$this->figurations->contains($figuration)) {
            $this->figurations[] = $figuration;
            $figuration->setBulletin($this);
        }

        return $this;
    }

    public function removeFiguration(Figurer $figuration): self
    {
        if ($this->figurations->contains($figuration)) {
            $this->figurations->removeElement($figuration);
            // set the owning side to null (unless already changed)
            if ($figuration->getBulletin() === $this) {
                $figuration->setBulletin(null);
            }
        }

        return $this;
    }

    public function __toString(){

        return $this->employe->getId().''.$this->employe->getFullName();
    }
}

I would now like that when creating a "Lot" with EasyAdmin that a "Bulletin" be generated for each employee and saved in the database. for example if I have 5 employees in my database, when creating a "Lot", 5 bulletins containing the same object Lot + an object "Employe" in the list of 5 are created automatically.

What I have done :

I created a LotController Controller which extends the EasyAdminController class and which I call as the basic controller in my easy_admin.yml

Code:

Easy_admin.yml

Lot: class: App\Entity\Lot controller: App\Controller\LotController

LotController.php

<?php

namespace App\Controller;

use App\Entity\Employe;
use App\Entity\Bulletin;
use EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController;

class LotController extends EasyAdminController
{
    public function persistEntity($entity)
    {

        $entityManager = $this->getDoctrine()->getManager();

        $employes =  $this->getDoctrine()
        ->getRepository(Employe::class)
        ->findAll();

        $bulletin = new Bulletin();

        $bulletin->setLot($entity);

        foreach($employes as $employe) {

            $bulletin->setEmploye($employe);
            $entityManager->persist($bulletin);
            $entityManager->flush();
        }

        parent::persistEntity($entity);   
    }
}

But when I save a lot only the "Bulletin" of the last "Employe" of my database is generated and I do not know why the first ones are omitted?

If you can help me ... Thank you in advance !

excuse my english, i'm french lol


Symfony Mailer TLS Certificate Validation Error

$
0
0

How can I turn off SSL certificate validations when using the new Mailer component with TLS and Symfony 5?

Symfony 4 Fos Rest : Error 415 Unsupported Media Type

$
0
0

Impossible to create a new event, I always get 415 error I test with postman, if I test the same endpoint with ParamConverter annotation, I can reach the function. So the error should come from configuration

Here is my controller

<?php

namespace App\Controller;

use App\Entity\Event;
use FOS\RestBundle\Controller\AbstractFOSRestController;
use FOS\RestBundle\View\View;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\Controller\Annotations as Rest;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
use Symfony\Component\Validator\ConstraintViolationListInterface;

/**
 * Event controller.
 * @Route("/api", name="api_")
 */
class EventController extends AbstractFOSRestController
{
    /**
     * Create New Event
     * @Rest\Post("/event/create")
     * @param Event $event
     * @param ConstraintViolationListInterface $violations
     * @ParamConverter("event", converter="fos_rest.request_body")
     * @throws
     * @return View
     */
    public function createAction(Event $event, ConstraintViolationListInterface $violations)
    {
        if (count($violations)) {
            return View::create($violations, Response::HTTP_BAD_REQUEST);
        }

        $em = $this->getDoctrine()->getManager();

        $em->persist($event);
        $em->flush();

        return View::create($event, Response::HTTP_OK);
    }
}

This is Fost Rest configuration, I checked the documentation and it should be ok

# Read the documentation: https://symfony.com/doc/master/bundles/FOSRestBundle/index.html
fos_rest:
    routing_loader:
        default_format: json
        include_format: false
    body_listener: true
    format_listener:
          rules:
              - { path: '^/', priorities: ['json'], fallback_format: json, prefer_extension: false }
    param_fetcher_listener: true
    access_denied_listener:
        json: true
    view:
        view_response_listener: 'force'
        formats:
            json: true
    body_converter:
        enabled: true
        validate: true
        validation_errors_argument: violations

And to finish, event entity

<?php

namespace App\Entity;

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

/**
 * @ORM\Entity
 * @ORM\Table(name="event")
 */
class Event
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\User")
     *
     */
    protected $organizer;

    /**
     * @ORM\Column(type="text")
     * @Assert\NotBlank
     */
    protected $title;

    /**
     * @ORM\Column(type="text")
     */
    protected $description;

    /**
     * @ORM\Column(type="text")
     */
    protected $address;

    /**
     * @ORM\Column(type="text")
     */
    protected $city;

    /**
     * @ORM\Column(type="text")
     */
    protected $postCode;

    /**
     * @ORM\Column(type="text")
     */
    protected $coverPicture;

    /**
     * @ORM\Column(type="float")
     */
    protected $price;

    /**
     * @ORM\Column(type="integer")
     */
    protected $maxAttendees;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $dateFrom;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $dateTo;

    /**
     * @ORM\Column(type="integer")
     */
    protected $status;

    /**
     * @ORM\Column(type="boolean")
     */
    protected $featured;

    /**
     * List of attendees
     * @ORM\ManyToMany(targetEntity="User")
     * @ORM\JoinTable(name="event_atendees",
     *      joinColumns={@ORM\JoinColumn(name="event_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="attendee_id", referencedColumnName="id")}
     *      )
     */
    protected $attendees;

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

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

    /**
     * @param int $id
     * @return Event
     */
    public function setId(int $id)
    {
        $this->id = $id;

        return $this;
    }

    /**
     * @return User
     */
    public function getOrganizer() : User
    {
        return $this->organizer;
    }

    /**
     * @param User $organizer
     * @return Event
     */
    public function setOrganizer(User $organizer)
    {
        $this->organizer = $organizer;

        return $this;
    }

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

    /**
     * @param string $title
     * @return Event
     */
    public function setTitle(string $title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * @return string
     */
    public function getDescription() : string
    {
        return $this->description;
    }

    /**
     * @param string $description
     * @return Event
     */
    public function setDescription(string $description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * @return string
     */
    public function getAddress() : string
    {
        return $this->address;
    }

    /**
     * @param string $address
     * @return Event
     */
    public function setAddress(string $address)
    {
        $this->address = $address;

        return $this;
    }

    /**
     * @return string
     */
    public function getCity() : string
    {
        return $this->city;
    }

    /**
     * @param string $city
     * @return Event
     */
    public function setCity(string $city)
    {
        $this->city = $city;

        return $this;
    }

    /**
     * @return string
     */
    public function getPostCode() : string
    {
        return $this->postCode;
    }

    /**
     * @param string $postCode
     * @return Event
     */
    public function setPostCode(string $postCode)
    {
        $this->postCode = $postCode;

        return $this;
    }

    /**
     * @return string
     */
    public function getCoverPicture() : string
    {
        return $this->coverPicture;
    }

    /**
     * @param string $coverPicture
     * @return Event
     */
    public function setCoverPicture(string $coverPicture)
    {
        $this->coverPicture = $coverPicture;

        return $this;
    }

    /**
     * @return float
     */
    public function getPrice() : float
    {
        return $this->price;
    }

    /**
     * @param float $price
     * @return Event
     */
    public function setPrice(float $price)
    {
        $this->price = $price;

        return $this;
    }

    /**
     * @return int
     */
    public function getMaxAttendees() : int
    {
        return $this->maxAttendees;
    }

    /**
     * @param int $maxAttendees
     * @return Event
     */
    public function setMaxAttendees(int $maxAttendees)
    {
        $this->maxAttendees = $maxAttendees;

        return $this;
    }

    /**
     * @return DateTime
     */
    public function getDateFrom() : DateTime
    {
        return $this->dateFrom;
    }

    /**
     * @param DateTime $dateFrom
     * @return Event
     */
    public function setDateFrom(DateTime $dateFrom)
    {
        $this->dateFrom = $dateFrom;

        return $this;
    }

    /**
     * @return DateTime
     */
    public function getDateTo() : DateTime
    {
        return $this->dateTo;
    }

    /**
     * @param DateTime $dateTo
     * @return Event
     */
    public function setDateTo(DateTime $dateTo)
    {
        $this->dateTo = $dateTo;

        return $this;
    }

    /**
     * @return int
     */
    public function getStatus() : int
    {
        return $this->status;
    }

    /**
     * @param int $status
     * @return Event
     */
    public function setStatus(int $status)
    {
        $this->status = $status;

        return $this;
    }

    /**
     * @return bool
     */
    public function getFeatured() : bool
    {
        return $this->featured;
    }

    /**
     * @param bool $featured
     * @return Event
     */
    public function setFeatured(bool $featured)
    {
        $this->featured = $featured;

        return $this;
    }

    /**
     * @return User[]
     */
    public function getAttendees() : ArrayCollection
    {
        return $this->attendees;
    }

    /**
     * @param User[] $attendees
     * @return Event
     */
    public function setAttendees($attendees)
    {
        $this->attendees = $attendees;

        return $this;
    }

    /**
     * @param User $attendee
     */
    public function addAttendee(User $attendee) {
        $this->attendees->add($attendee);
    }

    /**
     * @param User $attendee
     */
    public function removeAttendee(User $attendee) {
        $this->attendees->removeElement($attendee);
    }

}

Is somebody have an idea ?

You have requested a non-existent service "fos_user.manager"

$
0
0

I use symfony 4.1.13 and FOSUser v2.1.2 I got this error when I try to clear cache.

You have requested a non-existent service "fos_user.manager".

Here is my controller function

 /**
 * Create New User
 * @Rest\Post("/user/create")
 * @param Request $request
 * @param UserManager $userManager
 * @return View
 */
public function createAction(Request $request, UserManager $userManager): View
{
    [...]

    $userManager->updatePassword($user);

    [...]

    return View::create($user, Response::HTTP_OK);
}

this service should exist :

bin/console debug:container
FOS\UserBundle\Model\UserManager  alias for "fos_user.manager"

Here is the content of config/packages/fos_user.yaml

# FOSUser
fos_user:
  db_driver: orm
  firewall_name: main
  user_class: App\Entity\User
  from_email:
    address: "noreply@yourcompany.com"
    sender_name: "No Reply"

Service.yaml

parameters:
    locale: 'en'

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.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

    # add more service definitions when explicit configuration is needed
    # please note that last definitions always *replace* previous ones

    sensio_framework_extra.view.listener:
        alias: Sensio\Bundle\FrameworkExtraBundle\EventListener\TemplateListener

    FOS\OAuthServerBundle\Model\AccessTokenManagerInterface:
        alias: fos_oauth_server.access_token_manager.default

    FOS\UserBundle\Model\UserManager:
        alias: fos_user.manager

How to convert json Request to an array in symfony?

$
0
0

I am trying to convert the JSON Request $request to an array.

I have output something like this:

^ Symfony\Component\HttpFoundation\Request {#45
  +attributes: Symfony\Component\HttpFoundation\ParameterBag {#74
    #parameters: array:3 [
      "_route" => "app_movie_create""_controller" => "App\Controller\MovieController::create""_route_params" => []
    ]
  }
  +request: Symfony\Component\HttpFoundation\ParameterBag {#96
    #parameters: []
  }
  +query: Symfony\Component\HttpFoundation\ParameterBag {#69
    #parameters: array:1 [
      "title" => "Homecoming"
    ]
  }

I have seen some tutorials giving following solutions.

 $data = json_decode($request->getContent(), true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new BadRequestHttpException('invalid json body: ' . json_last_error_msg());
        }

But I am getting null in my case.

I can do like this. $request->get('title');

Symfony4. How to work with 2 swiftmail configurations?

$
0
0

I have 2 smtp-servers. How can I switch between them? My service should decide via wich smtp-server to send a mail.

In my swiftmailer.yaml, I have only the following configuration.

swiftmailer:
    url: '%env(MAILER_URL)%'
    spool: { type: 'memory' }

Can I set the login and password to the smtp-server on the fly in my service? I need a quick solution, if it's possible.

Thank you

Validate symfony 4 formfield filetype with mapped false and multiple true

$
0
0

I got a project about snowboard tricks. In my project, I got an entity Trick, that itslef has an attribute "illustrations" that is a collection of another entity : Illustration. I'm trying to do a form TrickType in which the user could load many illustrations (images : png, jpeg, jpg, gif) at once. Then the controller save the files, and several illustration entities are created with the names and paths of the files as "url" attribute.

So, the TrickType can't manage directly illustration entities, because I got to use a FileType field in my form this way the files could be load, and filetype of course doesn't directly create entities. That's why the filetype field in my tricktype form has to have the following options :

  • multiple : true (serveral files are loaded at once)
  • mapped : false (there's no field in Trick that is about url, just a collection of illustration entities)

My entities, forms and controllers are correctly done : if I don't do any verifications about the files, or if I do verifications, but on only one file, everything perfectly works. But I got to ensure each file is really an image.

Here is what I tried to do so :

1 - constraints directly in TrickType :

->add('illustrations', FileType::class, [
                "label" => "Illustrations (optionnel)",
                "multiple" => true,
                "mapped" => false,
                "required" => false,
                "constraints" => [
                    new File([
                        "maxSize" => "10M",
                        "mimeTypes" => [
                            "image/png",
                            "image/jpg",
                            "image/jpeg",
                            "image/gif"
                        ],
                        "mimeTypesMessage" => "Veuillez envoyer une image au format png, jpg, jpeg ou gif, de 10 mégas octets maximum"
                    ])
                ]
            ])

problem : constraint try to check the field, which is a collection and not a file. So I got the error "this value should be of type string"

2 - no constraint in the form, but in entities

Note : this solution and the following ones wouldn't have prevent wrong files to be save because it only concern entities, not files. So even if it worked, it would just prevent wrong files to be found from url in database and put in the website, but it wouldn't have been a really good solution anyway

in Illustration entity :

/**
     * @ORM\Column(type="string", length=255)
     * @Assert\Regex("/((.jpg)|(.jpeg)|(.png)|(.gif))$/")
     */
    private $url;

in Trick entity, 2 things tried :

/**
     * @ORM\OneToMany(targetEntity="App\Entity\Illustration", mappedBy="trick")
     * @Assert\All({
     *      @Assert\Valid
     * })
     */
    private $illustrations;

error : "The constraint Valid cannot be nested inside constraint Symfony\Component\Validator\Constraints\All"

Second try for tricks :

/**
     * @ORM\OneToMany(targetEntity="App\Entity\Illustration", mappedBy="trick")
     * @Assert\Valid
     */
    private $illustrations;

no errors, but the form is considered valid whatever happen (I can add any type of files, symfony doesn't stop me)

3 - none of what I did before, but callback instead in Trick entity

/**
     * @Assert\Callback
     */
    public function checkIllustrations(ExecutionContextInterface $context, $payload)
    {
        $forbidenExtensions = false;

        foreach ($this->illustrations as $illustration) {
            $url = $illustration->getUrl();
            if (! preg_match('/((.jpg)|(.jpeg)|(.png)|(.gif))$/', $url))
                $forbidenExtensions = true;
        }

        if ($forbidenExtensions)
        {
            $context->buildViolation("L'un des fichiers semble ne pas être une image. Seuls les extensions jpg, jpeg, png et gif sont acceptés.")
                    ->atPath("illustrations")
                    ->addViolation();
        }
    }

This, like in the previous case when I only used Valid (not within All constraint) doesn't do anything. Just like if nothing is checked.

Adding

dump($this->illustrations);
die();

at the beginning of my callback give me a result : an empty arraycollection. And of course, I send some files.

So, The callback is executed, but without illustrations.

This make me wonder if the callback is executed directly when I try to submit the form (so the empty illustrations is normal : there's no illustrations before the controller create it)

For informations, this is my method that handle form submission in my controller :

    /**
     * @Route("/adding-trick", name="adding_trick")
     * @IsGranted("ROLE_USER")
     */
    public function addingTrick(Request $request, ObjectManager $manager)
    {
        $trick = new Trick();

        $form = $this->createForm(TrickType::class, $trick);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $trick->setEditeur($this->getUser());

            $illustrations = $form['illustrations']->getData();

            if($illustrations)
            {
                foreach ($illustrations as $illustrationFile) {
                    $folder = "illustrations";
                    $extension = $illustrationFile->guessExtension();
                    if(!$extension)
                        $extension = "bin";
                    $illustrationName = rand(1, 999999999);

                    $illustrationFile->move($folder, $illustrationName . "." . $extension);

                    $illustration = new Illustration();

                    $illustration->setUrl("/" . $folder . "/" . $illustrationName . "." . $extension)
                                 ->setAlt("une illustration de la figure " . $trick->getNom())
                                 ->setTrick($trick);

                    $manager->persist($illustration);

                    $figure->addIllustration($illustration);
                }
            }

            // some code for other fields

            $manager->persist($figure);
            $manager->flush();

            $this->addFlash("success", "Figure ajoutée avec succès");

            return $this->redirectToRoute("trick_display", [
                "slug" => $trick->getSlug()
            ]);
        }

        return $this->render('handlingTricks/addingTrick.html.twig', [
            "form" => $form->createView()
        ]);
    }

if somebody has a clue about what I got to do ?

Thank you !

Symfony 4 make:entity --regenerate fail with: No entities were found in the "App" namespace

$
0
0

from composer.json

{
    "name": "symfony/website-skeleton",
    "type": "project",
    "license": "MIT",
    "description": "A skeleton to start a new Symfony website",
    "require": {
        "php": "^7.1.3",
        "ext-iconv": "*",
        "sensio/framework-extra-bundle": "^5.1",
        "symfony/apache-pack": "^1.0",
        "symfony/asset": "^4.0",
        "symfony/console": "^4.0",
        "symfony/expression-language": "^4.0",
        "symfony/flex": "^1.0",
        "symfony/form": "^4.0",
        "symfony/framework-bundle": "^4.0",
        "symfony/lts": "^4@dev",
        "symfony/monolog-bundle": "^3.1",
        "symfony/orm-pack": "^1.0",
        "symfony/process": "^4.0",
        "symfony/security-bundle": "^4.0",
        "symfony/serializer-pack": "*",
        "symfony/swiftmailer-bundle": "^3.1",
        "symfony/translation": "^4.0",
        "symfony/twig-bundle": "^4.0",
        "symfony/validator": "^4.0",
        "symfony/web-link": "^4.0",
        "symfony/webpack-encore-pack": "*",
        "symfony/yaml": "^4.0"
    },
    "require-dev": {
        "symfony/browser-kit": "^4.0",
        "symfony/css-selector": "^4.0",
        "symfony/debug-pack": "*",
        "symfony/dotenv": "^4.0",
        "symfony/maker-bundle": "^1.5",
        "symfony/phpunit-bridge": "^4.0",
        "symfony/profiler-pack": "*",
        "symfony/web-server-bundle": "^4.0"
    },
    "config": {
        "preferred-install": {
            "*": "dist"
        },
        "sort-packages": true
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "tests/"
        }
    },
    "replace": {
        "symfony/polyfill-iconv": "*",
        "symfony/polyfill-php71": "*",
        "symfony/polyfill-php70": "*",
        "symfony/polyfill-php56": "*"
    },
    "scripts": {
        "auto-scripts": {
            "cache:clear": "symfony-cmd",
            "assets:install --symlink --relative %PUBLIC_DIR%": "symfony-cmd"
        },
        "post-install-cmd": [
            "@auto-scripts"
        ],
        "post-update-cmd": [
            "@auto-scripts"
        ]
    },
    "conflict": {
        "symfony/symfony": "*"
    },
    "extra": {
        "symfony": {
            "allow-contrib": false
        }
    }
}

from doctrine.yaml:

# /config/packages/doctrine.yaml
doctrine:
    dbal:
        default_connection: training
        connections:
            training:
                dbname:   "training"
                driver:   "pdo_mysql"
                host:     "localhost"
                port:     "3306"
                user:     "userdb"
                password: "XXXXXXXXXX"
                charset:  UTF8
                mapping_types:
                    bit: boolean
    orm:
        auto_generate_proxy_classes: "%kernel.debug%"
        default_entity_manager: training
        entity_managers:
            training:
                connection: training
                auto_mapping: true

the command:

php bin/console doctrine:mapping:import --em=training App\Entity annotation --path=src/Entity

produce into src/Entity the Course.php entity:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Course
 *
 * @ORM\Table(name="course", indexes={@ORM\Index(name="id_product_idx_1", columns={"id_product"}), @ORM\Index(name="enabled_idx_1", columns={"enabled"}), @ORM\Index(name="sort_idx_1", columns={"sort"})})
 * @ORM\Entity
 */
class Course
{
    ....

after run into the console:

php bin/console make:entity --regenerate App

this fail with error:

No entities were found in the "App" namespace

same for

php bin/console make:entity --regenerate App\Entity 

if i try

php bin/console make:entity --regenerate App\Entity\Course

the output is

Could not find Doctrine metadata for "App\Entity\Course". Is it mapped as an entity?

what i'm doing wrong?


Attempted to load class "WebProfilerBundle" from namespace "Symfony\Bundle\WebProfilerBundle" when deploying on Heroku using development dependencies

$
0
0

We have a Symfony 4.3 web application hosted on Heroku. This is a new setup and we never managed to have the dev mode to work correctly. There are plenty of similar issues online but none fixes the exact symptoms we are facing here.

The project was created with a command line:

composer create-project symfony/website-skeleton appName

Let me clarify that: we do not want to change from"dev"to"prod"

We need to be able to use the application in dev mode in order to take advantage of error debugging for PHP as per the article "How to Customize Error Pages" for Symfony 4.3 here

$ php bin/console about
 -------------------- ----------------------------------------------------
  Symfony
 -------------------- ----------------------------------------------------
  Version              4.3.5
  End of maintenance   01/2020
  End of life          07/2020
 -------------------- ----------------------------------------------------
  Kernel
 -------------------- ----------------------------------------------------
  Type                 App\Kernel
  Environment          dev
  Debug                true
  Charset              UTF-8
  Cache directory      ./var/cache/dev (12.1 MiB)
  Log directory        ./var/log (13 KiB)
 -------------------- ----------------------------------------------------
  PHP
 -------------------- ----------------------------------------------------
  Version              7.3.10
  Architecture         64 bits
  Intl locale          n/a
  Timezone             Europe/Berlin (2019-10-28T15:48:05+01:00)
  OPcache              false
  APCu                 false
  Xdebug               false
 -------------------- ----------------------------------------------------
  Environment (.env)
 -------------------- ----------------------------------------------------
  APP_ENV              dev
 *just a few removed before posting for privacy*
 -------------------- ----------------------------------------------------

If we change from 'dev' to 'prod' environment the application works but we cannot see the errors the way we wish to. We could use the command below (but this is not the point we are trying to solve here) in order to use "Symfony Var Dumper Server". We do not want to use this method.

./bin/console server:dump

It seems that we might be missing a dependency but composer update and composer install and composer dump-autoload did not solve anything.

Also note the message "Did you forget a "use" statement for another namespace? in /tmp/build_a45354eb0ee7b20dd7ec870ed4fb1980/src/Kernel.php:23" - Is it possible that the WebProfilerBundle is broken in the master repository?

To further help understand the situation, below is the composer.json file

{
    "type": "project",
    "license": "proprietary",
    "require": {
        "php": "^7.1.3",
        "ext-ctype": "*",
        "ext-iconv": "*",
        "phpmailer/phpmailer": "^6.1",
        "sensio/framework-extra-bundle": "^5.5",
        "symfony/asset": "4.3.*",
        "symfony/console": "4.3.*",
        "symfony/dotenv": "4.3.*",
        "symfony/expression-language": "4.3.*",
        "symfony/flex": "^1.3.1",
        "symfony/form": "4.3.*",
        "symfony/framework-bundle": "4.3.*",
        "symfony/http-client": "4.3.*",
        "symfony/intl": "4.3.*",
        "symfony/mailer": "4.3.*",
        "symfony/monolog-bundle": "^3.1",
        "symfony/orm-pack": "^1.0",
        "symfony/process": "4.3.*",
        "symfony/security-bundle": "4.3.*",
        "symfony/serializer-pack": "*",
        "symfony/swiftmailer-bundle": "^3.1",
        "symfony/translation": "4.3.*",
        "symfony/twig-bundle": "4.3.*",
        "symfony/twig-pack": "^1.0",
        "symfony/validator": "4.3.*",
        "symfony/web-link": "4.3.*",
        "symfony/webpack-encore-bundle": "^1.7",
        "symfony/yaml": "4.3.*"
    },
    "require-dev": {
        "symfony/debug-bundle": "4.3.*",
        "symfony/debug-pack": "*",
        "symfony/maker-bundle": "^1.14",
        "symfony/profiler-pack": "^1.0",
        "symfony/test-pack": "*",
        "symfony/web-profiler-bundle": "4.3.*",
        "symfony/web-server-bundle": "4.3.*"
    },
    "config": {
        "preferred-install": {
            "*": "dist"
        },
        "sort-packages": true
    },
    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "App\\Tests\\": "tests/"
        }
    },
    "replace": {
        "paragonie/random_compat": "2.*",
        "symfony/polyfill-ctype": "*",
        "symfony/polyfill-iconv": "*",
        "symfony/polyfill-php71": "*",
        "symfony/polyfill-php70": "*",
        "symfony/polyfill-php56": "*"
    },
    "scripts": {
        "auto-scripts": {
            "cache:clear": "symfony-cmd",
            "assets:install %PUBLIC_DIR%": "symfony-cmd"
        },
        "post-install-cmd": [
            "@auto-scripts"
        ],
        "post-update-cmd": [
            "@auto-scripts"
        ]
    },
    "conflict": {
        "symfony/symfony": "*"
    },
    "extra": {
        "symfony": {
            "allow-contrib": false,
            "require": "4.3.*"
        }
    }
}

Our obstacle: trying to deploy to heroku using dev mode.

git push heroku master

which fails with the following message:

remote:        Executing script cache:clear [KO]
remote:         [KO]
remote:        Script cache:clear returned with error code 255
remote:        !!  PHP Fatal error:  Uncaught Symfony\Component\Debug\Exception\ClassNotFoundException: Attempted to load class "WebProfilerBundle" from namespace "Symfony\Bundle\WebProfilerBundle".
remote:        !!  Did you forget a "use" statement for another namespace? in /tmp/build_a45354eb0ee7b20dd7ec870ed4fb1980/src/Kernel.php:23
remote:        !!  Stack trace:
remote:        !!  #0 /tmp/build_a45354eb0ee7b20dd7ec870ed4fb1980/vendor/symfony/http-kernel/Kernel.php(429): App\Kernel->registerBundles()
remote:        !!  #1 /tmp/build_a45354eb0ee7b20dd7ec870ed4fb1980/vendor/symfony/http-kernel/Kernel.php(130): Symfony\Component\HttpKernel\Kernel->initializeBundles()
remote:        !!  #2 /tmp/build_a45354eb0ee7b20dd7ec870ed4fb1980/vendor/symfony/framework-bundle/Console/Application.php(159): Symfony\Component\HttpKernel\Kernel->boot()
remote:        !!  #3 /tmp/build_a45354eb0ee7b20dd7ec870ed4fb1980/vendor/symfony/framework-bundle/Console/Application.php(65): Symfony\Bundle\FrameworkBundle\Console\Application->registerCommands()
remote:        !!  #4 /tmp/build_a45354eb0ee7b20dd7ec870ed4fb1980/vendor/symfony/console/Application.php(149): Symfony\Bundle\FrameworkBundle\Cons in /tmp/build_a45354eb0ee7b20dd7ec870ed4fb1980/src/Kernel.php
on line 23
remote:        !!
remote:        Script @auto-scripts was called via post-install-cmd
remote:  !     WARNING: There was a class not found error in your code
remote:
remote:  !     ERROR: Dependency installation failed!
remote:  !
remote:  !     The 'composer install' process failed with an error. The cause
remote:  !     may be the download or installation of packages, or a pre- or
remote:  !     post-install hook (e.g. a 'post-install-cmd' item in 'scripts')
remote:  !     in your 'composer.json'.
remote:  !
remote:  !     Typical error cases are out-of-date or missing parts of code,
remote:  !     timeouts when making external connections, or memory limits.
remote:  !
remote:  !     Check the above error output closely to determine the cause of
remote:  !     the problem, ensure the code you're pushing is functioning
remote:  !     properly, and that all local changes are committed correctly.
remote:  !
remote:  !     For more information on builds for PHP on Heroku, refer to
remote:  !     https://devcenter.heroku.com/articles/php-support
remote:  !
remote:  !     REMINDER: the following warnings were emitted during the build;
remote:  !     check the details above, as they may be related to this error:
remote:  !     - There was a class not found error in your code
remote:
remote:  !     Push rejected, failed to compile PHP app.
remote:
remote:  !     Push failed

We currently do not know how to install or verify that bundles are indeed present and operational for Symfony 4.3 - ideas in this direction might help but not only.

php bin/console config:dump-reference

Available registered bundles with their extension alias if available
====================================================================

 ---------------------------- ------------------------
  Bundle name                  Extension alias
 ---------------------------- ------------------------
  DebugBundle                  debug
  DoctrineBundle               doctrine
  DoctrineCacheBundle          doctrine_cache
  DoctrineMigrationsBundle     doctrine_migrations
  FrameworkBundle              framework
  MakerBundle                  maker
  MonologBundle                monolog
  SecurityBundle               security
  SensioFrameworkExtraBundle   sensio_framework_extra
  SwiftmailerBundle            swiftmailer
  TwigBundle                   twig
  TwigExtraBundle              twig_extra
  WebProfilerBundle            web_profiler
  WebServerBundle              web_server
  WebpackEncoreBundle          webpack_encore
 ---------------------------- ------------------------

 // Provide the name of a bundle as the first argument of this command to dump its default configuration. (e.g.
 // config:dump-reference FrameworkBundle)
 //
 // For dumping a specific option, add its path as the second argument of this command. (e.g.
 // config:dump-reference FrameworkBundle profiler.matcher to dump the
 // framework.profiler.matcher configuration)

Symfony Mailer TLS Certificate Name Validation Error

$
0
0

How can I turn off name validations in symfony/mailer TLS connections. I am getting the following error.

Warning: stream_socket_enable_crypto(): Peer certificate CN=smtp.somename.com' did not match expected CN=smtp.someothername.com'

In swift mailer I can simply set verify_peer_name to false. How do you do it with the new symfony/mailer?

Symfony 4 - How to run Doctrine migrations before test?

$
0
0

I know that there are a lot of similar questions (Codeception & Symfony - run Doctrine migrations before tests) but do I really need to run migrations in tests like exec(...) or there is a better way for doing that?

Another thing: when I try to run migrations for sqlite db i get an error message: Migration can only be executed safely on mysql

Symfony 4 Bundle: AuthenticationUtils but no such service exists

$
0
0

I'm trying to make a Bundle (Symfony 4) for managing users of all our projects and I'm having a problem.

Cannot autowire argument $authenticationUtils of "App\Aroban\Bundle\UtilisateurBundle\Controller\SecurityController::login()": it references class "Symfony\Component\Security\Http\Authentication\AuthenticationUtils" but no such service exists.

I do not understand why the service is not injected...

In the composer.json of the project, there is "symfony/security-bundle": "4.3.*"

In the Bundle:

SecurityController.php

<?php

namespace App\Aroban\Bundle\UtilisateurBundle\Controller;

use App\Aroban\Bundle\UtilisateurBundle\Entity\Utilisateur;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
use Swift_Mailer;

class SecurityController extends AbstractController
{
    public function login(AuthenticationUtils $authenticationUtils): Response
    {
        $error = $authenticationUtils->getLastAuthenticationError();
        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render('@Utilisateur/security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);
    }

.......
}

Configuration.php

<?php

namespace App\Aroban\Bundle\UtilisateurBundle\DependencyInjection;

use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder('utilisateur');
        $rootNode = $treeBuilder->getRootNode();

        return $treeBuilder;
    }
}

UtilisateurExtension.php

<?php

namespace App\Aroban\Bundle\UtilisateurBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Loader;

class UtilisateurExtension extends Extension
{
    /**
     * {@inheritdoc}
     */
    public function load(array $configs, ContainerBuilder $container): void
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
        $loader->load('services.yaml');
    }
}

services.yaml (bundle)

services:
  _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

  App\Aroban\Bundle\UtilisateurBundle\:
    resource: '../../*'
    exclude: '../../{Entity,Migrations,Tests,Kernel.php}'

  App\Aroban\Bundle\UtilisateurBundle\Controller\:
    resource: '../../Controller/*'
    tags: ['controller.service_arguments']

When I execute the command

php bin/console debug:container | grep security

I do not see the service ...

Symfony\Component\Security\Csrf\CsrfTokenManagerInterface alias for "security.csrf.token_manager"
Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface alias for "security.csrf.token_generator"
Symfony\Component\Security\Csrf\TokenStorage\TokenStorageInterface alias for "security.csrf.token_storage"
doctrine.orm.security.user.provider Symfony\Bridge\Doctrine\Security\User\EntityUserProvider
maker.security_config_updater Symfony\Bundle\MakerBundle\Security\SecurityConfigUpdater
security.csrf.token_generator Symfony\Component\Security\Csrf\TokenGenerator\UriSafeTokenGenerator
security.csrf.token_manager Symfony\Component\Security\Csrf\CsrfTokenManager
security.csrf.token_storage Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage
twig.extension.security_csrf Symfony\Bridge\Twig\Extension\CsrfExtension
twig.runtime.security_csrf Symfony\Bridge\Twig\Extension\CsrfRuntime
// To search for a specific service, re-run this command with a search term. (e.g. debug:container
// log)

Thanks for your help!

Using an environment variable (from `.env` file) in custom Twig function in Symfony 4

$
0
0

How can I use an environment variable from the .env file in a custom Twig function (\Twig_SimpleFunction) in Symfony 4?

How to bypass error "Invalid type "json_array""

$
0
0

I have an entity:

<?php

namespace App\Entity\Aero;

use Doctrine\ORM\Mapping as ORM;

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

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

    /**
     * @ORM\Column(type="json")
     */
    private $timeOfFlightAndStations = [];

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

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

    public function setDateOfFlight(\DateTimeInterface $dateOfFlight): self
    {
        $this->dateOfFlight = $dateOfFlight;

        return $this;
    }

    public function getTimeOfFlightAndStations(): ?array
    {
        return $this->timeOfFlightAndStations;
    }

    public function setTimeOfFlightAndStations(array $timeOfFlightAndStations): self
    {
        $this->timeOfFlightAndStations = $timeOfFlightAndStations;

        return $this;
    }
}

When I try to add field with type json_array via con make:entity it shows me error:

[ERROR] Invalid type "json_array".

My computer says that type "json_array" is invalid, but also says that it is in the list of valid types. How is it possible?

Please, help me, how to deal with this error? Sorry, can't add more code on entity because of restrictions.

Symfony 4 Twig Custom Form Field Template For Collection Of Checkboxes

$
0
0

I've used a custom template no problem when using a collection of checkboxes to change the html to be in a table like this:

{% form_theme form _self %}

{% block _packing_dispatch_form_group_formsA_0_packagingList_widget %}
    <div {{ block('widget_container_attributes') }}>
        <div class="table-responsive">
            <table>
                {%- for child in form %}
                    <tr>
                        <td class="firstCol">{{- form_label(child, null, {translation_domain: choice_translation_domain}) -}}</td>
                        <td>{{- form_widget(child) -}}</td>
                    </tr>
                {% endfor -%}
            </table>
        </div>
    </div>
{% endblock %}

But now the collection has changed so it holds a collection of another form type which then holds the checkboxes, i can't figure out how i now apply the same template to the new collection of the second form type.

Here is the code:

PackagingDispatchFormGroupType.php

$data= [];
            $packingForm = new PackingDispatchForm();
            $data[] = $packingForm;

            $builder->add('formsA', CollectionType::class,[
               'entry_type'=>PackingDispatchFormType::class,
                'entry_options'=>[
                    'user'=>$this->user
                ],
                'allow_add'=>true,
                'allow_delete'=>true,
                'data'=>$data,
                'mapped'=>false
            ]);

PackagingDispatchFormType.php

->add('packagingList',ChoiceType::class,[
                'multiple'=>true,
                'expanded'=>true,
                'attr'=>[
                    'class'=>'packagingListInput'
                ],
                'choices'=>[
                    'Digitherm Camera, CDX8950-400' => 'Digitherm Camera, CDX8950-400',
                    'Battery, CDX370PACK' => 'Battery, CDX370PACK',
                    'Battery Tab, CDX8950-514' => 'Battery Tab, CDX8950-514',
                    'Memory Card, CDX8IS' => 'Memory Card, CDX8IS',
                    'Memory Card Reader, CDXUSBR' => 'Memory Card Reader, CDXUSBR',
                    'Charging Station, CDX370D' => 'Charging Station, CDX370D',
                    'Power Supply (3x Adapters), CDX370C' => 'Power Supply (3x Adapters), CDX370C',
                    'Australian Adapter' => 'Australian Adapter',
                    'Access Key, XP-100' => 'Access Key, XP-100',
                    'Wrist Strap, CDX8950-550' => 'Wrist Strap, CDX8950-550',
                    'Fragrance Card, CDX8950-512' => 'Fragrance Card, CDX8950-512',
                    'Accessory Card' => 'Accessory Card',
                    'Instructions For Safe User, CDX8950-511 Rev. A' => 'Instructions For Safe User, CDX8950-511 Rev. A',
                    'User Manual, CDX8950-507, Rev. A' => 'User Manual, CDX8950-507, Rev. A',
                    'Battery Warning Card' => 'Battery Warning Card',
                    'Charger Instruction Leaflet' => 'Charger Instruction Leaflet',
                    'Declaration Of Conformity, SOM15, Rev. A' => 'Declaration Of Conformity, SOM15, Rev. A'
                ],
                'disabled'=>($this->forView ? true : false),
                'choice_attr'=>function($choice, $key, $value){
                    return ['required'=>true];
                },
                'invalid_message'=>'All Of The Packaging List Checkboxes Are Required'
            ]);

The whole point here is that i can now duplicate the form field as an array of the checkboxes, but can't seem to apply the same html template.


CSRF token is always invalid on localhost - Symfony 4 forms

$
0
0

My form can never validate on localhost unless I deactivate my csrf field on localhost.

It works perfectly fine on prod.

I was thinking it could come from my config:

router.request_context.host: 'localhost:8000'
router.request_context.scheme: 'http'

But despite my numerous tries, I can't figure out where it's coming from.

My userType.php is fairly basic:

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // Remember username is email
        $builder
            ->add('firstName', TextType::class, array(
                'required' => true,
            ))
            ->add('lastName', TextType::class, array(
                'required' => true,
            ))
            ->add('email', EmailType::class, array(
                'required' => true,
            ))
            ->add('plainPassword', PasswordType::class, array(
                'required' => true,
            ))
            ->add('save', SubmitType::class, array('label' => 'Create Account'))
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => User::class,
            // enable/disable CSRF protection for this form
            'csrf_protection' => false,
            // the name of the hidden HTML field that stores the token
            'csrf_field_name' => '_token',
            // an arbitrary string used to generate the value of the token
            // using a different string for each form improves its security
            'csrf_token_id'   => 'user_item'
        ));
    }
}

And my form in twig is very straighforward:

{{ form_start(form, {'attr': {'id': 'register'}}) }}
    <div class="panel panel-body registration-form">
        <div class="text-center">
            <img style="margin: 20px auto;" src="{{ asset('platform/images/icon-profile.svg') }}"/>
            <h5 class="content-group-lg">ACCOUNT CREATION</h5>
        </div>

        {% for message in app.flashes('error') %}
            <p class="alert alert-danger no-border"><strong>{{ message }}</strong></p>
        {% endfor %}

        <div class="row">
            <div class="col-md-12">
                <div class="form-group has-feedback">
                    {{ form_widget(form.email, {'attr': {'class': '', 'placeholder': "Your Email"}}) }}
                    {#<div class="form-control-feedback">#}
                    {#<i class="icon-mention text-muted"></i>#}
                    {#</div>#}
                    <small class="text-danger">{{ form_errors(form.email) }}</small>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-6">
                <div class="form-group has-feedback">
                    {{ form_widget(form.firstName, {'attr': {'class': '', 'placeholder': "Your Fist Name"}}) }}
                    {#<div class="form-control-feedback">#}
                    {#<i class="icon-user-check text-muted"></i>#}
                    {#</div>#}
                    <small class="text-danger">{{ form_errors(form.firstName) }}</small>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group has-feedback">
                    {{ form_widget(form.lastName, {'attr': {'class': '', 'placeholder': "Your Last Name"}}) }}
                    {#<div class="form-control-feedback">#}
                    {#<i class="icon-user-check text-muted"></i>#}
                    {#</div>#}
                    <small class="text-danger">{{ form_errors(form.lastName) }}</small>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-md-12">
                <div class="form-group has-feedback">
                    {{ form_widget(form.plainPassword, {'attr': {'class': '', 'placeholder': "Create Password"}}) }}
                    {#<div class="form-control-feedback">#}
                    {#<i class="icon-user-lock text-muted"></i>#}
                    {#</div>#}
                    <small class="text-danger">{{ form_errors(form.plainPassword) }}</small>
                </div>
            </div>
        </div>

        <div class="form-group help-block">
            <div class="checkbox">
                By clicking on "Create Account" you accept our
                <a href="{{ path('terms') }}">terms of service</a>
            </div>
        </div>

        <div class="text-right">
            {{ form_widget(form.save, {'attr': {'class': 'btn btn-block new-btn new-blue'}} ) }}
{#            <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response"/>#}
            {#<button name="form[save]" type="submit" class="btn bg-teal-400 btn-labeled btn-labeled-right ml-10"><b><i class="icon-plus3"></i></b> Create account</button>#}
        </div>
    </div>
    {{ form_end(form) }}

Since I'm using form_start and form_end my csrf token field is generated with the correct name. I also tried with including the input manually:

Any help is appreciated.

Thank you.

when I try to write a dql query there is an error for lag & over ( beberlei/DoctrineExtensions )

$
0
0

I'm trying to convert a MySQL8 query to Doctrine DQL in Symfony4. I used to https://github.com/beberlei/DoctrineExtensions extensions. But there are still errors.

Query is work well.

SELECT id, machine_amount, LAG(machine_amount) OVER ( PARTITION BY machine_id ORDER BY id ) AS prevField FROM machine_income 

repositoryClass

$q = $this->createQueryBuilder('mi');

$q->select('mi.id, mi.machineAmount');
$q->addSelect('LAG(mi.machineAmount) OVER (PARTITION BY mi.machine ORDER BY mi.id) AS prevField');

return $q->getQuery()->getSQL(); 

doctrine.yaml

doctrine:
    orm:
        dql:
            string_functions:
                lag: DoctrineExtensions\Query\Mysql\Lag
                over: DoctrineExtensions\Query\Mysql\Over

DQL out

SELECT mi.id, mi.machineAmount, LAG(mi.machineAmount) OVER (PARTITION BY mi.machine ORDER BY mi.id) AS prevField FROM App\Entity\MachineIncome mi

When I try to create getSQL() I saw error.

error

[Syntax Error] line 0, col 59: Error: Expected Doctrine\ORM\Query\Lexer::T_FROM, got '('

any help?

How to pass an array to a function with class dependency? [closed]

$
0
0

Before I was using $allMovies = $this->findAll(); to retrieve object data.

array:2908 [
  0 => App\Entity\Movie {#450
    -id: 39
    -title: "ozcMpVxIWJ"
    -count: "0"
  }
  1 => App\Entity\Movie {#453
    -id: 115
    -title: "sfFcUlnEiV"
    -count: "0"
  }

Now I am trying createQueryBuilder() to get array data something like this after my query.

array:10 [
    0 => array:3 [
      "id" => 39
      "title" => "ozcMpVxIWJ""count" => "10"
    ]
    1 => array:3 [
      "id" => 115
      "title" => "sfFcUlnEiV""count" => "10"
    ]
    2 => array:3 [
      "id" => 215
      "title" => "dVrinJNPpC""count" => "10"
    ]

From this data, I need to add some more logic.

With my previous code, everything was running fine. But once I change to createQueryBuilder I am getting problem. Inside the loop, I have called a function with dependency injection of Entity Movie itself.

$moviesArray = array();

foreach ($movies as $movie) {
    $movie = $this->transform($movie);
    .....

}

public function transform(Movie $movie)
{
    return array(
        'id'    => (int) $movie->getId(),
        'title' => (string) $movie->getTitle(),
        'count' => (int) $movie->getCount()
    );
}

Since my data is array, how can I pass to this function and get the same output?

Symfony 4 + Swift Mailer [closed]

$
0
0

I'd like to use the bundle Swift Mailer to send templated mails, but all documentations I find (including https://symfony.com/doc/4.3/email.html) doesn't seem to work...

My .env file is configured this way:

MAILER_URL=smtp://localhost:25?encryption=&auth_mode=

I've tried several ways to use the service:

public function __construct(\Swift_Mailer $mailer)
{
    $this->mailer = $mailer;
}

And I have the same error each time:

$mailing = new Mailing();

Too few arguments to function App\Service\Mailing::__construct(), 
0 passed in /[...]/ReportController.php on line 128 and exactly 1 expected

Any idea of what may be missing?

Symfony login doing nothing [closed]

$
0
0

I ran in strange problem with Symfony 4.4. I'm using default login and registration system from Symfony 4.4 documentation. It is working fine locally, but when I upload it to other server - login does nothing. It is simply reloading page. Other pages of same website working fine, Database record created and readed correctly. Issue is only with Login. Seems that session is not created, but there is no errors, and page is simply reloaded. Any ideas?

Security.yaml:

security:
encoders:
    App\Entity\User:
        algorithm: argon2i

# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
    # used to reload user from session & other features (e.g. switch_user)
    app_user_provider:
        entity:
            class: App\Entity\User
            property: email
firewalls:
    dev:
        pattern: ^/(_(profiler|wdt)|css|images|js)/
        security: false
    main:
        anonymous: true
        guard:
            authenticators:
                - App\Security\LoginFormAuthenticator
            entry_point: App\Security\LoginFormAuthenticator
        logout:
            path:   app_logout

        # activate different ways to authenticate
        # https://symfony.com/doc/current/security.html#firewalls-authentication

        # https://symfony.com/doc/current/security/impersonating_user.html
        # switch_user: true
role_hierarchy:
    ROLE_ADMIN:       ROLE_USER
# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
    # - { path: ^/admin, roles: ROLE_ADMIN }
    # - { path: ^/profile, roles: ROLE_USER }
Viewing all 3924 articles
Browse latest View live


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