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

How do I overwrite a template of base application from my own bundle?

$
0
0

I use Symfony 4.4 and have written my own bundle. From this bundle I want to overwrite or extend an existing Twig-Template of the base application. So e.g. add a new line at the bottom of the Content block. I have already made several attempts, unfortunately without success. Most examples go in the other direction, overwriting bundle templates. Do you have any tips how I can solve the problem? Thanks a lot.


Iterate numeric values in twig

$
0
0

I'm newbie to symfony twig...Here i want to add the iterate function like below.

In the below case opening stock will be constant...want to iterate the (final) value to the upcoming dates.

Opening Stock       $500 

Date    Issue   receive     final
1.1.20  100               600 ( $500 + $100)
2.1.20           300      300 ( $600 - $300)
4.1.20  200               500 ( $300 + $200)

Can anyone send the best method to resolve,want javascript code with condition...

Thanks and regards,

Building forms dynamically in React using Symfony Forms

$
0
0

My application uses Symfony for backend and React for front end. Is there a way dynamically build form in React by converting Symfony form into react forms? Rendering Symfony form in React app?

Symfony - PHP : the last element of a loop isn't managed

$
0
0

In a Symfony project, when a form to translate backend items is submitted, I get the different translations in a foreach loop to store they in the database. All is rigth except for the last element which not stored in the database.

There is the treatment :

if ($seasonsForm->isSubmitted() && $seasonsForm->isValid()) 
{  

    foreach($seasons as $season)
    {

        foreach($locales as $locale)
        {

            if($locale)
            {

                $translation = $seasonsForm['season_' . $season->getId() . '_' . $locale]->getData();

                if ($translation) 
                {

                    dump($locale . ' : ' . $translation);

                    $season->setSeason($translation);
                    $season->setTranslatableLocale($locale);

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

                }

            }

        }

    } 

    $this->addFlash('success', "Seasons were successfully translated.");

    return $this->redirectToRoute('backend.translations');

}

There is the result of the dump :

enter image description here

However, the last element ("fr : Top") isn't stored in the database :

enter image description here

Someone would an idea about the origin of this problem?

Thanks for your help.

Symfony Query Builder : Avoid escaping double-quotes

$
0
0

One of my database field stores Json (as text). I'd like to query with like commande to find this text : "media":"40".

here is my query :

 $query=$this->createQueryBuilder('f');
 $query->andWhere("f.content like :mediajson ")
       ->setParameter('mediajson','%"media":"'.$mediaId.'"%');

but doctrine runs thie query (for $mediaid=40 ):

Select * from f WHERE f.content LIKE '%\"media\":\"40\"%';

And I'd like to have :

Select * from f WHERE f.content LIKE '%"media":"40"%';

Any ideas to avoid double-quote escaping ?

Best Regards

Last element in a loop is not persisted to DB

$
0
0

In a Symfony project, when a form to translate backend items is submitted, I get the different translations in a foreach loop to store them in the database. All is right except for the last element which not stored in the database.

There is the treatment:

if ($seasonsForm->isSubmitted() && $seasonsForm->isValid()) 
{  

    foreach($seasons as $season)
    {

        foreach($locales as $locale)
        {

            if($locale)
            {

                $translation = $seasonsForm['season_' . $season->getId() . '_' . $locale]->getData();

                if ($translation) 
                {

                    dump($locale . ' : ' . $translation);

                    $season->setSeason($translation);
                    $season->setTranslatableLocale($locale);

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

                }

            }

        }

    } 

    $this->addFlash('success', "Seasons were successfully translated.");

    return $this->redirectToRoute('backend.translations');

}

There is the result of the dump :

enter image description here

However, the last element ("fr : Top") isn't stored in the database :

enter image description here

Doctrine fixtures ManyToOne - Faker don't loading

$
0
0

