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

Get Multiple Entities from Symfony route annotation with the same column name

$
0
0

I have two Doctrine Entities. Project and Story, both of which have a unique column name Alias. I want to fetch both project and story entities (In this case i actually want only the Story object but the project alias will be dynamic). I tried with the @Entity property:

    /**
     * @Route("/project/{Alias}/{StoryAlias}", name="front-project-story-page" )
     * @Entity("Story", expr="repository.findBy(['Alias'=>StoryAlias])")
     */
    public function FrontProjectStoryPage(Project $project,Story $story)
    {
     ....
    }

But it prompts this error

An exception has been thrown during the rendering of a template 
("[Semantical Error] Annotation @Entity is not allowed to be declared on method. 
You may only use this annotation on these code elements: CLASS in /home/../config/routes/../../src/Controller/ 
(which is being imported from "/home/../config/routes/annotations.yaml"). 
Make sure annotations are installed and enabled.").

How can i fetch entities that may have same column name?


Symfony 4 : Get user object on logout handler give anonymous string

$
0
0

i'm trying to remove the token property i have added in User Entity on logout listener but it's give me anonymous string. How can I get the User object to update it ?

My LogoutListener:

namespace App\Listener;

class LogoutListener implements LogoutHandlerInterface
{
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /**
     * This method is called by the LogoutListener when a user has requested
     * to be logged out. Usually, you would unset session variables, or remove
     * cookies, etc.
     */
    public function logout(Request $request, Response $response, TokenInterface $token)
    {
        var_dump($token->getUser());die;

        /*$user->setToken(null);
        $user->setDateToken(null);
        $this->entityManager->persist($user);
        $this->entityManager->flush();*/
    }
}

My service.yml:

    app.logout.listener:
        class: App\Listener\LogoutListener

My security.yml:

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        logout:
            pattern: ^/logout
            anonymous: true
            logout:
                path: /logout
                handlers: [app.logout.listener]
                success_handler: app.logout.success.listener

How to do username case insensitive in login form?

$
0
0

I'm using the login form from Symfony, but I can't login, if the entered username is 'FOO' and in the DB is stored 'foo'. I'm using Postgres. It means the username-field is case sensitive. What can I do?

Does @Assert\Choice(callback="...") work only with form builder?

$
0
0

I want restrict values in the field action. Only pre-defined strings may be stored in this field. Does @Assert\Choice(callback="getActions") work only with form builder? Is there an another way to check allowed values?

class Log
{
    const SENT_REGISTRATION_EMAIL = 'Registration email was sent';

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="text", length=50)
     * @Assert\Choice(callback="getActions")
     */
    private $action;

    .
    .
    .

    /**
     *
     * @return string[]
     */
    public static function getActions(): array
    {
        return [self::SENT_REGISTRATION_EMAIL];
    }
}
$log = new Log();
$log->setAction(Log::SENT_REGISTRATION_EMAIL);

$this->em->persist($log);
$this->em->flush();

Definine a synthetic service in Symfony 4.1 doesn't work from within a bundle

$
0
0

I am creating a Symfony Bundle that defines a synthetic service:

my_alias:
    public: true
    synthetic: true

After installing the bundle, the application's console command cache:clear always fails with the error:

[Symfony\Component\DependencyInjection\Exception\RuntimeException] Invalid service "my_alias": class "" does not exist.

If I create the same alias inside the actual framework, this error does not turn up.

Is this a bug, or am I doing something wrong?

symfony 3.4 unrecognized option in config

$
0
0

Can you help me to resolve this problem? I am trying to the composer update

Unrecognized option "environment" under "test_sq.fallback"

config_dev.yml

 test_sq:
   fallback:
     environment: dev

Lorsque j ai mis mon site sur le Web (PS: en local tout marche correctement) [closed]

$
0
0

Bonjour tout le monde,

Je viens vers vous aujourd'hui car je rencontre un problème avec un de mes sites web : enter image description here Malgré plusieurs tentatives je ne parviens toujours pas à résoudre mon probléme. Je vous remercie d'avance L'erreur en PJ(photo) Fatal error: require(): Failed opening required '/homepages/39/d275580826/htdocs/BergeyronConsulting/BergeyronConsulting/vendor/composer/../symfony/var-dumper/Resources/functions/dump.php' (include_path='.:/usr/lib/php7.1') in /homepages/39/d275580826/htdocs/BergeyronConsulting/BergeyronConsulting/vendor/composer/autoload_real.php on line 66

Configuring which Redis adapter to use in Symfony Cache

$
0
0

I want to make use of Predis\Client instead of \Redis for all the Redis connections.

The Symfony docs on cache adapters describe that you can give additional options to the createConnection method. However, this is all autowired in the service container. The only thing I'm declaring is that I want to use Redis for caching:

