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
相关产品推荐
相关产品推荐

