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

Rest-bundle of Symfony 4 requires config in 4.3 version, while Symfony 4 uses 5.0

$
0
0

Following this tutorial I tried to configure REST API on fresh new Symfony 4 install.

The first step in the tutorial is doing:

composer create-project symfony/skeleton rest_api_project

Followed by

composer require friendsofsymfony/rest-bundle

However, when I try to install friendsofsymfony/rest-bundle, I get:

Your requirements could not be resolved to an installable set of packages. Problem 1 - Installation request for friendsofsymfony/rest-bundle ^2.6 -> satisfiable by friendsofsymfony/rest-bundle[2.6.0]. - friendsofsymfony/rest-bundle 2.6.0 requires symfony/config ^3.4|^4.3 -> no matching package found.

So basically that this bundle requires symfony/config ^3.4|^4.3 while Symfony 4 uses 5.0.

How to make it work? And how this tutorial meant for Symfony 4 could even work when the friendsofsymfony/rest-bundle does not support config in 5.0 version?


Translating this SQL Query into DQL

$
0
0

I'm looking for a translation of this SQL query into doctrine query builder in Symfony 4.3,

My SQL Query :

SELECT card_name 'Name', sets.name "Set"
FROM cards
INNER JOIN sets on cards.card_set = sets.id
WHERE sets.name = 'THE PARAMETER'

The goal of the function im calling in my Controller is to find magic the gathering cards from a specific set. The tables cards and sets are linked of course, so I have to make a join then a where with the string parameter.

The function in the controler calling the repository :

