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

Is there a known bug for bernard.receiver when used with symfony 4?

$
0
0

I tried using bernard-bundle in my Symfony 4.3 project to run a basic helloWorld background task, but when I try to run bernard: consume I get an error

In SimpleRouter.php line 38:

Given "my_receiver" is not supported. 

This is the services.yaml part

 my_receiver:
        class: App\BackgroundTasks\Receiver\
        tags:
            - { name: bernard.receiver, message: 'HelloWorld' }

It says the error is in SimpleRouter, so I tried debugging there using

    var_dump($name);
    var_dump($receiver);
    var_dump(class_exists($receiver)); 

and I got

    string(10) "HelloWorld"
    string(11) "my_receiver"
    bool(false)

Is this a bug because of Symfony? Or am I missing something?


Symfony4 MongoDB inject repository

$
0
0

I try to injcect doctrine mongo repository to controller. In services.yaml file I added entry:

    App\Account\Repository\MongoAccountRepository:
    factory: ["@doctrine_mongodb", getRepository]
    arguments:
      - App\Account\Domain\Entity\Account

In my code I want to use repositories hidden behind the interface AccountRepository

class MongoAccountRepository extends DocumentRepository implements AccountRepository {}

When I try to inject repository to controller constructor

class DefaultController extends Controller 
{
     private $accountRepository;

     public function __construct(AccountRepository $accountRepository) {
           $this->accountRepository = $accountRepository;
     }

I get following error:

Argument 1 passed to App\Account\UserInterface\DefaultController::__construct() must implement interface App\Account\Domain\Repository\AccountRepository, instance of Doctrine\ODM\MongoDB\DocumentRepository given

Has someone similar problem?

Using pre-set data and changing the value

$
0
0

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

Entity supplier:

<?php

namespace App\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Doctrine\ORM\Mapping as ORM;

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

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

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

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

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     *
     * @var string
     */
    private $company;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     *
     * @var string
     */
    private $named;

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

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     *
     * @var string
     */
    private $building;

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

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     *
     * @var string
     */
    private $other;

    /**
     * @ORM\Column(type="integer", length=5)
     *
     * @var integer
     */
    private $zipcode;

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

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

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     *
     * @var string
     */
    private $url;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     *
     * @var string
     */
    private $login;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     *
     * @var string
     */
    private $passwordSite;

    /**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     *
     * @Vich\UploadableField(mapping="fournisseur_image", fileNameProperty="imageName", size="imageSize")
     *
     * @var File
     */
    private $imageFile;

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

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

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

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

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

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

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

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

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

    /**
     * @ORM\OneToMany(targetEntity="Reference", mappedBy="fournisseur")
     */
    private $references;

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

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

    /**
     * @return string
     */
    public function getCategory(): ?string
    {
        return $this->category;
    }

    /**
     * @param string $category
     */
    public function setCategory(string $category): void
    {
        $this->category = $category;
    }

    /**
     * @return string
     */
    public function getCivility(): ?string
    {
        return $this->civility;
    }