framework:
  cache:
    app: cache.adapter.redis
    default_redis_provider: '%redis_dsn%'

Is there any way I can configure the default options for the RedisAdapter? Or is there another way that I can set Symfony always to use Predis\Client for Redis?

Configuring the DSN with ?class=\Predis\Client works, is this the optimal solution?


How to redirect user outside of react but on the same domain?

$
0
0

My app is built with react and Symfony 4.

I use Symfony 4 for all the backend as well as all the public parts of the site for SEO purposes (blog/landing page/legals and so on).

Now I would like to redirect my user from my react app to my webapp (after he/she logs out). For example, I would like my-app.com/logout to be on a Symfony webpage and NOT on my react app. So from my-app.com/dashboard, if I click logout (or landing page or blog) I go to my-app.com/logout (or landingpage or blog).

How would I do that? A friend told me I should create a sub domaine. Is there any other way?

Thanks a lot.

How to reference mailer component of symfony 4.3 with FOSUserBundle

$
0
0

I would like to send my FOSUserBundle emails via the Symfony's new mailer component.

Given these instructions, I need to create a service that implements the FOSUserBundle MailerInterface. Thus I created a service and implemented the methods.

<?php


namespace App\Service;

// some use statements 

class FOSUserSendgridMailer implements MailerInterface
{...

Now I want to reference this new service in the fos_user_yaml by:

fos_user:
  db_driver: orm # other valid values are 'mongodb' and 'couchdb'
  firewall_name: main
  service:
    mailer: App\Service\FOSUserSendgridMailer

I then get an error The service "fos_user.listener.email_confirmation" has a dependency on a non-existent service "App\Service\FOSUserSendgridMailer".

Autowire and autoconfigure are both set to true in services.yaml.

How do I reference my new service correctly?

How to use orWhere inside andWhere in a doctrine query builder

$
0
0

I would like to create a search in which you can select several cities and options like this.

SELECT * FROM `company` WHERE (`city_id` = 4 OR `city_id` = 5) AND (`option` = 1 OR `option` = 2)

How can i make this in Doctrine?

/**
 * @param CompanyAdminSearch $search
 * @return Query
 */
public function findVisibleQuerySupplierSearch(CompanyAdminSearch $search): Query
{
    $query = $this->findVisibleQuerySupplier();

    if ($search->getCity()->count() > 0){
        $k = 0;
        foreach ($search->getCity() as $k => $city){
            $k++;
            $query = $query
                ->andWhere($query->expr()->orX("company.city = :city$k"))
                ->setParameter("city$k", $city);
        }
    }

    if ($search->getOptions()->count() > 0) {
        $k = 0;
        foreach ($search->getOptions() as $k => $option){
            $k++;
            $query = $query
                ->andWhere(":option$k MEMBER OF company.options")
                ->setParameter("option$k", $option);
        }
    }

    return $query->getQuery();
}

private function findVisibleQuerySupplier(): QueryBuilder
{
    return $this->createQueryBuilder('company')
        ->andWhere('company.metier = :metier')
        ->setParameter('metier', true)
        ;
}

I try with orX but it doesn't work.

Can someone help me?

Symfony Messenger / RabbitMQ detecting requed messages

$
0
0

If consuming message fails message is re-queued with a delay by default. Is there a way to add a counter to a message so I could know if message is on its last attempt?

This is desired behavior:

First attempt:

App\Message\Message {
  body: array:2 [
    "id" => 2
    "alias" => "some_alias",
    "attempt" => 0,
  ]
}

First retry:

App\Message\Message {
  body: array:2 [
    "id" => 2
    "alias" => "some_alias",
    "attempt" => 1,
  ]
}

Second retry:

App\Message\Message {
  body: array:2 [
    "id" => 2
    "alias" => "some_alias",
    "attempt" => 2,
  ]
}

Third retry:

App\Message\Message {
  body: array:2 [
    "id" => 2
    "alias" => "some_alias",
    "attempt" => 3,
  ]
}

Symfony Upload with VichUploader and One to Many Associated Entities

$
0
0

This is my problem brief: I have 2 entities that are associated OneToMany relation. There is no problem when uploading first time but the update process were confused. If an update request sent that handleRequest function of Form were remove some of the relation entities and add the new upload files.

For example: I have 1 credit and 2 extra file related with that credit. Then when I want to update and upload any other file. The last file has been deleted automaticly when execute the handleRequest function of Form.

Here is my codebase:

Credit entity:

/**
 * @ORM\Entity(repositoryClass="App\Repository\CreditRepository")
 * @Vich\Uploadable()
 */
class Credit
{

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\ExtraFile", mappedBy="credit", cascade={"persist", "remove"})
     * @var ExtraFile[] An ArrayCollection of ExtraFile objects.
     */
    private $extraFiles;

ExtraFile entity:

/**
 * Class ExtraFile
 * @ORM\Entity()
 * @Vich\Uploadable()
 */
class ExtraFile
{

    /**
     * @ORM\ManyToOne(targetEntity="Credit", inversedBy="extraFiles")
     */
    private $credit;

In my Controller:

public function applicationFiles(Credit $credit, Request $request): Response
{
    $form = $this->createForm(CreditExtraType::class, $credit);
    $form->handleRequest($request); // <--- At this point the $credit entity "extraFiles" entities changed and removed the last or two entities (it depent how much file send for upload) with OneToMany.
    if ($form->isSubmitted() && $form->isValid()) {

And the CreditExtraType codes:

class CreditExtraType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('extraFiles', CollectionType::class, [
                'entry_type' => CreditExtraVichFileType::class,
                'allow_add' => true,
                'allow_delete' => true,
                'required' => false,
                'by_reference' => false,
                'disabled' => false,
            ])
        ;

    }

Do you have any idea?

Processing form in modal window with Vue js, Symfony and Semantic UI

$
0
0

Iam trying to make an application using Symfony4, Semantic UI and Vue js. Now Iam struggling making the Vue js working on elements inside modal window from Semantic.

I have some input fields from Symfony Form builder inside Semantic modal. I want to prevent default action on submit button - form has v-on:submit.prevent="onSubmit" attribute. onSubmit function is just e.preventDefault() code.

When I open modal and try to click on that button, it just ignore that code and reload page as it thinks I clicked submit button (which I did but I want to call that onSubmit method in Vue).

Can someone help how to make it working? Thanks.

Code as twig template:

<a class="ui button add-client-button" @click="openModal">
  <i class="plus icon"></i>
  Add client
</a>

<div class="ui tiny modal add-client">

    <div class="header">Add client</div>
         <div class="content">

         {{ form_start(client_form, { 'attr' : { 'class': 'ui form', 'v-on:submit.prevent' : 'onSubmit' }} ) }}
    ...some form inputs...
         </div>
    <div class="actions">
            <button class="ui black deny button">Close</button>
            <button class="ui button add-client-modal-button" @click="onSubmit">Add</button>
        </div>
</div>

Code Vue js:

new Vue({
delimiters: ['@{', '}'],
el: '#app',
data: {
    modalDom: null
},
mounted: function() {
    this.modalDom = $('.ui.tiny.modal.add-client').modal({ inverted: false, closable: false });
},
methods: {
onSubmit: function (e)
{
    e.preventDefault();
    console.log('hey')
},
openModal: function()
{
    this.modalDom.modal('show');
}
});

whole code: https://www.codepile.net/pile/D7ooyW7j

Entity class made with make:entity not recognized in Controller despite use namespace

$
0
0

In Symfony 4, using bin/console I've created new Entity:

php bin/console make:entity Being
...

It created Entity/Being.php and Repository\BeingRepository.php files.

Later I've also used make:migration and doctrine:migration:migrate, and my changes are now visible in database.

The problem is, when I wrote simple controller in Controller/DefaultController.php:

namespace App\Controller;
use App\Entity\Being;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class DefaultController extends AbstractController
{

/**
 * @Route("/", name="blog_index")
 */
public function index()
{
    $entityManager = $this->getDoctrine()->getManager();
    $beings =  $entityManager->getRepository(Being::class);
    return $this->render('default/index.html.twig',
        ["beings" => $beings->findAll()]);
}
}

I get error:

Class 'App\Entity\Being' does not exist

I also tried changing Being to explictly \App\Entity\Being with same result.

Note that I've not touched the files created by make:entity (Entity/Being.php and Repository\BeingRepository.php). First one looks like this:

<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\BeingRepository")
 */
class Being
{
...

Do I miss something?


Using VichUploaderBundle to upload a file through an API

$
0
0

So, what I need is a basic file upload. What I have is Symfony 4 and VichUploaderBundle, integrated exactly as described https://symfony.com/doc/current/bundles/EasyAdminBundle/integration/vichuploaderbundle.html

Entity is marked as @Vich\Uploadable, fields are defined correcty:

/**
 * @Vich\UploadableField(mapping="images", fileNameProperty="fileName")
 * @var File
 */
private $file;

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

This is my Type:

class MyType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name', TextType::class)
            ->add('file', VichImageType::class, ['allow_file_upload' => true])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => My::class,
            'allow_extra_fields' => false,
            'http_method' => 'POST'
        ]);

        $resolver->setRequired('http_method');
    }
}

What I have in my controller:

$form = $this->createForm(MyType::class, null);
    $form->submit(array_merge($request->request->all(), $request->files->all()));