I have tried to use faker to load some fixtures in my database and when I do php bin/console doctrine:fixtures:load for some reason that I don't know. The load doesn't work and I don't have an error to explain me why it doesn't populate.If anyone can help me to just understand the problem ,it will be great.

Below you can see my code, it's datafixture for 2 entity with a relation many to one (tracker-position).

<?php

namespace App\DataFixtures;
use App\Entity\Positions;
use App\Entity\Tracker;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Persistence\ObjectManager;
use Faker;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;


class PositionsFixtures extends AbstractFixture implements ContainerAwareInterface ,FixtureInterface,OrderedFixtureInterface
{
    private $container;
    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    public function load(ObjectManager $manager)
    {

        $faker = Faker\Factory::create('fr_FR');
        $positions =[];
        for($i=0;$i < 5;$i++){
            $positions[$i] = new Positions();
            $positions[$i]->setTracker($faker->name);
            $positions[$i]->setCreationDate($faker->dateTime);
            $positions[$i]->setPositionDate($faker->dateTime);
            $positions[$i]->setState($faker->state);
            $positions[$i]->setLatitude($faker->latitude);
            $positions[$i]->setLongitude($faker->longitude);
            $positions[$i]->setSpeed($faker->numberBetween(0,400));
            $positions[$i]->setHeading($faker->numberBetween(0,360));
            $positions[$i]->setAddress($faker->address);
            $positions[$i]->setRawDate($faker->text);

            $manager->persist($positions[$i]);

        }

        $trackers =[];
        for($k=0;$k < 5;$k++){
            $trackers[$k] = new Tracker();
            $trackers[$k]->setName($faker->name);
            $trackers[$k]->setTrackerId($faker->uuid);
            $trackers[$k]->setEquipmentType($faker->realText());
            $trackers[$k]->setPlate($faker->randomLetter);
            $trackers[$k]->setDescription($faker->text);
            $trackers[$k]->setPhoneNumber($faker->phoneNumber);
            $trackers[$k]->setLastState($faker->state);
            $trackers[$k]->setLastConnectionDate($faker->dateTime);
            $trackers[$k]->setLastIp($faker->ipv4);
            $trackers[$k]->setLastPort($faker->numberBetween(100,80000));
            $trackers[$k]->setLastBatteryLevel($faker->numberBetween(0,100));
            $trackers[$k]->setLastLatitude($faker->latitude);
            $trackers[$k]->setLastLongitude($faker->longitude);
            $trackers[$k]->setLastHeading($faker->numberBetween(0,360));
            $trackers[$k]->setImage($faker->imageUrl());
            $trackers[$k]->setEnabled($faker->boolean);
            $randomPositions =(array) array_rand($positions,rand(1,count($positions)));
            foreach($randomPositions as $key => $value){

                $trackers[$k]->addPosition($positions[$key]);
            }
            $manager->persist($positions[$i]);

        }
        $manager->flush();
    }
   public function getOrder()
    {
        return 1;
    }
}

Cron Bundle fail run bin/console on symfony 4

$
0
0

I'm trying to run a command through a cron job in a Symfony 4 app.

I have created my command and it run success when I run manually from the console (from my symfony root directory)

C:\xampp\htdocs\MY-PROJECT>php bin/console MY-COMMAND /*It works fine*/

I installed CronBundle (https://packagist.org/packages/cron/cron-bundle) and I registered a cron job from the console:

C:\xampp\htdocs\MY-PROJECT>php bin/console cron:create

The cron job was successfully create in the database, and I try to run:

C:\xampp\htdocs\MY-PROJECT>php bin/console cron:run"
time: 0.15687298774719

The cron job seems to run but it doesn't do anything (but the console show the time elapsed). The cron_report database table report the error =>"Could not open input file: bin/console"

It seems that the cron bundle run the command from a different directory than the one I use when I run the command manually (the root directory of the project).

I tried to run from the console "php bin/console cron:start", but a error message is thrown =>"This command needs the pcntl extension to run." I'm running xampp on windows


Symfony 4 - Entity for ChoiceType Multiple

$
0
0

I stuck on my form. I want to add a ChoiceTyp with multiple true.

 ->add('b2bOnlineOffline', ChoiceType::class, [
            'choices' => [
                'English' => 'en',
                'Spanish' => 'es',
                'Bork' => 'muppets',
                'Pirate' => 'arr',
            ],
            'multiple' => true,
            'required' => true
        ])

If I use in my entity string, I get the error:

Expected argument of type "string or null", "array" given at property path "b2bOnlineOffline".

So i understand I have to use in my entity a array definition. What is the correct way? If I use json for the column:

//
/**
 * @ORM\Column(type="json")
 */
private $b2bOnlineOffline;

//

how must look the getter and setter?

    public function getB2bOnlineOffline(): ?json
{
    return $this->b2bOnlineOffline;
}

public function setB2bOnlineOffline(?json $b2bOnlineOffline): self
{
    $this->b2bOnlineOffline = $b2bOnlineOffline;

    return $this;
}

Or in general, how is the best way to handle the datas/entity for such case?

THX

File being uploaded as part of a form isn't part of the request in Symfony 4

$
0
0

A form I have created includes an upload field to upload a file with. This file can be any format. The form itself is created inside a FormType, and a controller handles the submission of the form successfully. However, every time I submit the form to this controller and I do a print_r or var_dump(), the upload field isn't included as part of the params of the POST request. When I use $file = $request->files->get('estimateUpload'); and var_dump() that it will only ever return NULL.

Here is the formType that I am using:

<?php

namespace App\Form;

use App\Entity\IhcVehicleDamageMatrix;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\File;

class IhcVehicleDamageEntryType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('id')
            ->add('incidentId')
            ->add('vehicleDamageId')
            ->add('damageType')
            ->add('description')
            ->add('wheelTyreDamage')
            ->add('tyreAge')
            ->add('tyreDotCode')
            ->add('treadDepth')
            ->add('renumerationCost')
            ->add('itemAge')
            ->add('created')
            ->add('modified')
            ->add('estimateUpload', FileType::class, [
                'required' => false
            ])
        ;
    }

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

In the view file this is how I am using the upload field:

{{ form_start(damageForm, {'action': path('forms_ihc_damage_details_submitform'), 'method': 'POST', 'attr': {'id': 'ihcFormDamageDetails', 'enctype': 'multipart/form-data'}}) }}
{{ form_row(damageForm._token) }}
                    <tr>
                        <th>Upload Estimate</th>
                        <td>
                            {{ form_widget(damageForm.estimateUpload) }}
                            <small>{{ form_help(damageForm.estimateUpload) }}</small>
                            <div class="form-error">
                                {{ form_errors(damageForm.estimateUpload) }}
                            </div>
                        </td>
                    </tr>
{{ form_errors(damageForm) }}
{{ form_end(damageForm, {'render_rest': false}) }}

And in the controller, this is how I am getting the form data:

    public function vehicleDamageForm(Request $request)
    {
        // Get Form Details
        $formdet = $request->get('ihc_vehicle_damage_entry');

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

        $file = $request->files->get('estimateUpload');
        var_dump($file);
}

How to redirect with an addFlash from a class that implements Symfony 4 UserCheckerInterface

$
0
0

I need your help. I set up an account activation system by email address that works very well.

Currently, I manage to refuse access but I do not know how to do a redirection with an addFlash and not display the 403 pass.

You'll have an idea of ​​how I could do that?

Here is how I deny access, I use the UserChecker.