    /**
     * @param string $civility
     */
    public function setCivility(string $civility): void
    {
        $this->civility = $civility;
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param mixed $name
     */
    public function setName($name): void
    {
        $this->name = $name;
    }

    /**
     * @return string
     */
    public function getCompany(): ?string
    {
        return $this->company;
    }

    /**
     * @param string $company
     */
    public function setCompany(string $company): void
    {
        $this->company = $company;
    }

    /**
     * @return string
     */
    public function getNamed(): ?string
    {
        return $this->named;
    }

    /**
     * @param string $named
     */
    public function setNamed(string $named): void
    {
        $this->named = $named;
    }

    /**
     * @return string
     */
    public function getSurname(): ?string
    {
        return $this->surname;
    }

    /**
     * @param string $surname
     */
    public function setSurname(string $surname): void
    {
        $this->surname = $surname;
    }

    /**
     * @return string
     */
    public function getBuilding(): ?string
    {
        return $this->building;
    }

    /**
     * @param string $building
     */
    public function setBuilding(string $building): void
    {
        $this->building = $building;
    }

    /**
     * @return string
     */
    public function getStreet(): ?string
    {
        return $this->street;
    }

    /**
     * @param string $street
     */
    public function setStreet(string $street): void
    {
        $this->street = $street;
    }

    /**
     * @return string
     */
    public function getOther(): ?string
    {
        return $this->other;
    }

    /**
     * @param string $other
     */
    public function setOther(string $other): void
    {
        $this->other = $other;
    }

    /**
     * @return int
     */
    public function getZipcode(): ?int
    {
        return $this->zipcode;
    }

    /**
     * @param int $zipcode
     */
    public function setZipcode(int $zipcode): void
    {
        $this->zipcode = $zipcode;
    }

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

    /**
     * @param string $city
     */
    public function setCity(string $city): void
    {
        $this->city = $city;
    }

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

    /**
     * @param string $country
     */
    public function setCountry(string $country): void
    {
        $this->country = $country;
    }

    /**
     * @return string
     */
    public function getUrl(): ?string
    {
        return $this->url;
    }

    /**
     * @param string $url
     */
    public function setUrl(string $url): void
    {
        $this->url = $url;
    }

    /**
     * @return string
     */
    public function getLogin(): ?string
    {
        return $this->login;
    }

    /**
     * @param string $login
     */
    public function setLogin(string $login): void
    {
        $this->login = $login;
    }

    /**
     * @return string
     */
    public function getPasswordSite(): ?string
    {
        return $this->passwordSite;
    }

    /**
     * @param string $passwordSite
     */
    public function setPasswordSite(string $passwordSite): void
    {
        $this->passwordSite = $passwordSite;
    }

    /**
     * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $imageFile
     */
    public function setImageFile(?File $imageFile = null): void
    {
        $this->imageFile = $imageFile;
    }

    public function getImageFile(): ?File
    {
        return $this->imageFile;
    }

    public function setImageName(?string $imageName): void
    {
        $this->imageName = $imageName;
    }

    public function getImageName(): ?string
    {
        return $this->imageName;
    }

    public function setImageSize(?int $imageSize): void
    {
        $this->imageSize = $imageSize;
    }

    public function getImageSize(): ?int
    {
        return $this->imageSize;
    }

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

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

        return $this;
    }

    public function getType(): ?string
    {
        return $this->type;
    }

    public function setType(string $type): self
    {
        $this->type = $type;

        return $this;
    }

    public function getPhone1(): ?string
    {
        return $this->phone1;
    }

    public function setPhone1(string $phone1): self
    {
        $this->phone1 = $phone1;

        return $this;
    }

    public function getPhone2(): ?string
    {
        return $this->phone2;
    }

    public function setPhone2(string $phone2): self
    {
        $this->phone2 = $phone2;

        return $this;
    }

    public function getFax(): ?string
    {
        return $this->fax;
    }

    public function setFax(string $fax): self
    {
        $this->fax = $fax;

        return $this;
    }

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

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

        return $this;
    }

    public function getNote(): ?string
    {
        return $this->note;
    }

    public function setNote(string $note): self
    {
        $this->note = $note;

        return $this;
    }
}

Entity article:

<?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\ArticlesRepository")
 */
class Article
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

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

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

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

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

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

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

    /**
     * Many Users have Many Groups.
     * @ORM\ManyToMany(targetEntity="Fournisseur")
     * @ORM\JoinTable(name="articles_fournisseurs",
     *      joinColumns={@ORM\JoinColumn(name="article_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="fournisseur_id", referencedColumnName="id")}
     *      )
     */
    private $fournisseurs;

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

    /**
     * @return mixed
     */
    public function getIdTactill()
    {
        return $this->id_tactill;
    }

    /**
     * @param mixed $id_tactill
     */
    public function setIdTactill($id_tactill): void
    {
        $this->id_tactill = $id_tactill;
    }

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

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

        return $this;
    }

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

    public function setPrice(float $price): self
    {
        $this->price = $price;

        return $this;
    }

    public function getReference(): ?string
    {
        return $this->reference;
    }

    public function setReference(string $reference): self
    {
        $this->reference = $reference;

        return $this;
    }

    public function getInStock(): ?bool
    {
        return $this->in_stock;
    }

    public function setInStock(bool $in_stock): self
    {
        $this->in_stock = $in_stock;

        return $this;
    }

    public function getImage(): ?string
    {
        return $this->image;
    }

    public function setImage(string $image): self
    {
        $this->image = $image;

        return $this;
    }

    public function getTaxes()
    {
        return $this->taxes;
    }

    public function setTaxes($taxes): void
    {
        $this->taxes = $taxes;
    }

    public function getFournisseurs()
    {
        return $this->fournisseurs;
    }

    public function setFournisseurs($fournisseurs): void
    {
        $this->fournisseurs = $fournisseurs;
    }
}