    if ($form->isSubmitted() && $form->isValid()) {
        /** @var $my */
        $my = $form->getData();
        $em = $this->getDoctrine()->getManager();
        $em->persist($my);
        $em->flush();

        return $this->json($my);
    }

The outcome of this is a TransformationException:

Compound forms expect an array or NULL on submission.

I've debugged the whole thing with xDebug - it successfully submits name field, and even file field, for the first time. But then, for some reason, it thinks it's a compound form and tries to submit it one more time - which obviously leads to a transformation exception https://github.com/symfony/form/blob/master/Form.php#L571

And, when I try to set 'compound' => false, it doesn't submit the file field at all.

What might be the problem here? I've seen in the docs, that for using it with EasyAdmin it's enough to just specify the field name and type 'vich_image', why it doesn't work outside the EasyAdmin? You could notice, by the way, that I've added extra parameter 'allow_file_upload' => true as it wasn't submitting without it https://github.com/symfony/form/blob/master/Form.php#L534

Symfony4/Doctrine - Cannot connect via SSL (DBAL Config)

$
0
0

Can somebody please let me know what's missing? All %env% variables are correct. Everything worked perfectly until I enabled SSL.

Using these connection details and 'Key.crt.pem' I have no issues connecting to the database using Sequel Pro.

Error:

{"code":500,"message":"An exception occurred in driver: SQLSTATE[HY000] [9002] SSL connection is required. Please specify SSL options and retry."}

doctrine:
dbal:
    # configure these for your database server
    driver: 'pdo_mysql'
    server_version: '5.7'
    charset: latin1
    default_table_options:
        charset: latin1
        collate: latin1_swedish_ci
    dbname:               '%env(resolve:DATABASE_NAME)%'
    host:                 '%env(resolve:DATABASE_HOST)%'
    port:                 '%env(resolve:DATABASE_PORT)%'
    user:                 '%env(resolve:DATABASE_USER)%@%env(resolve:DATABASE_HOST)%'
    password:             '%env(resolve:DATABASE_PASSWORD)%'
    mapping_types:
            enum: string
    options:
        MYSQL_ATTR_SSL_CA : '/Path/Key.crt.pem'

Why Symfony messenger was not restarted by Supervisor (after MYSQL update)?

$
0
0

I have Symfony 4.3 application with a single messenger process consuming DB messages that is started/restarted by Supervisor. Everything works flawlessly (for 3 months), the messenger is started after reboot, restarted after I kill it or after its timeout.

Today I noticed that messenger is not running while Supervisor is. Last time I can tell for sure messenger was running is 19 hours (not very busy messenger) before MYSQL update (5.7.27 > 5.7.28) was performed by unattended-upgrades - it was 3 hours after the update when I noticed. The supervisor log shows nothing.

  • Does messenger crash because of the DB SW update?
  • Why was messenger not restarted by Supervisor as usual?
  • Is there any way to prevent it in the future (i mean how to make sure messenger is always running or at least trying to run)?

is there a way to get the value [product_code]1INSAZE from querystring and use it to run sql query

$
0
0

I am trying to get data from a querystring that looks like this:

http://127.0.0.1:8000/product/controller/php?ids[]=[product_code]1INSAZE

if I do :

$ids = $request->query->get('ids', null);

and dump it I get something like this :

array:1 [▼ 0 => "[product_code]1INSAZE" ] ]

if I dump($ids[0]) I get:

"[product_code]1INSAZE"

i Need that string in order to do this:

$ids = $ids[0];

$result = $this->createQueryBuilder('k')

->andWhere("k.product_code = $ids")

->getQuery()

->getResult();

return $result;

I get this error :

[Syntax Error] line 0, col 72: Error: Expected Literal, got '['

is it related to that [product_code]? and If yes how do I get rid of that and execute the query?

Error while sending email [Symfony mailerBundle]

$
0
0

I'm building a website with symfony 4, today I try to send email with the emailBundle of symfony i'm using also the mailgun bundle as transport. Everything is well configured.

When I send email the classic way with ->text() or ->html() everything work but when I use twig templating for email I get this error :

Unable to send an email: Need at least one of 'text' or 'html' parameters specified (code 400).

This is the code part for mail sending :

<?php
            $email = (new TemplatedEmail())
                ->from(new NamedAddress('blabla','blabla'))
                ->to($user->getEmail())
                ->subject('Account registration')
                ->htmlTemplate('emails/signup.html.twig')
                ->context([
                    'firstName' => $user->getFirstName(),
                    'email' => $user->getEmail(),
                    'url' => $_ENV['blabla'].'/account'
                ]);
            $transport = new MailgunTransport($_ENV['blabla'],$_ENV['blabla']);
            $mailer = new Mailer($transport);
            $mailer->send($email);
?>

Thanks in advance

Viewing all 3924 articles
Browse latest View live


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