class UserChecker implements UserCheckerInterface
{
    /**
     * Checks the user account before authentication.
     *
     * @param UserInterface $user
     * @return RedirectResponse
     */
    public function checkPreAuth(UserInterface $user)
    {
        if ($user->getIsActivated() === null || $user->getIsActivated() === false) {
            throw new HttpException(403, 'Access denied.');
        } else {
            return new RedirectResponse('account_login');
        }
    }

Doctrine only saves one of many manyToOne relations

$
0
0

There are two entities related by ManyToOne relation: A 'Block' can have many 'Button', and 'Button' can be in one block. I have a form system where I can add multiple Button type for a block. The problem is that only one button gets saved to the database when trying to save multiple.

But when i save one, I can go back and save multiple at once. I am not able to understand this behavior.

Block:

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

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Block\Button", mappedBy="block", 
        orphanRemoval=true, cascade={"persist"})
     */
    private $buttons;



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

    /**
     * @return Collection|Button[]
     */
    public function getButtons(): Collection
    {
        return $this->buttons;
    }

    public function addButton(Button $button): self
    {
        if (!$this->buttons->contains($button)) {
            $this->buttons[] = $button;
            $button->setBlock($this);
        }

        return $this;
    }

    public function removeButton(Button $button): self
    {
        if ($this->buttons->contains($button)) {
            $this->buttons->removeElement($button);
            // set the owning side to null (unless already changed)
            if ($button->getBlock() === $this) {
                $button->setBlock(null);
            }
        }

        return $this;
    }   
}

Button:

/**
 * @ORM\Entity(repositoryClass="App\Repository\Block\ButtonRepository")
 * @ORM\Table(name="block_button")
 */
class Button
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Block", inversedBy="buttons")
     * @ORM\JoinColumn(nullable=false)
     */
    private $block;

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

    public function getBlock(): ?Block
    {
        return $this->block;
    }

    public function setBlock(?Block $block): self
    {
        $this->block = $block;

        return $this;
    }
 }

Following is the form type:

BlockType

class BlockType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('buttons', CollectionType::class, [
                'entry_type' => BlockButtonType::class,
                'entry_options' => ['label' => false],
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false,
                'help' => '<a data-collection="add" class="btn btn-info btn-sm" href="#">Add Button</a>',
                'help_html' => true,
                'attr' => [
                    'data-field' => 'buttons'
                ]
            ])
    }

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

BlockButtonType

class BlockButtonType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('label');
    }

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

Active /inactive icon function in symfony [closed]

$
0
0

I have a product list which contains product id,name and actions (ACTIVE,INACTIVE & UPDATE)all the 3 are material-icons.If i click on active icon the status of the product should change to 1 (when ACTIVE)..and if i click on to inactive action the status should be 0 instead of 1(updating database value.)How it is implemented in Symfony?Can anyone please help to solve this.

Doctrine extensions same translation for different locales not stored

$
0
0

In a Symfony project, when I try to store a translation for a locale different as the default locale but with the same translation, this one isn't stored in the database.

There is an treatment example to store the translations :

foreach($seasons as $season)
{

    foreach($locales as $locale)
    {

        if($locale)
        {

            $translation = $seasonsForm['season_' . $season->getId() . '_' . $locale]->getData();

            if ($translation) 
            {

                $season->setSeason($translation);
                $season->setTranslatableLocale($locale);

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

            }

        }

    }

}

By example, if the season for "en" locale is "High" and the season for "fr" locale is "Haute", the translations are successfully stored in the database. However, if the season for "en" locale is "Top" and the season for "fr" locale is "Top", the "fr" translation isn't stored in the database.

PHP Warning: Module 'MapScript' already loaded in Unknown on line 0 [closed]

$
0
0

I just start working with symfony4 and a long install of symfony i have the warning "PHP Warning: Module 'MapScript' already loaded in Unknown on line 0" i dont kow what the problem exactly howhever i cant generate entity and controller it show the same warning PHP Warning: Module 'MapScript' already loaded in Unknown on line 0 please i need your hope


react native can't subscribe to mercure backend notifications

$
0
0

I'm working on a notifications system with React Native and Symfony. I configured Mercure with docker to handle front subscription to real time updates : the .env file :