Entity reference:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

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

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

    /**
     * @ORM\OneToOne(targetEntity="Article", cascade={"remove"})
     */
    private $article;

    /**
     * @ORM\ManyToOne(targetEntity="Fournisseur", inversedBy="references")
     * @ORM\JoinColumn(name="fournisseur_id", referencedColumnName="id")
     */
    private $fournisseur;

    public function __toString()
    {
        return $this->refcode;
    }

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

    public function getRefcode(): ?string
    {
        return $this->refcode;
    }

    public function setRefcode(string $refcode): self
    {
        $this->refcode = $refcode;

        return $this;
    }

    public function getArticle()
    {
        return $this->article;
    }

    public function setArticle($article): void
    {
        $this->article = $article;
    }
}

FormType article:

<?php

namespace App\Form;

use App\Entity\Article;
use App\Entity\Fournisseur;
use App\Entity\Reference;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Vich\UploaderBundle\Form\Type\VichImageType;

class ArticlesType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('id_tactill', HiddenType::class)
            ->add('name', TextType::class, [
                'label' => 'Nom'
            ])
            ->add('price', MoneyType::class, [
                'label' => 'Prix'
            ])
            ->add('reference')
            ->add('in_stock', CheckboxType::class, [
                'label' => 'En stock'
            ])
            ->add('image')
            ->add('taxes', HiddenType::class)
            ->add('fournisseurs', EntityType::class, [
                'class' => Fournisseur::class,
                'label' => 'Choisir un fournisseur',
                'required' => false,
                'attr' => ['class' => 'js_fournisseur'],
                'choice_label' => function ($fournisseur) {
                    return $fournisseur->getTitle();
                }
            ])
            ;
    }

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

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

Thank you for your help

How to access not-injected services directly on Symfony 4+?

$
0
0

I'm trying to update Symfony 2.8 to Symfony 4 and I am having serious problems with the Services Injection.

I'm looking the new way to use Services inside Controllers, with auto-wiring:

