2
votes

I've created an admin interface using Symfony and Sonata. For the moment, everything is working fine.

Now, I want to test how the hooks are working, according to this tutorial : http://sonata-project.org/bundles/admin/master/doc/reference/saving_hooks.html For the moment, I just want to test how this method works. What I would like to do, is write a log everything I create an object via my admin interface. Here's the first part of my AdminClass code (working) :

namespace AAA\AdminBundle\Admin;

use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Validator\ErrorElement;

class CompteAdmin extends Admin
{
// Fields to be shown on create/edit forms
protected function configureFormFields(FormMapper $formMapper)
{
    $formMapper
        ->add('prenom')
        ->add('nom')
        ->add('fonction')
    ;
}

And here's the following part (not working) :

public function postPersist($logger)
{
    $logger = $this->get('logger');
    $logger->err('Une erreur est survenue');
}

When trying to add an object, I have this log error :

PHP Fatal error:  Call to undefined method INERIS\AdminBundle\Admin\CompteAdmin::get()

or

PHP Fatal error:  Call to undefined method INERIS\AdminBundle\Entity\Compte::err()

depends if I comment lines or not.

To write into log, Symfony use Monolog. I followed this tutorial http://symfony.com/doc/current/cookbook/logging/monolog.html, but obviously I'm doint it wrong because the $logger should be declared into a controller, not there.

I don't know how to figure out then.

Maybe there is an add missing at the beginning of the AdminClass to enable Monolog. Maybe my function postPersist took the wrong object.

Any tips would be helpful ;)

Edit : Resolved, check the post below.

2

2 Answers

2
votes

You need to add

 calls:
   - [ setLogger, ['%logger%'] ]

to admin's service definition (usually in admin.yml) and add method to *Admin class

use Symfony\Bridge\Monolog\Logger

....

public function setLogger(Logger $logger) {
    $this->logger = $logger;
}

after that you can log as usual

$this->logger->err('Une erreur est survenue');

UPDATE

After discussion in comment's this is the correct way of getting logger in *Admin class:

public function postPersist($logger)
{
    $logger = $this->getConfigurationPool()->getContainer()->get('logger');
    $logger->err('Une erreur est survenue');
}    

Looks like SonataAdminBundle does not uses standard service injection/resolving system

0
votes

maybe you must get the logger object this way:

$logger = $this->getContainer()->get('logger');

and add at the beggining this, if that doesn't work:

use Symfony\Component\HttpKernel\Log\LoggerInterface;