###> symfony/mercure-bundle ###
# See https://symfony.com/doc/current/mercure.html#configuration
MERCURE_PUBLISH_URL=http://mercure.localhost/.well-known/mercure
# The default token is signed with the secret key: !ChangeMe!
MERCURE_JWT_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXJjdXJlIjp7InB1Ymxpc2giOlsiKiJdfX0.9-LscFk3QfdDtZ4nyg6BiH4_qDm6pbYHydURBMsDgEc
###< symfony/mercure-bundle ###

mercure.yaml:

mercure:
    enable_profiler: '%kernel.debug%'
    hubs:
        default:
            url: '%env(MERCURE_PUBLISH_URL)%'
            jwt: '%env(MERCURE_JWT_TOKEN)%'

I created a Notifications component in my React Native application and i use the code in the official documentation of symfony mercure: https://symfony.com/doc/4.3/mercure.html#subscribing Notifications.js code :

import React, { Component } from 'react';
import { View, Text } from 'react-native';

export default class Notifications extends Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }

    componentDidMount() {
        const url = new URL('http://mercure.localhost/.well-known/mercure');
        url.searchParams.append('topic', 'http://dev.api.partage-mandats.proprietes-privees.com/mandate_shares/{id}');

        url.searchParams.append('topic', 'http://example.com/books/1');
        const eventSource = new EventSource(url);

        eventSource.onmessage = e => console.log(e);
    }

    render() {
        return (
            <View>
                <Text> Notifications </Text>
            </View>
        );
    }
}

I tested with Postan and i get a valid response : Postman test mercure

And i tried the javaScript code in a html file for testing :

<script type="text/javascript">

const url = new URL('http://mercure.localhost/.well-known/mercure');
url.searchParams.append('topic', 'http://dev.api.partage-mandats.proprietes-privees.com/mandate_shares/{id}');

url.searchParams.append('topic', 'http://example.com/books/1');
const eventSource = new EventSource(url);

eventSource.onmessage = e => console.log(e); 
</script>
</html>

And i get a real time response when i run request with Postman : console log in html file My problem is that URL, searchParams and eventSource are not compatible with react native. How can i transform this javaScript code to react native valid code ? I tried to install some librairies : whatwg-url, buffer, react-native-event-source and my current code is :

import React, { Component } from 'react';
import { View, Text } from 'react-native';

import { URL, URLSearchParams } from 'whatwg-url';
import { Buffer } from 'buffer';
import RNEventSource from 'react-native-event-source';

export default class Notifications extends Component {
  constructor(props) {
    super(props);
    this.state = {
    };
  }

  componentDidMount() {
    global.Buffer = Buffer;
    global.URL = URL;
    global.URLSearchParams = URLSearchParams;
    global.EventSource = RNEventSource;

    const url = new global.URL('http://mercure.localhost/.well-known/mercure');
    url.global.URLSearchParams.append('topic', 'http://dev.api.partage-mandats.proprietes-privees.com/mandate_shares/{id}');

    url.global.URLSearchParams.append('topic', 'http://example.com/books/1');
    const eventSource = new global.EventSource(url);

    eventSource.onmessage = e => console.log(e); 
  }

  render() {
    return (
      <View>
        <Text> Notifications </Text>
      </View>
    );
  }
}

I got this error : undefined is not an object (evaluating 'url.global.URLSearchParams')

No logging in production environment when running Console commands

$
0
0

When running Console commands in prod mode, I need to log Doctrine related debug messages. Everything works fine in dev with the following configuration, so I assume I forgot something to set when in prod?

My system:

  • PHP 7.3
  • Symfony 4.4
  • Monolog
  • Doctrine

How do I run commands:

I run commands in prod as either

php bin/console app:scrape --env=prod

or

# set APP_ENV=prod in .env.local before
php bin/console app:scrape

Both result in no logs. I am sure, I run prod, because Symfony creates var/cache/prod every time.