use App\Service\AuxiliarService;
class DefaultController extends AbstractController
{
    public function index(AuxiliarService $service)
    {
        $var = $service->MyFunction();
        ....

This way works fine, but I dislike the explicit way to refer MyService as a parameter of the function. This way I don't even need to register the Service in the services.yaml

Is any way to use Services as in Symfony 2.8:

class DefaultController extends Controller
    {
        public function index()
        {
            $var = $this->get('AuxiliarService')->MyFunction(); /*Doesn't need to be explicit indicate before*/
            ....

With the services.yaml

services:
    auxiliar_service:
        class:        AppBundle\Services\AuxiliarService
        arguments: 
            entityManager: "@doctrine.orm.entity_manager"
            container: "@service_container" #I need to call services inside the service

This way I don't need to indicate the Service as a parameter in the function of the Controller. In some cases, inside a Service, I need to call more than 10 services depends on the data, so indicate them as a parameter in the function is annoying.

Another doubt in Symfony 4, is how to call a Service inside another Service without pass it as an argument or parameter. It used to be possible by injecting the service container to be able to call a service inside a service:

$this->container->get('anotherService')

In Symfony 4, I think it is more expensive (in code) use Service because you have to explicitely indicate them when you are going to use them.

Symfony monolog fingers crossed handler not excluding specified http codes

$
0
0

I am using the fingers crossed handler to buffer log messages until an error occurs. Below is my config:

monolog:
  handlers:
    buffer:
      action_level: error
      excluded_http_codes: [401, 403, 404]
      handler: logger
      type: fingers_crossed
    logger:
      formatter: monolog.formatter.json
      include_stacktraces: true
      level: info
      path: php://stderr
      type: stream

I am finding that exceptions that should match the excluded_http_codes are still being output into my log.

I have dug into the Symfony\Bridge\Monolog\Handler\FingersCrossed\HttpCodeActivationStrategy class and am finding that $this->requestStack->getMasterRequest() is returning null by the time the exception reaches the isHandlerActivated method.

Is there something I am clearly doing wrong?

Recommended approach Symfony 4 - custom fields

$
0
0

I am trying to fully migrate to Symfony 4, leaving Wordpress behind as much as I'll can.

Right now I can manage the pages, posts and best of all, application logic, given the power of Symfony framework. What I am lacking, though I have an idea, is making something like Advanced Custom Fields WP plugin.

I want to be able to add blocks to a page which could optionally contain repeatable blocks with forms. I am thinking to build this myself, unless there is already a solution that would already cover this for Symfony 4.3 >.

I tried Sonata but is too bloating and I would like to keep my app logic flexible.

How to configure a Symfony workflow

$
0
0

I work on Symfony 4.2 version I made an Workflow Service, who has three places draft, reviewed and published

I add to conf/products/framework.yaml this lines of code. But i don't understand what is currentPlace in the code. I worked by this example https://symfony.com/doc/4.2/workflow.html

workflows:
        article_publishing:
            type: 'workflow'
            audit_trail:
                enabled: true
            marking_store:
                type: 'multiple_state'
                arguments:
                    - 'currentPlace'
            supports:
                - App\Entity\Article
            initial_marking: draft
            places:
                -draft
                -reviewed
                -published
            transitions:
                to_review:
                    from: draft
                    to:   reviewed
                publish:
                    from: reviewed
                    to:   published

But when I refresh the site I get this error

   Warning: array_map(): Argument #2 should be an array

Error

Image upload with sonata admin

$
0
0

I think the issue is pretty simple to solve but I can't find any clear answer right now. I hope you might have an idea.

I'm trying to upload an image with sonata admin.

In my entity I have this field

/**
 * @ORM\Column(type="string", length=2000)
 * @Assert\File(mimeTypes={ "image/png", "image/jpeg" })
 */
private $image;

When I go to the sonata admin form view. The button Upload file is there and defined as below

$formMapper->add('image', FileType::class);

But when I try to send the form, I'm getting this error

The form's view data is expected to be an instance of class Symfony\Component\HttpFoundation\File\File, but is a(n) string. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) string to an instance of Symfony\Component\HttpFoundation\File\File.

I hint this is due to the doctrine string type. But I don't think doctrine has a "File" type.

Thanks for your help.


I have an error when using API platform SWAGGER on Symfony4 project

$
0
0

I made this for GET statement in the controller

<?php


namespace App\Controller\Api;


use App\Entity\Article;
use App\Factory\EntityFactory;
use App\Repository\ArticleRepository;
use Swagger\Annotations as SWG;
use Nelmio\ApiDocBundle\Annotation\Model;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Routing\Annotation\Route;


class ArticlesController
{
    private $repository;
    private $factory;
    private $serializer;

    public function __construct(ArticleRepository $repository, EntityFactory $entityFactory, SerializerInterface $serializer)
    {
        $this->repository = $repository;
        $this->factory = $entityFactory;
        $this->serializer = $serializer;
    }

    /**
     * @Route(path="/articles/{article}", methods={"GET"}, name="article_get")
     *
     * @SWG\Get(
     *     tags={"Articles"},
     *     @SWG\Parameter(
     *        name="article",
     *        in="path",
     *        type="integer",
     *        description="Article ID",
     *     ),
     * )
     * @SWG\Response(
     *     response=200,
     *     description="Article fetched",
     *     @Model(type=Article::class, groups={"article:get", "article:category", "category:index"})
     * )
     */
    public function get(Article $article): JsonResponse
    {
        $data = $this->serializer->serialize($article, 'json', ['groups' => ['article:get', 'article:category', 'category:index']]);

        return new JsonResponse($data, JsonResponse::HTTP_OK, [], true);
    }

}

The entity from the article looks like this:

<?php

namespace App\Entity;

use App\Entity\User\User;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
use Swagger\Annotations as SWG;



/**
 * @ORM\Entity(repositoryClass="App\Repository\ArticleRepository")
 * @ORM\Table(name="articles")
 * @ORM\HasLifecycleCallbacks
 */
class Article implements EntityInterface
{
    /**
     * @var int
     *
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     * @Groups({"article:id", "article:get", "article:index"})
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups({"article:category"})
     *
     */
    private $title;

    /**
     * @ORM\Column(type="string", length=255)
     * @Groups({"article:create", "article:get", "article:index", "article:update"})
     */
    private $lead;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Groups({"article:create", "article:get", "article:index", "article:update"})
     */
    private $slug;

    /**
     * @ORM\Column(type="text", nullable=true)
     * @Groups({"article:create", "article:get", "article:index", "article:update"})
     */
    private $content;

    /**
     * @ORM\Column(type="datetime")
     * @Groups({"article:create", "article:get", "article:index", "article:update"})
     * @SWG\Property(property="updated_at")
     */
    private $publishedAt;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Category", inversedBy="articles")
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id", onDelete="CASCADE", nullable=false)
     * @Groups({"article:category"})
     *
     */
    private $category;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\User\User", inversedBy="articles")
     * @ORM\JoinColumn(nullable=false)
     * @Groups({"article:user"})
     */
    private $author;

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

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

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

    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 getLead(): ?string
    {
        return $this->lead;
    }

    public function setLead(string $lead): self
    {
        $this->lead = $lead;

        return $this;
    }

    public function getSlug(): ?string
    {
        return $this->slug;
    }

    public function setSlug(string $slug): self
    {
        $this->slug = $slug;

        return $this;
    }

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

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

        return $this;
    }

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

    public function setPublishedAt(\DateTimeInterface $publishedAt): self
    {
        $this->publishedAt = $publishedAt;

        return $this;
    }

    public function getCategory(): ?Category
    {
        return $this->category;
    }

    public function setCategory(?Category $category): self
    {
        $this->category = $category;

        return $this;
    }

    public function getAuthor(): ?User
    {
        return $this->author;
    }

    public function setAuthor(?User $author): self
    {
        $this->author = $author;

        return $this;
    }

    public function getArticleFilename(): ?string
    {
        return $this->articleFilename;
    }

    public function setArticleFilename(?string $articleFilename): self
    {
        $this->articleFilename = $articleFilename;

        return $this;
    }
    public function getImagePath()
    {
        return 'images/'.$this->getImageFilename();
    }

    public function getMarking()
    {
        return $this->marking;
    }

    public function setMarking($marking, $context = [])
    {
        $this->marking = $marking;
        $this->transitionContexts[] = [
            'new_marking' => $marking,
            'context' => $context,
            'time' => (new \DateTime())->format('c'),
        ];
    }

    public function getTransitionContexts()
    {
        return $this->transitionContexts;
    }

    public function setTransitionContexts($transitionContexts): self
    {
        $this->transitionContexts = $transitionContexts;
    }
}

And when I go to http://localhost/docs I become this error. That my annotations are not enabled or installed. Thank you for your help.

Error message:

Exception thrown when handling an exception (Symfony\Component\Config\Exception\LoaderLoadException: [Syntax Error] Expected Doctrine\Common\Annotations\DocLexer::T_CLOSE_CURLY_BRACES, got 'article' at position 179 in method App\Controller\Api\ArticlesController::get() in /app/config/routes/../../src/Controller/Api (which is being imported from "/app/config/routes/annotations.yaml"). Make sure annotations are installed and enabled.)

How to redirect to different route than dashboard in Sonata Admin

$
0
0

How can I make my homepage not redirect to the dashboard of Sonata Admin Bundle?

I tried adding a route in my routes.yaml. It shows up in debug:route, but there's another entry for /

  Z:\htdocs\myproject>php bin/console debug:route
 ------------------------------------------ -------- -------- ------ ----------------------------------------------
  Name                                       Method   Scheme   Host   Path
 ------------------------------------------ -------- -------- ------ ----------------------------------------------
  sonata_admin_redirect                      ANY      ANY      ANY    /
  sonata_admin_dashboard                     ANY      ANY      ANY    /dashboard
  sonata_admin_retrieve_form_element         ANY      ANY      ANY    /core/get-form-field-element
  sonata_admin_append_form_element           ANY      ANY      ANY    /core/append-form-field-element
  sonata_admin_short_object_information      ANY      ANY      ANY    /core/get-short-object-description.{_format}
  sonata_admin_set_object_field_value        ANY      ANY      ANY    /core/set-object-field-value
  sonata_admin_search                        ANY      ANY      ANY    /search
  sonata_admin_retrieve_autocomplete_items   ANY      ANY      ANY    /core/get-autocomplete-items
  admin_app_myentity_list                    ANY      ANY      ANY    /app/myentity/list
  admin_app_myentity_create                  ANY      ANY      ANY    /app/myentity/create
  admin_app_myentity_batch                   ANY      ANY      ANY    /app/myentity/batch
  admin_app_myentity_edit                    ANY      ANY      ANY    /app/myentity/{id}/edit
  admin_app_myentity_delete                  ANY      ANY      ANY    /app/myentity/{id}/delete
  admin_app_myentity_show                    ANY      ANY      ANY    /app/myentity/{id}/show
  admin_app_myentity_export                  ANY      ANY      ANY    /app/myentity/export
  statistics_monat                           ANY      ANY      ANY    /app/anotherentity/month/{year}/{month}
  statistics_woche                           ANY      ANY      ANY    /app/anotherentity/week/{year}/{week}
  index                                      ANY      ANY      ANY    /

How can I remove or overwrite the sonata_admin_redirect entry? I want it to redirect to /app/myentity/list.

How to recover all elements of an ArrayCollection?

$
0
0

I would like to retrieve the id of the ArrayCollection to upload multiple photos at the same time. The upload of the image having for id 0, works (normal) but when I want to upload several images I have an error telling me that it could not upload the image having for id 1.

How do we get all the elements of an ArrayCollection?

foreach ($store->getImages() as $image) {
/*                $key = $store->getImages()->getValues();
                dump(array_keys($key));
                die();*/
                $picture = $form['images'][0]['imageName']->getData();
                dump($picture);
                die();
                if ($picture) {
                    $pictureImageFileName = $fileUploader->uploadPicture($picture[0]);
                    $image->setImageName($pictureImageFileName);
                }
//                $image->setStore($store);
                $em->persist($image);
            }
StoreController.php on line 53:
array:2 [▼
  0 => 0
  1 => 1
]

Multiple File Upload in one api call using api-platform

$
0
0

I want to upload multiple images at once in single api call through api-platform endpoint. I have imageTest as my entity, UploadImageAction as my controller and ImageType as my form.

Please let me know how do I handle array for file form-data for multiple upload at once.

imageTest Entity :

<?php


namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use App\Controller\UploadImageAction;

/**
 * @ORM\Entity()
 * @Vich\Uploadable()
 * @ApiResource(
 *     collectionOperations={
 *             "get",
 *              "post" ={
 *                   "method"="POST",
 *                    "path"="/images/products",
 *                    "controller"=UploadImageAction::class,
 *                    "defaults"={"_api_receive"=false}
 *              }
 *     }
 * )
 */

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

    /**
     * @Vich\UploadableField(mapping="products", fileNameProperty="url")
     * @Assert\NotNull()
     */
    private $file;

    /**
     * @ORM\Column(nullable=true)
     */
    private $url;


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

    public function getFile()
    {
        return $this->file;
    }

    public function setFile($file): void
    {
        $this->file = $file;
    }

    public function getUrl()
    {
        return '/images/products/' . $this->url;
    }

    public function setUrl($url): void
    {
        $this->url = $url;
    }

    } 

UploadImageAction :

<?php


namespace App\Controller;


use ApiPlatform\Core\Validator\Exception\ValidationException;
use ApiPlatform\Core\Validator\ValidatorInterface;
use App\Entity\imageTest;
use App\Form\ImageType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\Component\HttpFoundation\Request;

class UploadImageAction
{

    /**
     * @var FormFactoryInterface
     */
    private $formFactory;
    /**
     * @var EntityManagerInterface
     */
    private $entityManager;
    /**
     * @var ValidatorInterface
     */
    private $validator;

    public function __construct(
        FormFactoryInterface $formFactory,
        EntityManagerInterface $entityManager,
        ValidatorInterface $validator
    )
    {

        $this->formFactory = $formFactory;
        $this->entityManager = $entityManager;
        $this->validator = $validator;
    }

    public function __invoke(Request $request)
    {
        // Create a new Image instance

        $image = new imageTest();
        // Validate the form
        $form = $this->formFactory->create(ImageType::class, $image);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()){
            // Persist the new Image entity
            $this->entityManager->persist($image);
            $this->entityManager->flush();

            $image->setFile(null);

            return $image;
        }


        // Uploading done for us in background by VichUploader

        // Throw an validation exception, that means something went wrong during
        // form validation
        throw new ValidationException(
            $this->validator->validate($image)
        );


    }
    } 

ImageType :

<?php
namespace App\Form;
use App\Entity\imageTest;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class ImageType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('file', FileType::class, [
            'label' => 'label.file',
            'required' => false,

        ]);
    }
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => imageTest::class,
            'csrf_protection' => false
        ]);
    }
    public function getBlockPrefix()
    {
        return '';
    }
    } 

