How to log from FormEventSubscriber in Symfony 5.0?

I’m new in Symfony, and I’m trying to build my application. But I can’t find in documentation how to use Logger in Event Subscriber for a form.

I have monolog.yml:

monolog:
    channels: ["my"]
    handlers:
        my_handler:
            type: stream
            path: "%kernel.project_dir%/log/%kernel.environment%.event.log"
            level: debug
            channels: ["my"]

I have FormType:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email', EmailType::class)
//here some other fields are added
            ->addEventSubscriber(new FormEventSubscriber());
    }

Then, I have pretty dummy FormEventSubscriber:

class FormEventSubscriber implements EventSubscriberInterface
{

    public static function getSubscribedEvents()
    {
        return [
            FormEvents::PRE_SET_DATA => 'onPreSetData',
            FormEvents::PRE_SUBMIT   => 'onPreSubmit',
        ];
    }

    public function onPreSetData(FormEvent $event)
    {
        $user = $event->getData();
        $form = $event->getForm();
    }

    public function onPreSubmit(FormEvent $event)
    {
        $user = $event->getData();
        $form = $event->getForm();
    }
}

Now I must add LoggerInterface to it. I’m trying to insert this code to subscriber:

    private $logger;

    public function __construct(LoggerInterface $myLogger)
    {
        $this->logger = $myLogger;
    }

And then Symfony says that I must add argument to call addEventSubscriber(new FormEventSubscriber()) in FormType.

So how must I do it? When I simply make object of Logger() class in FormType and add it as argument, it logs nothing

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *