2

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.

4

2 回答 2

2

您需要添加

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

到管理员的服务定义(通常在 admin.yml 中)并将方法添加到 *Admin 类

use Symfony\Bridge\Monolog\Logger

....

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

之后您可以照常登录

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

更新

在评论中讨论后,这是在 *Admin 类中获取记录器的正确方法:

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

看起来 SonataAdminBundle 不使用标准的服务注入/解析系统

于 2013-11-14T16:41:08.983 回答
0

也许您必须以这种方式获取记录器对象:

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

并在开始时添加,如果这不起作用:

use Symfony\Component\HttpKernel\Log\LoggerInterface;
于 2013-11-14T16:35:35.763 回答