How can I know the real path for my monolog logs to read them from a controller? [closed]

$
0
0

I use monolog in my application to get logs on the actions of my users.

useractions:
            type: rotating_file
            path:  "%kernel.logs_dir%/useractions.log"
            level: info
            channels: [useractions]
            max_files:      60

So I get the actions of users in different .log files in /var/log/

I would like to read these logs directly on my application, and present them to users.

Is this possible?

I do not know the real path of the log file so I do not know how I can access it from a controller.

The path: "http://xxx/var/log/useractions.log" gives me :

No route found for "GET /var/log/useractions.log"

But "http://xxx/_profiler/open?file=var\log\useractions.log" works well

Security error message key translations possibilities (to dutch)

$
0
0

I've been looking for all the error message key translations so can translate them all to dutch. The docu explains the following

'Invalid credentials.': 'The password you entered was invalid!'

So how to "translate" invalid credentials. I want to change all the error message to dutch or make own texts. I already change the default langue to nl:

framework:
default_locale: nl
translator:
    default_path: '%kernel.project_dir%/translations'
    fallbacks:
        - en

But where can i find all the possibilites like: Invalid credentials. i googled a lot but cant seem to find it.

Symfony 4, how get the root path directory (or /src path) properly from a Service Class ? ( error : 'Call to a member function get() on null')

