You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Symfony表单类型中无法通过事件监听器捕获自定义自动完成事件

自动完成FormType事件监听器无法捕获事件问题

我开发了一个自动完成FormType,希望用户搜索时触发事件,但无法通过事件监听器(非订阅者)捕获该事件。用户输入内容时,Ajax请求会调用searchController分发事件,相关代码如下:

自定义事件代码

class AutoCompleteEvent extends Event {

    /**
     * @Event("Symfony\Contracts\EventDispatcher\Event")
     */
    public const SEARCH = 'autocomplete.search';

    protected $term;

    /**
      * {@inheritdoc}
      */
    public function __construct($term) {
        $this->term = $term;
    }

    /**
      * @returns string term
      */
    public function getTerm() {
        return $this->term;
    }

}

FormType代码

public function buildForm(FormBuilderInterface $builder, array $options):void {

    $this->dispatcher->addListener(AutoCompleteEvent::SEARCH,function(AutoCompleteEvent $event){
        dd("foo",$event);
    });
}

SearchController代码

public function defaultCompleter(Request $request, EntityManagerInterface $em,EventDispatcherInterface $dispatcher,$entityName){

    $event = new AutoCompleteEvent("toto");
    $dispatcher->dispatch($event, AutoCompleteEvent::SEARCH);

}

我原本认为事件监听器在FormType中执行时,能够获取FormType的选项上下文,而事件订阅者不具备这样的执行上下文。但通过分析器观察到:searchController中分发的事件处于孤立状态,FormType中注册的监听器并未被调用。

内容的提问来源于stack exchange,提问作者Chopchop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 18:06:00