$cards = $card_repo->findBySetName($name);`

And finally, the DQL query I'm trying to make in the CardsRepository:

    /**
     * @return Cards[]
     * @param String $set_name
     */
    public function findBySetName(String $set_name)
    {
        return $this->createQueryBuilder('c')
        ->leftJoin('c.cardSet', 'set')
            ->addSelect('name')
            ->where('name = :set_name')
            ->setParameter('set_name', $set_name)
            ->getQuery()
            ->getResult();
    }

And it doesn't work. I don't get the DQL syntax, it makes 0 sense to me. Do I need a select? A from?

Join 2 tables linked by a 0..n / 0..n relation with PHP Doctrine ORM

$
0
0

I have 2 tables : User and Series.
There is also another table: User_Series that symbolize what series a user follow. Since this table symbolize just a relation 0..n --- 0..n, a class for it wasn't generated.

How can I create a QueryBuilder that retrieves all the series that an user follow?

What I've tried and doesn't work (all series are returned):

$this->getDoctrine()
    ->getRepository(Series::class)
    ->createQueryBuilder('s')
    ->join(User::class, 'u')
    ->where('u = :user_id')
    ->setParameter('user_id', $user->getId())
    ->getQuery()
    ->execute();

Symfony 4.3 dynamic form for tags solution with Doctrine many to one association

$
0
0

First, I'm sorry for my bad english. I need to create form to adding new tags for Article but when I submit form then Request data is not handled in my form because new added tags are not in entity array collection. Is possible to add custom choices to form field with many to one association?

Here is my code:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        dump($builder->getFormConfig()); die;
        /** @var Domain $domain */
        $domain = $this->currentDomainService->getCurrentDomain();

        $builder
            ->add('articleTitle', TextType::class, [])
            ->addEventSubscriber(new TagsChoicesSubscriber())
        ;
    }

class TagshoicesSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            FormEvents::PRE_SET_DATA => ['preSetData', -50],
            FormEvents::PRE_SUBMIT => ['preSetData', -50],
        );
    }

    public function preSetData(FormEvent $event, $childName)
    {

        $choices = array();

        /** @var Article $article */
        $article = $event->getData();

        if ($article instanceof Article) {

            foreach ($article->getTags() as $tag) {
                $tags[] = $tag->getTagName();
            }

            $event->getForm()->add(
                'tags',
                ChoiceType::class,
                [
                    'multiple' => true,
                    'mapped' => false,
                    'choices' => $choices,
                    'data' => $tags,
                    'required' => true,
                    'constraints' => [
                        new NotBlank(),
                    ],
                ]
            );
        }
    }
}

/**
 * Article
 * @ORM\Entity()
 */
class Article
{
    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Tags", mappedBy="article")
     */
    private $tags;
}
/**
 * Tag
 *
 * @ORM\Entity()
 */
class Tag
{
    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Article", inversedBy="tags")
     * @ORM\JoinColumn(name="article_id", referencedColumnName="id")
     */
    private $article;
}


        $form = $this->createForm('App\Form\ArticleType', $article);
        $form->handleRequest($request);

Symfony 4 - How to embed children in forms

$
0
0

Let's suppose I have this Document, a Model Tree Structures with Child References

/**
 * @ODM\EmbeddedDocument
 */
class Link
{
    /**
     * @var string
     *
     * @ODM\Field(type="string")
     */
    private $title;

    //...

    /**
     * @var Link[]
     *
     * @ODM\EmbedMany(targetDocument=Link::class)
     */
    private $children = [];
}

I want to create a form for it

class LinkType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', TextType::class)
            ->add('link', TextType::class)
            ->add('target', TextType::class)
            ->add('children', CollectionType::class, [
                'entry_type' => LinkType::class,
                'allow_add' => true,
                'allow_delete' => true,
            ])
        ;
    }
}

I get a 500 error with empty message (nothing in the log). I guess since I'm embedding the same form, it creates a kind of infinite loop...

Have you ever faced this problem before? If so, have you found a solution?

Post data contains list attribute in symfony

$
0
0

I have a manyToMany association between Tweet and Hashtag. I am trying to submit the Tweet form to create a tweet with the selected hashtags from the checked boxs. In addition, i'm using FosRestBundle.

Is there any solution?

I tried to do like this but data inserted but hashtags never !

Tweet Entity:

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

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

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

/**
 * @ORM\ManyToMany(targetEntity="App\Entity\Hashtag", inversedBy="tweets")
 */
private $hashtags;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\TwitterProfile", inversedBy="tweets")
 */
private $author;

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

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

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

public function setPublishDate(\DateTimeInterface $PublishDate): self
{
    $this->PublishDate = $PublishDate;

    return $this;
}

/**
 * @return Collection|Hashtag[]
 */
public function getHashtags(): Collection
{
    return $this->hashtags;
}

public function addHashtag(Hashtag $hashtag): self
{
    if (!$this->hashtags->contains($hashtag)) {
        $this->hashtags[] = $hashtag;
    }

    return $this;
}

public function removeHashtag(Hashtag $hashtag): self
{
    if ($this->hashtags->contains($hashtag)) {
        $this->hashtags->removeElement($hashtag);
    }

    return $this;
}

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

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

    return $this;
}
}

TweetType:

<?php


    namespace App\Forms;

    use App\Entity\Tweet;
    use App\Entity\TwitterProfile;
    use Doctrine\ORM\EntityRepository;
    use Symfony\Bridge\Doctrine\Form\Type\EntityType;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\Extension\Core\Type\CollectionType;
    use Symfony\Component\Form\Extension\Core\Type\DateType;
    use Symfony\Component\Form\Extension\Core\Type\SubmitType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\OptionsResolver\OptionsResolver;

    class TweetType extends AbstractType
    {
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
      $builder
        ->add('PublishDate', DateType::class,[
            'widget' => 'choice'
        ])

        ->add('hashtags', CollectionType::class,[
            'entry_type' => HashtagType::class
        ])

        ->add('author', EntityType::class,[
            'class' => TwitterProfile::class,
            'query_builder' => function (EntityRepository $er) {
                return $er->createQueryBuilder('tp');
            }
        ])
        ->add('save', SubmitType::class)
    ;

}
public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class'
        =>
            Tweet::class,
        'csrf_protection'
        =>
            false
    ));
}
}

TweetController:

<?php

  namespace App\Controller;

  use App\Entity\Tweet;
  use App\Forms\TweetType;
  use Doctrine\Common\Collections\ArrayCollection;
  use FOS\RestBundle\Controller\FOSRestController;
  use Symfony\Component\HttpFoundation\Request;
  use Symfony\Component\HttpFoundation\Response;
  use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  use Symfony\Component\Routing\Annotation\Route;
  use FOS\RestBundle\Controller\Annotations as Rest;

  class TweetController extends FOSRestController
 {

 /**
 * List All Tweets
 * @Rest\Get("/getAllTweets")
 * @return Response
 */
public function getTweets()
{
    $repository=$this->getDoctrine()->getRepository(Tweet::class);
    $tweets=$repository->findall();
    return$this->handleView($this->view($tweets));
}

/**
 * List One Tweet
 * @Rest\Get("/tweet/{id}")
 * @param int $id
 * @return Response
 */
public function getOneTweet(int $id)
{
    $repository=$this->getDoctrine()->getRepository(Tweet::class);
    $tweet=$repository->find($id);

    if ($tweet == null){
        throw new NotFoundHttpException("this tweet with id:".$id." not founded");
    }

    return $this->handleView($this->view($tweet));
}

/**
 * List One Hashtag to recommand
 * @Rest\Get("/tweets/recommanded-hashtag/group/{groupId}")
 * @param int $groupId
 * @return Response
 */
public function getHashtagToRecommand(int $groupId)
{
    $hashs = new ArrayCollection();
    $repository=$this->getDoctrine()->getRepository(Tweet::class);
    $tweets = $repository->findHashtagToRecommand($groupId);

    if ($tweets == null){
        throw new NotFoundHttpException("this hashtag not founded");
    }

    foreach ($tweets as $key){
        $hashs->add($key->getHashtags());
    }

    return $this->handleView($this->view($hashs));
}

 /**
 * Create New Tweet
 * @Rest\Post("/tweet/add")
 *
 * @return Response
 */
public function postTweet(Request $request)
{
    $tweet = new Tweet();
    $form = $this->createForm(TweetType::class,$tweet);
    $data = json_decode($request->getContent(),true);
    $form->submit($data);
    if ($form->isSubmitted() && $form->isValid()){
        $em = $this->getDoctrine()->getManager();
        $em->persist($tweet);
        $em->flush();
        return $this->handleView($this->view(['status' => 'ok'], Response::HTTP_CREATED));
    }

    return $this->handleView($this->view($form->getErrors()));
}

/**
 * Update Tweet
 * @Rest\Put("/tweet/update/{id}")
 * @param int $id
 * @return Response
 */
public function putTweet(Request $request, int $id)
{
    $repository=$this->getDoctrine()->getRepository(Tweet::class);
    $existingTweet = $repository->find($id);
    if (null === $existingTweet) {
        throw new NotFoundHttpException();
    }
    $form = $this->createForm(TweetType::class, $existingTweet);
    $form->submit($request->request->all());

    if (false === $form->isValid()) {
        return $this->handleView($this->view($form->getErrors()));
    }

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

    return $this->handleView($this->view(['status' => 'ok'], Response::HTTP_OK));
}

/**
 * Update Partially Tweet
 * @Rest\Patch("/tweet/patch/{id}")
 * @param int $id
 * @return Response
 */
public function patchTweet(Request $request, int $id)
{
    $repository=$this->getDoctrine()->getRepository(Tweet::class);
    $existingTweet = $repository->find($id);
    if (null === $existingTweet) {
        throw new NotFoundHttpException();
    }
    $form = $this->createForm(TweetType::class, $existingTweet);
    $form->submit($request->request->all());

    if (false === $form->isValid()) {
        return $this->handleView($this->view($form->getErrors()));
    }
    $em = $this->getDoctrine()->getManager();
    $em->flush();

    return $this->handleView($this->view(['status' => 'ok'], Response::HTTP_OK));
}

/**
 * Delete Tweet
 * @Rest\Delete("/tweet/{id}")
 * @param int $id
 * @return Response
 */
public function deleteTweet(int $id)
{
    $repository=$this->getDoctrine()->getRepository(Tweet::class);
    $existingTweet = $repository->find($id);
    $em = $this->getDoctrine()->getManager();
    $em->remove($existingTweet);
    $em->flush();
    return $this->handleView($this->view(['status' => 'ok'], Response::HTTP_NO_CONTENT));
}
}

Symfony 4.4 FormType problem with validate

$
0
0

I have a problem with my validation form when I submit there is no error message just refresh the page and I don't understand what I have forget? I tried with SubmitType but I have the same problem.

My FormType

class FilmType extends AbstractType
{
   public function buildForm(FormBuilderInterface $builder, array $options)
   {

    $builder
        ->add('titre')
        ->add('resume')
        ->add('dateSortie')
        ->add('personnages', EntityType::class, [
            'class' => Personnage::class,
            'query_builder' => function (PersonnageRepository $pr) {
                return $pr->createQueryBuilder('p')
                    ->orderBy('p.nom', 'ASC');
            },
            'choice_label' => 'nom'
        ])
        ->getForm();
}

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

}

My Controller, I think is ok

 /**
 *
 * @param Request $request
 * @Route("/film/new", name="film_new")
 * @return Response
 *
 */
public function new(Request $request): Response
{
    $film = new Film();
    $form = $this->createForm(FilmType::class, $film);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($film);
        $entityManager->flush();

        return $this->redirectToRoute('home');
    }

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

MY Twig, I add form_errors but nothing more

{% block body %}
    <form>
        <div class="form-group">
            {{ form_start(form)}}
            {{ form_errors(form) }}
            {{ form_widget(form) }}
            <button> Envoyer </button>
            {{ form_end(form) }}
        </div>
    </form>
{% endblock %}

My Film entity.....

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

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

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

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

    /**
     * @ORM\ManyToMany(targetEntity="App\Entity\Personnage", mappedBy="film")
     */
    private $personnages;

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

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

    public function getTitre(): ?string
    {
        return $this->titre;
    }

    public function setTitre(string $titre): self
    {
        $this->titre = $titre;

        return $this;
    }

    public function getResume(): ?string
    {
        return $this->resume;
    }

    public function setResume(string $resume): self
    {
        $this->resume = $resume;

        return $this;
    }

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

    public function setDateSortie(\DateTimeInterface $dateSortie): self
    {
        $this->dateSortie = $dateSortie;

        return $this;
    }

    /**
     * @return Collection|Personnage[]
     */
    public function getPersonnages(): Collection
    {
        return $this->personnages;
    }

    public function addPersonnage(Personnage $personnage): self
    {
        if (!$this->personnages->contains($personnage)) {
            $this->personnages[] = $personnage;
            $personnage->addFilm($this);
        }

        return $this;
    }

    public function removePersonnage(Personnage $personnage): self
    {
        if ($this->personnages->contains($personnage)) {
            $this->personnages->removeElement($personnage);
            $personnage->removeFilm($this);
        }

        return $this;
    }

Error in messenger during composer update symfony

$
0
0

I am trying to update my symfony installation from 4.1.7 but I receive the following error in my console:

In MessenegerPass.php line 279: Invalid middleware: service "allow_no_handler" not found.

Here is my comoposer.json

{
"type": "project",
"license": "proprietary",
"require": {
    "php": "^7.1.3",
    "ext-ctype": "*",
    "ext-iconv": "*",
    "msgphp/user": "^0.7.0",
    "msgphp/user-bundle": "^0.7.0",
    "oneup/uploader-bundle": "^2.1",
    "sensio/framework-extra-bundle": "^5.2",
    "symfony/apache-pack": "^1.0",
    "symfony/asset": "4.2.*",
    "symfony/console": "4.2.*",
    "symfony/expression-language": "4.2.*",
    "symfony/flex": "^1.6",
    "symfony/form": "4.2.*",
    "symfony/framework-bundle": "4.2.*",
    "symfony/messenger": "4.2.*",
    "symfony/monolog-bundle": "^3.5",
    "symfony/orm-pack": "^1.0",
    "symfony/process": "4.2.*",
    "symfony/security-bundle": "4.2.*",
    "symfony/serializer-pack": "*",
    "symfony/swiftmailer-bundle": "^3.1",
    "symfony/twig-bundle": "4.2.*",
    "symfony/validator": "4.2.*",
    "symfony/web-link": "4.2.*",
    "symfony/yaml": "4.2.*"
},
"require-dev": {
    "symfony/debug-pack": "*",
    "symfony/dotenv": "4.2.*",
    "symfony/maker-bundle": "^1.9",
    "symfony/profiler-pack": "*",
    "symfony/test-pack": "*",
    "symfony/web-server-bundle": "4.2.*"
},
"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.2.*"
    }
},
"minimum-stability": "dev",
"prefer-stable": true

}

I tried also to delete composer.lock but still I get the same results. Any help would be appreciated.


Symfony 4 Adding/Updating Entities from Command

$
0
0

I have a command that i run from CLI to import data and create entries.

$doctrine = $this->getContainer()->get('doctrine');
$em = $doctrine->getEntityManager();
/** @var PropertyRepository $propRepo */
$propRepo = $doctrine->getRepository(Property::class);
$propRepo->findOneBy(['id' => $property['PropertyId']])

My Command extends ContentAwareCommand ( even tho it says its deprecated it really dont like it )

SO how can i query my repositories from inside this Command?

Nelmio API doc area and bearer token with symfony 4

$
0
0

I have API in Symfony 4. I added NelmioApiDocBundle to my project, but i have problem with my docs. This is my configuration: packages\nelmio_api_doc.yaml

nelmio_api_doc:
    documentation:
        #        schemes: [http, https]
        info:
            title: Symfony JWT API
            description: Symfony JWT API docs
            version: 1.0.0
        securityDefinitions:
            Bearer:
                type: apiKey
                description: 'Authorization: Bearer {jwt}'
                name: Authorization
                in: header
        security:
            - Bearer: []
    areas: # to filter documented areas
        default:
            path_patterns:
                - ^/api(?!/doc$) # Accepts routes under /api except /api/doc

config\routes.yaml

# Expose your documentation as JSON swagger compliant
app.swagger_ui:
    path: /api/doc
    methods: GET
    defaults: { _controller: nelmio_api_doc.controller.swagger_ui }

This i my swagger ui screen: enter image description here

I have controller: SpeakerController, HomeController, How can I make each controller a separate area and the rest in default? i.e. SpeakerController in area Speaker, HomeController in area Home etc ..

My next problem is that I have an API protected by a bearer token, when I click Authorize in the swagger, I will add the current jwt token and I want to request it, in response I get:

{
  "code": 401,
  "message": "JWT Token not found"
}

In postman i don't have problem: enter image description here

How to a dynamically add roles to a user in Symfony 4?

$
0
0

Using Symfony 4.4.2.

I'm trying to add roles to the current user dynamically (in memory, doesn't have to persist in DB), using an Event Listener.

So I added a service:

    App\EventListener\RoleListener:
        tags:
            - { name: kernel.event_listener, event: kernel.exception }

And created the listener:

<?php

// src/EventListener/RoleListener.php

namespace App\EventListener;

use Symfony\Component\Security\Core\Security;

class RoleListener {
    private $context;

    public function __construct(Security $context) {
        $this->context = $context;
    }

    public function onKernelController(FilterControllerEvent $event) {

        // other logic will be here
        $this->context->getUser()->addRole('ROLE_ANOTHER');

    }
}

However, the user doesn't get the additional role - they still just have "ROLE_USER" (according to the Symfony Profiler).

Symfony 4 @Gedmo\SoftDeleteable() for form with collection type form

$
0
0

I have problem with soft delete item with form collection in Symfony framework

I want to add and remove items in relation with Symfony form collection, If I remove item from collection this item must soft deleted from relation records

with below image you can imagine relations

product relation generated with Mysql workbench

This is my form collections in Symfony forms

Main form
   +
   |
   ProductType+
   |          |
   |          |
   |          PackagesType+
   |                      |
   |                      |
   |                      PackageProductsType
   |
   |
   +

Package products add and removed with JS in frontend based on Symfony example for form collections

my problem is when I remove completely from package_product with activating orphanRemoval=true in annotation of entity every thing work well but record removed completely and I want record soft deleted based on my propose, But when I change below function in Package Entity

    public function removePackageProduct(PackageProduct $packageProduct): self
    {
        if ($this->packageProducts->contains($packageProduct)) {
            $this->packageProducts->removeElement($packageProduct);
            // set the owning side to null (unless already changed)
            if ($packageProduct->getPackage() === $this) {
                $packageProduct->setPackage(null);
            }
        }
        return $this;
    }

always in top function I get last record in packageProducts and when I remove this line $packageProduct->setPackage(null); to disable loosing data in record and replace it with $packageProduct->setDeletedAt(new \Datetime()); to set deleted item, In saved records removed record delete from database and a new record added filled with last record data and deletedAt datetime.

For example:

PackageProduct records before delete first item:

+----+------------+------------+--------+-----------+
| ID | Product_id | package_id | amount | deletedAt |
+----+------------+------------+--------+-----------+
|  1 |         10 |          1 |      3 |           |
|  2 |         11 |          1 |      4 |           |
|  3 |         12 |          1 |      5 |           |
+----+------------+------------+--------+-----------+

PackageProduct records after delete first item:

+----+------------+------------+--------+-----------+
| ID | Product_id | package_id | amount | deletedAt |
+----+------------+------------+--------+-----------+
|  2 |         11 |          1 |      4 |           |
|  3 |         12 |          1 |      5 |           |
|  4 |         12 |          1 |      5 |2020-1-20..|
+----+------------+------------+--------+-----------+

But I expected PackageProduct records after delete first item:

+----+------------+------------+--------+-----------+
| ID | Product_id | package_id | amount | deletedAt |
+----+------------+------------+--------+-----------+
|  1 |         10 |          1 |      3 |2020-1-20..|
|  2 |         11 |          1 |      4 |           |
|  3 |         12 |          1 |      5 |           |
+----+------------+------------+--------+-----------+

How can fix this to get expected result?

How to create a database with a specific chaset and collation, when using doctrine:database:create?

$
0
0

The short version first:

I want the command doctrine:database:create to create the database with the correct/defined charset and collation. How to achieve that? (In the best case without to change any global settings on the server.)


The detailed version:

The context is a Symfony 4 application and Doctrine 2. DBMS: MySQL, OS: Ubuntu 14.04. I want to create the database with Doctrine:

$ bin/console doctrine:database:create

The SQL statement executed Doctrine in the background is:

CREATE DATABASE `mydb`

Means: It doesn't use the charset and collate settings from the .../config/packages/doctrine.yaml and also the DATABASE_URL in the .../.env is ignored.

.../config/packages/doctrine.yaml

parameters:
    env(DATABASE_URL): ''

doctrine:
    dbal:
        # configure these for your database server
        driver: 'pdo_mysql'
        server_version: '5.7'
        charset: utf8mb4
        default_table_options:
            charset: utf8mb4
            collate: utf8mb4_unicode_ci

        # With Symfony 3.3, remove the `resolve:` prefix
        url: '%env(resolve:DATABASE_URL)%'
        mapping_types:
            enum: string
    orm:
        auto_generate_proxy_classes: '%kernel.debug%'
        naming_strategy: doctrine.orm.naming_strategy.underscore
        auto_mapping: true
        mappings:
            App:
                is_bundle: false
                type: annotation
                dir: '%kernel.project_dir%/src/Base/Entity'
                prefix: 'App\Base\Entity'
                alias: App

.../.env

###> doctrine/doctrine-bundle ###
DATABASE_URL=mysql://root:pwd@127.0.0.1:3306/mydb?charset=utf8mb4
###< doctrine/doctrine-bundle ###

The database DEFAULT_CHARACTER_SET_NAME is then latin1 and the DEFAULT_COLLATION_NAME is latin1_swedish_ci:

SELECT
    `DEFAULT_CHARACTER_SET_NAME`, `DEFAULT_COLLATION_NAME`
FROM
    information_schema.SCHEMATA 
WHERE
    schema_name = 'mydb'
;

+----------------------------+------------------------+
| DEFAULT_CHARACTER_SET_NAME | DEFAULT_COLLATION_NAME |
+----------------------------+------------------------+
| latin1                     | latin1_swedish_ci      |
+----------------------------+------------------------+

Symfony : Unknown database type geometry requested

$
0
0
 php bin/console doctrine:mapping:import "App\Entity" annotation --path=src/Entity

In AbstractPlatform.php line 436:
                                                                                                               
  Unknown database type geometry requested, Doctrine\DBAL\Platforms\PostgreSQL100Platform may not support it.  
                                                                                                               

doctrine:mapping:import [--em [EM]] [--shard SHARD] [--filter FILTER] [--force] [--path PATH] [-h|--help] [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi] [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--] <command> <name> [<mapping-type>]

How to redirect old site URL to new Symfony 4 application URL using htaccess file?

$
0
0

I am in the process of migrating a static website to Symfony 4. I would like to redirect the old URLs to their corresponding routes in the new Symfony 4 app (while keeping the same domain name), like so:

https://www.old-site-url.com/contact.html to https://www.old-site-url.com/contact

I have tried specifying a redirect rule in the htaccess (located in the project root) :

RewriteRule https://www.old-site-url.com/contact.html$ https://beta.old-site-url.com/about [R=301,L]

Note: I redirect one URL to the beta subdomain during the testing phase.

However the redirections still wouldn't work. What am I doing wrong?

Thank you!


I'm getting error while installing symfony application [closed]

$
0
0

I'm installing composer and symfony 4.12.4 application.in symfony documentation they run the command in console program.I don't know what is console and how to write code.Give some tips to solve the problem..

How to create dynamic fields in easy admin list page?

$
0
0

I am working on easy admin list page. I have fields that depends on database. How could i add dynamic fields in yaml file ? Here season field may repeat depends on database

 list:
       title: "test"
       fields:
           - { property: name, label: "name" }
           - { property: season,  label: "season" }

Is there any good example how to use Symfony API Platform? [closed]

$
0
0

We're trying to build API with API Platform, but we found constant problems with finding good example/practices on using the platform.

Our constant requirements were/are:

  • Separation of entities and platform mappings (we already have separate YAML files, but there is lack of documentation on what is possible)
  • Preferred usage of Dto objects with generation of .ts interfaces for FE
  • Larger amount of custom operations with custom payloads (DTOs)
  • Usage of IDs not IRIs

Protect Oracle database against SQL Injection

$
0
0

I'm on Symfony and I don't know how protect my database against sql injection. If you have some idea, I will be gratefull.

My function with sql :

  public function getResult($$value)
    {
        $sql = "SELECT SOMETHING FROM SOMETHING smt
                WHERE smt.THING = '".$value."'";

        return $this->egee->executeQuery($sql);

    }

And here is my executeQuery funciton :

   public function executeQuery($sql) {

        $entityManager = $this->em->getConnection('xxx');

        $stmt = $entityManager->prepare($sql);

        $stmt->execute();

       return $stmt->fetch();
    }

I allready try with BindParam, but it's didn't work with Oracle.

Symfony4 Twig Extension return image path

$
0
0

I want to create a TwigExtension Function in Symfony4 in order to display images based on a string property in the view.

I have installed the assets: "symfony/asset": "^4.4",

In lower versions of Symfony I could to this with AssetsHelper::getUrl() -> Returns the public url/path of an asset.

I am not sure how can I achieve this in Symfony4 with "Twig".

Viewing all 3924 articles
Browse latest View live


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