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

what is the form variable

$
0
0

I have this template in twig :

{% form_theme form _self %}  

{% block body %}

<div class="container">
    <h1>creer une nouvelle annonce</h1>

    {{ form_start(form) }}

        {{ form_widget(form) }}

        <button type="submit" class="btn btn-primary">créer la nouvelle annonce</button>

    {{ form_end(form, {'render_rest': false}) }}

</div>

{% endblock %}

{% block form_row %}

<pre>
    {{ dump() }}
</pre>
<div class="form-group">
    {{ form_label(form) }}
    {{ form_widget(form) }}
</div>

{% endblock %}

and this is the output of the dump function in my chrome:

array:32 [▼
"value" => """attr" => array:1 [▶]
  "form" => Symfony\Component\Form\FormView {#707 ▶}
  "id" => "ad_title""name" => "title""full_name" => "ad[title]""disabled" => false
  "label" => null
  "label_format" => null
  "multipart" => false
  "block_prefixes" => array:3 [▶]
  "unique_block_prefix" => "_ad_title""row_attr" => []
  "translation_domain" => null
  "label_translation_parameters" => []
  "attr_translation_parameters" => []
  "cache_key" => "_ad_title_text""errors" => Symfony\Component\Form\FormErrorIterator {#708 ▶}
  "valid" => true
  "data" => null
  "required" => true
  "size" => null
  "label_attr" => []
  "help" => null
  "help_attr" => []
  "help_html" => false
  "help_translation_parameters" => []
  "compound" => false
  "method" => "POST""action" => """submitted" => false
  "app" => Symfony\Bridge\Twig\AppVariable {#277 ▶}
]

schreenshot

What is the form variable in line number 4 of output of dump function above


I can't reply to the cmd when it asks for an input (solved)

$
0
0

I am just starting to learn how to use Symfony 4 and I have a problem. Sometimes when I use the command terminal, it interacts with me (like it asks for the name of a property of an entity), the problem is that I can never reply, it always stops and aborts the interaction immediately.

Edit: It still doesn't work but I wrote the option -v and it gave me the thing on the next picture/link. Does somebody know what it means? Here is the command display with -v

Edit(2): I searched inside the code where the error appeared and I saw this above the function where the RuntimeException come from:

/**
 * Asks the question to the user.
 *
 * @return bool|mixed|string|null
 *
 * @throws RuntimeException In case the fallback is deactivated and the response cannot be hidden
 */

Does somebody know what it means?

Edit(Solved): as you may see in the comment section, I solved my problem by using php version 7.3.12 instead of 7.4

Merge pdfs documents in one KnpLabs/KnpSnappyBundle

$
0
0

I'm trying to use KnpLabs/KnpSnappyBundle, I want to know if i can :

  1. Merge pdf files in one
  2. Convert images to pdf
  3. Load pdf locally

My Controller

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Knp\Snappy\Pdf;
use Symfony\Component\HttpKernel\KernelInterface;

class PdfController extends AbstractController
{
    private $pdf;
    private $kernel;

    public function __construct(Pdf $pdf, KernelInterface $kernel)
    {
        $this->pdf = $pdf;
        $this->kernel = $kernel;
    }

    /**
     * @Route("pdf")
     */
    public function pdfAction()
    {
        $html = "<html><body>hello snappy !</body></html>";
        // trying to merge pdf -> error
        $this->pdf->generate(['http://www.pdf995.com/samples/pdf.pdf', 'http://www.africau.edu/images/default/sample.pdf'], 'merge.pdf');
        //trying to convert jpg to pdf -> it show empty PDF !
        $this->pdf->generate('https://www.cleverfiles.com/howto/wp-content/uploads/2018/03/minion.jpg', 'jpgToPdf.pdf');
    }
}

Error :

The exit status code '1' says something went wrong: stderr: "Loading pages (1/6) [> ] 0% [===> ] 5% [======> ] 10% Error: Failed loading page http://www.pdf995.com/samples/pdf.pdf (sometimes it will work just to ignore this error with --load-error-handling ignore) Error: Failed loading page http://www.africau.edu/images/default/sample.pdf (sometimes it will work just to ignore this error with --load-error-handling ignore) Exit with code 1, due to unknown error. " stdout: "" command: /usr/bin/wkhtmltopdf --lowquality 'http://www.pdf995.com/samples/pdf.pdf''http://www.africau.edu/images/default/sample.pdf''merge.pdf'.

Symfony 4, get Logger, get Doctrine, get Rabbit out of the controller

$
0
0

In Symfony 3.3 on the controller I could do:

$sendEmailManager = new SendEmailManager($this->container);

And in the Manager:

private $ container;
public function __construct(ContainerInterface $ container) {
$this->container = $container;
}

I could use this in all methods:

$logger = $ this->container->get('logger');
$em = $this->container->get('doctrine')->getManager();
$container->get('old_sound_rabbit_mq.producer_email_text_producer')->publish(json_encode($ dataToRabbit));

How can I do this in Symfony 4.4?

symfony route import with allowable null prefix does not work

$
0
0

when importing routes from a resource file with a prefix, symfony will not match a valid route with an empty prefix unless the URL has a double / in it (//).

How to reproduce Given this setting:

web:
  resource: '_routes.yaml'
  prefix: /{route_prefix?}
  requirements:
    route_prefix: valueA|valueB

and _routes.yaml:

product_list:
  path: '/brands/{brand_name}/{id}.html'
  controller: App\Controller\Brand\ProductController::index

the router will match: /valueA/brands/{brand_name}/{id}.html and /valueB/brands/{brand_name}/{id}.html but will not match/brands/{brand_name}/{id}.html unless you provide the URL like this: //brands/{brand_name}/{id}.html

Is it really a bug or something I do not understand?

How to prevent user from being unauthenticated after dynamic password change

$
0
0

The problem is when I change user password in my database while I'm logged in, my user becomes unauthenticated after refreshing the page.

It causes too many redirects error in my browser because my root controller is trying to redirect to controller which is protected by @Security("is_granted('ROLE_ADMIN')") annotation.

SecurityController.php

/**
 * @Route("/", name="app_login")
 */
public function login(AuthenticationUtils $authenticationUtils): Response
{
    // (...)
    return $this->redirectToRoute('admin');
}

AdminController.php

/**
 * @Route("/admin", name="admin")
 * @Security("is_granted('ROLE_ADMIN')", message="403 Access denied")
 */
public function index()
{
    // (...)
}

After refreshing /admin view (or every other view) it fails to authenticate current user due to @Security annotation and it falls back to root controller when the infinite redirect loop begins.

How to prevent Symfony from changing user status on password change while being logged in?

How to keep a pre-existing table unchanged when using migrations in Symfony?

$
0
0

I need that Symfony/migration/Doctrine to leave my table untouched. Don't touch her structure at all!

I have a pre-existing table (a legacy database) with the id field defined like this: "id bigint NOT NULL DEFAULT nextval('configuracoes_seq'::regclass),"

When I define ORM (Doctrine) like this:

 * @ORM\Column(name="id", type="bigint", nullable=false, options={"default":"nextval('configuracoes_seq'::regclass)"})
 * @ORM\Id 
 * @ORM\GeneratedValue(strategy="IDENTITY")
 * @ORM\SequenceGenerator(sequenceName="configuracoes_seq", allocationSize=1, initialValue=1)

The make:migration changes my table (I don't want it to change) like this:

$this->addSql('DROP SEQUENCE configuracoes_seq CASCADE');
$this->addSql('ALTER TABLE configuracoes ALTER id SET');     

When I define ORM (Doctrine) like this:

 * @ORM\Column(name="id", type="bigint", nullable=false, options={"default":"nextval('configuracoes_seq'::regclass)"})
 * @ORM\Id 
 * @ORM\GeneratedValue(strategy="SEQUENCE")
 * @ORM\SequenceGenerator(sequenceName="configuracoes_seq", allocationSize=1, initialValue=1)   

The make:migration changes my table (I don't want it to change) like this:

    $this->addSql('ALTER TABLE configuracoes ALTER id SET DEFAULT nextval(\'configuracoes_seq\'::regclass)');
    $this->addSql('ALTER TABLE configuracoes ALTER id DROP DEFAULT');

When I define ORM (Doctrine) like this:

 * @ORM\Column(name="id", type="bigint", nullable=false)
 * @ORM\Id 
 * @ORM\GeneratedValue(strategy="SEQUENCE")
 * @ORM\SequenceGenerator(sequenceName="configuracoes_seq", allocationSize=1, initialValue=1)   

The make:migration changes my table (I don't want it to change) like this:

    $this->addSql('ALTER TABLE configuracoes ALTER id DROP DEFAULT');

When I define ORM (Doctrine) like this:

 * @ORM\Column(name="id", type="bigint", nullable=false)
 * @ORM\Id 
 * @ORM\GeneratedValue(strategy="IDENTITY")
 * @ORM\SequenceGenerator(sequenceName="configuracoes_seq", allocationSize=1, initialValue=1)

The make:migration changes my table (I don't want it to change) like this:

    $this->addSql('DROP SEQUENCE configuracoes_seq CASCADE');

Does anyone know please how I keep my table unchanged?

Duplicate definition of column class inherence mapping doctrine

$
0
0

My project contains multiple type of 'Computed'. I try to setup the first one like this:

AbtractComputed:

<?php

namespace App\Entity;

use App\Repository\ComputedRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping\Builder\ClassMetadataBuilder;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Mapping\MappingException;
use ES\Common\Enum\ComputedEnum;
use ReflectionException;

abstract class AbstractComputed
{
    /** @var integer */
    protected $id;

    /** @var string */
    protected $name;

    /** @var string */
    protected $type;

    /**
     * User constructor.
     */
    public function __construct()
    {
    }

    /**
     * @param ClassMetadata $metadata
     * @throws MappingException
     */
    public static function loadMetadata(ClassMetadata $metadata)
    {
        // @formatter:off
        $builder = new ClassMetadataBuilder($metadata);
        $builder
            ->setTable('computed')
            ->setCustomRepositoryClass(ComputedRepository::class)
            ->setJoinedTableInheritance()
            ->setDiscriminatorColumn('kind')
            ->createField('id', Types::INTEGER)
                ->makePrimaryKey()
                ->generatedValue()
            ->build()
            ->createField('name', Types::STRING)
                ->length(255)
            ->build()
            ->createField('type', Types::STRING)
                ->length(255)
                ->nullable()
            ->build()
        ;
        // @formatter:on
        foreach (static::getDiscriminatorMap() as $discr => $class) {
            $metadata->addDiscriminatorMapClass($discr, $class);
        }
    }

    /**
     * @return string
     */
    abstract public static function getKind(): string;

    /**
     * @return array
     */
    public static function getDiscriminatorMap()
    {
        return [
            ComputedProbeImport::getKind() => ComputedProbeImport::class,
        ];
    }

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

    /**
     * @return string|null
     */
    public function getName(): ?string
    {
        return $this->name;
    }

    /**
     * @param string|null $name
     * @return self
     */
    public function setName(string $name = null): self
    {
        $this->name = $name;

        return $this;
    }

    /**
     * @return string|null
     */
    public function getType(): ?string
    {
        return $this->type;
    }

    /**
     * @param string $type
     * @return self
     * @throws ReflectionException
     */
    public function setType(string $type): self
    {
        if (!ComputedEnum::isValidConstValue($type))
        {
            throwException(new \Exception('Invalid Computed type.'));
        }

        $this->type = $type;

        return $this;
    }
}

ComputedProbeImport:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping\ClassMetadata;
use ES\Common\Enum\ComputedEnum;

class ComputedProbeImport extends AbstractComputed
{
    /**
     * @inheritDoc
     */
    public static function getKind(): string
    {
        return ComputedEnum::PROBE_IMPORT;
    }

    /**
     * @param ClassMetadata $metadata
     */
    public static function loadMapping(ClassMetadata $metadata)
    {

    }
}

but when i run bin/console doctrine:schema:update --dump-sql

I didn't understand why console return this error:

[Doctrine\ORM\Mapping\MappingException]                                                                                     
  Duplicate definition of column 'id' on entity 'App\Entity\ComputedProbeImport' in a field or discriminator column mapping. 

// stackoverflow want i add more text so i already try clear cache but that not help... I hate annotation mapping this is why i use the class metadataBuilder, but i put a empty function in the childrens, technicaly this entity isn't mapped ?:/


Symfony 4 Accessing Swift_Mailer in Service

$
0
0

I have been looking at the Symfony 4.1 documentation on using the Swift_mailer. However, it appears the documentation is only assumed it being used in the Controller classes. I'm trying to create a Service with some reusable functions that send email.

I created a EmailService.php file in my service directory. When creating a new instance of this service, it quickly throws and error:

"Too few arguments to function App\Service\EmailService::__construct(), 0 passed in *MyApp\src\Controller\TestController.php on line 33 and exactly 1 expected"

I'm not sure how to pass \Swift_Mailer $mailer into the __construct correctly? I have auto wiring enabled in the services.yaml, so i'm not sure what I need to do differently?

class EmailService
{
    private $from = 'support@******.com';
    private $mailer;

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

How do I pass the \Swift_Mailer into this EmailService construct?

I tried adding this to my config\services.yaml with no success:

App\Service\EmailService:
        arguments: ['@mailer']

The DoctrineBundle is not registered in your application. Try running "composer require symfony/orm-pack" [closed]

$
0
0

I have installed the "DoctrineBundle" and when I trying again, I get the "Nothing to install or update" message.This is the code I'm running on submission of a form is the following:

$patient = new Patient();
$patient->setFirstName($formData['firstname']);
$patient->setLastName($formData['lastname']);
$patient->setGender($formData['gender']);

$mainEm = $this->getDoctrine()->getManagerByClass(Patient::class);
$mainEm->persist($patient);
$mainEm->flush();

The error message I get when running that, is the following:

if (!$this->container->has('doctrine')) {            
    throw new \LogicException('The DoctrineBundle is not registered in your application. Try running "composer require symfony/orm-pack".');        
}

This is the screen shot of the message:

enter image description here

Symfony 4 is painfully slow in DEV

$
0
0

I try to run a simple Symfony 4 project on a docker container. I have tested regular PHP scripts, and they work very well. But, with Symfony project, the execution gets ridiculously slow. For example, a page without any significant content takes 5-6 seconds.

I have attached the screenshots from Symfony's performance profiler.

Screenshot1Screenshot2Screenshot3Screenshot4

Do you have any idea what how to reduce this execution time to an acceptable level?

Displaying search field with omines/datatables-bundle

$
0
0

Im new to omines/datatables-bundle and I have problem displaying search.

I was studying documentation and was not able to get it working. Ive created a table like this

$table = $dataTable->create()
          ->add('street', TextColumn::class, ["label" => "Street", "searchable" => true, "globalSearchable" => true])
          ->add('houseNumber', TextColumn::class, ["label" => "House number", "searchable" => true])
          ->add('postal', TextColumn::class, ["label" => "Postal Code", "searchable" => true])
          ->add('city', TextColumn::class, ["label" => "City", "searchable" => true])
          ->add('country', TextColumn::class, ["label" => "Country", "searchable" => true])
          ->createAdapter(ORMAdapter::class, [
            'entity' => CustomAddress::class,
          ])
          ->handleRequest($request);

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

        return $this->render('sales_request/add_custom_address.html.twig', ['datatable' => $table]);

Also, in my twig template

<div id="addresses">Loading...</div>
    <script src="{{ asset('bundles/datatables/js/datatables.js') }}"></script>
    <script>
        $(function() {
            $('#addresses').initDataTables({{ datatable_settings(datatable) }}, { searching: true });
        });
    </script>

The datatable works fine, sorting is working etc, but I dont see the search input field.How should I configure it to display it?

Symfony 4: I decorated UrlGeneratorInterface, but it's not used, it uses CompiledUrlGenerator instead

$
0
0

I decorated UrlGeneratorInterface

app.decorator.url_generator:
    class: App\CoreBundle\Routing\Extension\UrlGenerator
    decorates: Symfony\Component\Routing\Generator\UrlGeneratorInterface
    arguments: ['@app.decorator.url_generator.inner']

but it's not used in cases where some bundle in example executes $this->generator->generate(), and I tracked what Symfony does through XDebug and CompiledUrlGenerator is used instead. I can see where this happens, namely in Symfony\Component\Routing\Router in getGenerator it specifically checks for CompiledUrlGenerator::class. But I don't want to override vanilla Symfony code. How am I supposed to override/decorate/extend which class in order for mine to be chosen always, as I have special parameters I need to add to the path. Thank you in advance!

Symfony 4 / Doctrine 2 Can't execute method of Entity a second time

$
0
0

Searched the internet for a answer but I can't get any information regarding this issue. (The names are fictional.)

I am working on a complex webapplication and I am trying to use a 'customSession' entity with a field called 'humanData' and its saved as a blob. With the method getHumanData() I can get the data from the entity. But if I execute the method a second time the data is null.

Entity: customSession

    /**
     * @ORM\Entity(repositoryClass="App\Repository\customSessionRepository")
     */
    class customSession {

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

  public function getHumanData() {
    if (is_resource($this->humanData)) {
      $humanData = stream_get_contents($this->humanData);
      return $humanData;
    } else {
      return $this->humanData;
    }
  }

  public function setHumanData($humanData): self {
    $this->humanData= json_encode($humanData);
    return $this;
  }

    }

Testscript:

$first = json_decode($this->customSession->getHumanData());
$second = json_decode($this->customSession->getHumanData());
dump($first);
dump($second);
die();

Output $first:

Test.php on line 11:
{#6514
  +"gender": "M"
  +"firstName": "Test1"
  +"namePrefix": ""
  +"lastName": "Test2"
  +"initials": "TT"
  +"phone": "1234567890"
  +"email": "test.test@gmail.com"
  +"address": "Test 3"
  +"zipcode": "6745"
  +"place": "Amsterdam"
  +"country": "Nederland"
  +"countryCode": "NL"
}

Output $second:

Test.php on line 12:
null

Does anyone know why this is? And how to avoid it? I need the data in several places.

How do I redirect an anonymous user to custom page instead of the login page if they do not have access to a URL?

$
0
0

I created a login form for my Symfony 5 project.

I want redirect anonymous user to custom page (not the login page) when the user does not have access to my admin panel.

The application controller:

// TestController.php
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;

class TestController extends AbstractController
{
    /**
     * @Route("/admin/panel", name="test")
     * @IsGranted("ROLE_ADMIN")
     */
    public function index()
    {

        return $this->render('test/index.html.twig', [
            'controller_name' => 'TestController',
        ]);
    }
}

And my configuration settings:

# security.yaml
security:
    encoders:
        App\Entity\Admin:
            algorithm: auto

    providers:
        admin:
            entity:
                class: App\Entity\Admin
                property: username

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

            guard:
                authenticators:
                    - App\Security\AdminLoginFormAuthenticator
            logout:
                path: app_logout
        main:
            anonymous: lazy

My application authenticator:

// AdminLoginFormAuthenticator.php 
namespace App\Security;

use App\Entity\Admin;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;

class AdminLoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface
{
    use TargetPathTrait;

    private $entityManager;
    private $urlGenerator;
    private $csrfTokenManager;
    private $passwordEncoder;

    public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)
    {
        $this->entityManager = $entityManager;
        $this->urlGenerator = $urlGenerator;
        $this->csrfTokenManager = $csrfTokenManager;
        $this->passwordEncoder = $passwordEncoder;
    }

    public function supports(Request $request)
    {
        return 'app_admin' === $request->attributes->get('_route')
            && $request->isMethod('POST');
    }

    public function getCredentials(Request $request)
    {
        $credentials = [
            'username' => $request->request->get('username'),
            'password' => $request->request->get('password'),
            'csrf_token' => $request->request->get('_csrf_token'),
        ];
        $request->getSession()->set(
            Security::LAST_USERNAME,
            $credentials['username']
        );

        return $credentials;
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        $token = new CsrfToken('authenticate', $credentials['csrf_token']);
        if (!$this->csrfTokenManager->isTokenValid($token)) {
            throw new InvalidCsrfTokenException();
        }

        $user = $this->entityManager->getRepository(Admin::class)->findOneBy(['username' => $credentials['username']]);

        if (!$user) {
            // fail authentication with a custom error
            throw new CustomUserMessageAuthenticationException('...!');
        }

        return $user;
    }

    public function checkCredentials($credentials, UserInterface $user)
    {
        return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
    }

    /**
     * Used to upgrade (rehash) the user's password automatically over time.
     */
    public function getPassword($credentials): ?string
    {
        return $credentials['password'];
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
            return new RedirectResponse($targetPath);
        }

        return new RedirectResponse($this->urlGenerator->generate('homepage'));
    }

    protected function getLoginUrl()
    {
        return $this->urlGenerator->generate('app_admin');
    }
}

Guard Authenticator in Symfony 4

$
0
0

I am creating a simple login authentication system in Symfony 4 and using security component Guard. My FormLoginAuthenticator is following:

<?php
namespace App\Security;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\Security\Core\Security;

class FormLoginAuthenticator extends AbstractFormLoginAuthenticator
{
    private $router;
    private $encoder;

    public function __construct(RouterInterface $router, UserPasswordEncoderInterface $encoder)
    {
        $this->router = $router;
        $this->encoder = $encoder;
    }

    public function getCredentials(Request $request)
    {
        if ($request->getPathInfo() != '/login_check') {
          return;
        }

        $email = $request->request->get('_email');
        $request->getSession()->set(Security::LAST_USERNAME, $email);
        $password = $request->request->get('_password');

        return [
            'email' => $email,
            'password' => $password,
        ];
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        $email = $credentials['email'];

        return $userProvider->loadUserByUsername($email);
    }

    public function checkCredentials($credentials, UserInterface $user)
    {
        $plainPassword = $credentials['password'];
        if ($this->encoder->isPasswordValid($user, $plainPassword)) {
            return true;
        }

        throw new BadCredentialsException();
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        $url = $this->router->generate('welcome');

        return new RedirectResponse($url);
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
       $request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);

       $url = $this->router->generate('login');

       return new RedirectResponse($url);
    }

    protected function getLoginUrl()
    {
        return $this->router->generate('login');
    }

    protected function getDefaultSuccessRedirectUrl()
    {
        return $this->router->generate('welcome');
    }

    public function supportsRememberMe()
    {
        return false;
    }
}

But it is showing following error:

(1/1) FatalErrorException Error: Class App\Security\FormLoginAuthenticator contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (Symfony\Component\Security\Guard\AuthenticatorInterface::supports)

Could you please give me any clue which abstract method of this class is causing this error ?

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,
  ]
}

Doctrine2/Symfony4 : ManyToMany relation with nested ManyToOne relation

$
0
0

I have a problem with a query. I have 3 entities define like below :

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

    //...

    /**
     * @var Product[]
     *
     * @ORM\ManyToMany(targetEntity="App\Entity\Product", mappedBy="categories")
     */
    private $products;

    //...
}

  • Product entity
class Product
{
    /**
     * @var int
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     * @ORM\Column(type="integer")
     */
    private $id;

    //...

    /**
     * @var Collection
     *
     * @ORM\ManyToMany(targetEntity="App\Entity\Category", inversedBy="products")
     * @ORM\JoinTable(name="product_category",
     *   joinColumns={
     *     @ORM\JoinColumn(name="id_product", referencedColumnName="id", nullable=false)
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="id_category", referencedColumnName="id", nullable=false)
     *   }
     * )
     */
    private $categories;

    /**
     * @var Provider
     *
     * @ORM\ManyToOne(targetEntity="App\Entity\Provider", inversedBy="products")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="id_provider", referencedColumnName="id", nullable=false)
     * })
     */
    private $provider;

    //...
}

  • Provider entity
class Provider
{
    /**
     * @var int
     *
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     * @ORM\Column(type="integer")
     */
    private $id;

    //...

    /**
     * @var Product[]
     *
     * @ORM\OneToMany(targetEntity="App\Entity\Product", mappedBy="provider", orphanRemoval=true, cascade={"all"})
     */
    private $products;

    //...
}

I want to query all products categories manage by a provider. So i try this :

class CategoryRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Category::class);
    }

    public function findByProvider(Provider $provider)
    {
        $qb = $this->createQueryBuilder('c');

        return $qb->leftJoin('c.products', 'p')
                  ->addSelect('p')
                  ->andWhere('p.provider = :provider')
                  ->setParameter('provider', $provider)
                  ->addOrderBy('c.name')
                  ->getQuery()
                  ->getResult();
    }
}

