duanchazhou6779 2012-06-16 08:58
浏览 46

Symfony2 Sonata Admin访问容器

I have an entity with a required active user field so I need to add the active user's name in configureFormFields():

class DokumentAdmin extends Admin
{    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
                ->add('email')
                 ...
                ->add('user_name',null,array('required' => true, 'data' => "THIS IS A LOGGED ADMIN NAME"))
        ;
    }

I tried to use a listener,

public function prePersist(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        if ($entity instanceof Dokument) {
         //set user name

        }
    }

but I don't now how use the container object here.

  • 写回答

3条回答 默认 最新

  • dongshi8359 2012-09-01 00:36
    关注

    I have the same issue. I need to parse some parameters from my config.yml but it fails.

    As solution, you can inject the container to your admin class, but this is not recommanded. You should inject only services or parameters you need.

    How to do ?

    you should use the setter injection instead of construct injection.

    Here is an example of injecting a parameters in snata Admin Class:

    when yu define your admin service, just add a call like this:

    <service id="skonsoft.znata.admin.keyword" class="%skonsoft.znata.admin.keyword.class%">
            <tag name="sonata.admin" manager_type="orm" group="Keyword" label="Keyword"/>
            <argument />
            <argument>%skonsoft.znata.admin.keyword.entity.class%</argument>
            <argument>SonataAdminBundle:CRUD</argument>
            <call method="setTranslationDomain">
                <argument>SkonsoftZnataBundle</argument>
            </call>
    
             <!-- here you inject your parameter using setter injection -->
            <call method="setEnabledLocales">
                <argument>%skonsoft_znata.locales%</argument>
            </call>
        </service>
    

    After, just add a method called setEnabledLocales inside your admin class that like

    public function setEnabledLocales($locales){
        $this->enabedLocales = $locales;
    }
    

    Don't forget to add $enabedLocales as property in your admin class.

    Finally you can use this property.

    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本