$
0
0

In Symfony 4, from a controller I can get the root path of my project via :

// From a Controller Class, in the src/Controller dir

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
// ...
Class myController extends Controller{
// ...
// in a public method
$rootDir = $this->get('kernel')->getRootDir();

But how can I get the root path from a Service Class ? I tried this (ugly) way

// From a Service Class, in the src/Service dir

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
// ...
Class myService extends Controller{
// ...
// in a public method
$rootDir = $this->get('kernel')->getRootDir();

But when I did that, I get the error :

"Call to a member function get() on null"

Why this solution does not work?


Api Platform with Swift Mailer

$
0
0

I would know if API Platform is reliable to Swift Mailer. In fact, I woul use Swift Mailer to send a email when a new task has add. It works good when I use my controller, but not working with Postman or Swagger UI.

//mail sending
       $message = (new \Swift_Message('New task has done !'))
           ->setContentType('text/html')
           ->setFrom("fromAdresse@sample.fr")
           ->setTo('sample@email.com')
           ->setBody(
               $this->renderView('email/new.html.twig',
                    ['work' => $work]));
        $mailer->send($message);

I would use the same thing when users pass by the API UI, it's possible to handle the request ? Because controller and API hasn't the same route.

API : /api/works (POST) to add an element

Controller : work/new (POST) to add an element too

How I can use Swift Mailer on the API platform Request ? Or How I can handle the request with custom controller ?

Thx for advice and answers, I'm beginer with both.

php -S 127.0.0.1:8000 -t public not works

$
0
0

When I run this command: php -S 127.0.0.1:8000 -t public the error is can not open file 127.0.0.1:8000

I'm using symfony 4, when I lunch the server with the command php bin/console server:run it works, but with command php -S 127.0.0.1:8000 -t public it doesn't work.

How to resolve the permission errors for MySQL server?

$
0
0

I am trying to work on this project. https://github.com/thiagogomesverissimo/symfony_traditional_login Following the instructions. But when I was executing

php bin/console doctrine:migrations:migrate

Then I get the following errors:

In AbstractMySQLDriver.php line 112:

An exception occurred in driver: SQLSTATE[HY000] [1045] Access 
denied for user 'master'@'localhost' (using password: YES)                               

In PDOConnection.php line 50:

SQLSTATE[HY000] [1045] Access denied for user 
'master'@'localhost'(using 
password: YES)                                                                

In PDOConnection.php line 46:

SQLSTATE[HY000] [1045] Access denied for user 'master'@'localhost' 
(using password: YES)

I did try to edit the mysql url in the env file like below:

https://github.com/thiagogomesverissimo/symfony_traditional_login/blob/master/.env.dist

DATABASE_URL=mysql://db_username:db_password@127.0.0.1:3306/db_mydbname

Another try was:

DATABASE_URL=mysql://root:root@localhost/mydbname

I am just replacing the username, password, and mydbname with my information. But still getting the same errors. Any help would be highly appreciated.

How to use Intl component with table builider?

$
0
0

Hey I use ominis/datatables bundle in Symfony 4.3. I store in my db country code from Intl. How to use Intl::getRegionBundle()->getCountryName($value) when i'm using table builider. My code below (but not working)

$table = $this->datatableFactory->create([])
        ->add('name', TextColumn::class, ['label' => 'Name', 'className' => 'bold'])
        ->add('adress', TextColumn::class, ['label' => 'Adress', 'className' => 'bold'])
        ->add('city', TextColumn::class, ['label' => 'City', 'className' => 'bold'])
        ->add('state', TextColumn::class, ['label' => 'State', 'className' => 'bold'])
        ->add('country_code', TextColumn::class, ['label' => 'Country', 'className' => 'bold', 'render' => function($value, $context) {
            return Intl::getRegionBundle()->getCountryName($value);}])
        ->add('vat', TextColumn::class, ['label' => 'VAT', 'className' => 'bold'])
        ->add('regon', TextColumn::class, ['label' => 'Regon', 'className' => 'bold'])
        ->createAdapter(ORMAdapter::class, [
            'entity' => Company::class
        ])
        ->handleRequest($request);

    if ($table->isCallback()) {
        return $table->getResponse();
    }     

How to setup .env in Synfony for Reverse engineering using PDO

$
0
0

I just started a project with Symfony 4. In this project, I do not want to create my Entity but recover existing database on an AS / 400. According to the doc Symfony, I have to reverse engineer but I have to complete the .env file with the information from my database namely: reverse_engineering DATABASE_URL = mysql: // db_user: db_password@127.0.0.1: 3306 / db_name However, the AS400 does not work with mysql but with DB2. How can I make the bridge? I'm thinking about using PDO, but I do not know how to make and modify my .env file.

Do you have an idea to help me?

Thanks for your help If you need more information, just let me know.

Viewing all 3925 articles
Browse latest View live


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