But i always have an empty result despite the fact that a provider have many products. Please how should i achieve this query. Thank you

How to prevent Symfony 4 service override?

$
0
0

I have base /config/services.yaml which stores many services in my Symfony 4.3 project. For example:

My\Namespace\Service:
  - '@My\Namespace\Dependency'

For my test purposes, I have config/test/test_services.yaml where I store services with 'test.' prefix to test private services, making them public in test env.

One of the services, declared in test_services.yaml has no prefix. It is identical by its name (FQCN) to another one defined in services.yaml. They have different constructor arguments of the same type.

Test one (/config/test_services.yaml) has mocked dependencies returning fixtures data:

My\Namespace\Service:
  - '@My\Namespace\MockedDependency'

Is there a way to prevent service override to not replace mocked service with real one during test execution in test env?

Symfony TwigBundle not loading any custom extensions

$
0
0

I am working on updating Zikula from Symfony 3 to Symfony 4 (I'm working specifically in this PR at the moment). Part of this is removing Symfony's old templating mechanism and switching entirely to Twig. In the process I am running into a very unusual problem: None of the custom Twig extensions in the included Bundles or the pseudo bundles (they're just Bundles named Modules) are loaded and available in templates.

Yes, the extensions class are autowired and autoloaded and yes they are available - i.e. they are listed in bin/console debug:container and specifically if I do something like

me% bin/console debug:container AdminExtension

Information for Service "Zikula\AdminModule\Twig\Extension\AdminExtension"
==========================================================================

 ---------------- -------------------------------------------------- 
  Option           Value                                             
 ---------------- -------------------------------------------------- 
  Service ID       Zikula\AdminModule\Twig\Extension\AdminExtension  
  Class            Zikula\AdminModule\Twig\Extension\AdminExtension  
  Tags             twig.extension                                    
  Public           no                                                
  Synthetic        no                                                
  Lazy             no                                                
  Shared           yes                                               
  Abstract         no                                                
  Autowired        yes                                               
  Autoconfigured   yes                                               
 ---------------- -------------------------------------------------- 

 ! [NOTE] The "Zikula\AdminModule\Twig\Extension\AdminExtension" service or alias has been removed or inlined when the  
 !        container was compiled.                                                                                       

This clearly shows that not only is the service properly autowired, but it is also tagged correctly.

If I do bin/console debug:twignone of the custom extensions are listed (at the top with functions, filters, etc). I even tried to step through the TwigBundle Compiler process and I am quite sure the callable are being included there.

Do you have any idea what the problem is or how I might troubleshoot it?

Viewing all 3925 articles
Browse latest View live


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