Monolog configuration file: config/package/prod/monolog.yaml

This file configures Monolog in prod environment.

monolog:
    handlers:
        main:
            type: fingers_crossed
            action_level: debug
            handler: nested
            excluded_http_codes: [404, 405]
        nested:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.log"
            level: debug
        deprecation:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.deprecations.log"
        deprecation_filter:
            type: filter
            handler: deprecation
            max_level: info
            channels: ["php"]
        doctrine:
            level: debug
            type: stream
            path: "%kernel.logs_dir%/doctrine/info.log"
            channels: ["doctrine"]

Output of APP_ENV=prod bin/console debug:config monolog:

https://gist.github.com/k00ni/419f62941e496a376be35a0d06e44131

How to get Symfony 4 dependency injection working with two different use case scenarios?

$
0
0

We're trying to find the best way to implement dependency injection in a Symfony project with a quite specific problematic.

At user level, our application rely on an "Account" doctrine entity which is loaded with the help of the HTTP_HOST global against a domain property (multi-domain application). Going on the domain example.domain.tld will load the matching entity and settings.

At the devops level, we also need to do batch work with CLI scripts on many accounts at the same time.

The question we are facing is how to write services that will be compatible with both needs?

Let's illustrate this with a simplified example. For the user level we have this and everything works great:

Controller/FileController.php

    public function new(Request $request, FileManager $fileManager): Response
    {
        ...
        $fileManager->addFile($file);
        ...

    }

Service/FileManager.php

    public function __construct(AccountFactory $account)
    {
        $this->account = $account;
    }

Service/AccountFactory.php

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

    public function createAccount()
    {
        $httpHost = $this->requestStack->getCurrentRequest()->server->get('HTTP_HOST');
        $account = $this->accountRepository->findOneBy(['domain' => $httpHost]);

        if (!$account) {
            throw $this->createNotFoundException(sprintf('No matching account for given host %s', $httpHost));
        }

        return $account;
    }

Now if we wanted to write the following console command, it would fail because the FileManager is only accepting an AccountFactory and not the Account Entity.

$accounts = $accountRepository->findAll();
foreach ($accounts as $account) {
    $fileManager = new FileManager($account);
    $fileManager->addFile($file);
}

We could tweak in the AccountFactory but this would feel wrong... In reality this is even worse because the Account dependency is deeper in services.

Does anyone have an idea how to make this properly ?

Delete collection null value entries from Database in sonata admin with symfony 4

$
0
0

I want to delete collection entry from database. When I will delete any collection from sonata admin collection then I want to that entry deleted from database.

->add('account_person_type', CollectionType::class, [
      'label' => 'Account Person Type',
      'required' => true,
      'by_reference' => false,
      'type_options' => []
 ], ['edit' => 'inline', 'inline' => 'table', 'sortable' => 'position',]
)

How to automatically call a service in symfony 4

$
0
0

I have a service in my project

services:
exemple.annotation_reader:
    class: App\Annotation\ModelAnnotationReader
    public: true
    arguments: ["@annotations.reader"]
    calls:
        - [getAnnotation]

And I want call the methode "getAnnotation" without adding this line in my controller

$this->get('exemple.annotation_reader')->getAnnotation();

And there is my function getAnnotation

public function getAnnotation(){
    $reflClass = new \ReflectionMethod('App\Manager\BigDataTestManager', 'getAllData');
    $classAnnotations = $this->reader->getMethodAnnotations($reflClass);

    foreach ($classAnnotations AS $annot) {
        if ($annot instanceof ModelAnnotation) {
            print_r($annot);
        }
    }
}

the goal of my project is to create a custom annotation in symfony 4, I want show the annotation's parameters

/**
 * @Model(
 *     namespace="App\Model\Exemple",
 *     version=50,
 *     types={"json","xml"}
 * )
 */

so I want create a service who call a function automatically when there is an annotation on a function.

Viewing all 3924 articles
Browse latest View live


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