【问题标题】:Drupal 8 subscribe to an event from inside blockDrupal 8 从块内订阅事件
【发布时间】:2017-08-09 15:25:20
【问题描述】:

我目前正在尝试围绕 Drupal 8 模块开发最佳实践展开思考。我要做的就是在用户可以输入电子邮件地址的页面上创建一个简单的表单Demoform。当表单被提交时,我想发送一个事件demo_form.save。我还需要一个块,然后在块中显示用户的电子邮件地址(让我们说第二个侧边栏)。我之前已经实现了EventSubscriber 作为测试,因此事件得到正确调度等,我还订阅了事件(但如何获取块内的信息)现在我的问题是:这个工作流的最佳实践是什么:

文件 DemoForm.php

class DemoForm extends ConfigFormBase {
  ...
  $event = $dispatcher->dispatch('demo_form.save', $e);
  ...
}

文件 DemoEventSubscriber.php

class DemoEventSubscriber implements EventSubscriberInterface {
  static function getSubscribedEvents() {
    $events['demo_form.save'][] = array('onConfigSave', 0);  
    return $events;
  }
  public function onConfigSave($event) {
    ...
  }

}

这很有效,我可以从 DemoEventSubscriber 类中的表单访问输入,并用它做任何我想做的事情。 但现在我想在块标记中显示电子邮件地址。这应该怎么做最好?

文件 DemoBlock.php

class DemoBlock extends BlockBase {
 public function build() {
  // here return markup with email address from form
 }
}

如何结合事件订阅者和块标记? Blockbase 本身可以实现 EventSubscriberInterface 并独立于 DemoEventSubscriber.php 吗?还是我需要注册一个传输表单数据的服务,然后在块的build() 函数中访问该服务?还是我错过了另一种方式?

感谢您的任何意见。

【问题讨论】:

    标签: drupal-8


    【解决方案1】:

    我不确定您需要该事件做什么,但要调度该事件,请使用您已在 DemoForm 类的 submitForm() 函数中显示的代码。

    因为您使用的是 ConfigFormBase,我假设您希望将提交的电子邮件地址存储在 config 中,使用 config form documentation 中的代码:

      /** 
       * {@inheritdoc}
       */
      public function submitForm(array &$form, FormStateInterface $form_state) {
        // Retrieve the configuration
        $this->config('mymodule.settings')
          // Set the submitted configuration setting
          ->set('email', $form_state->getValue('email'))
          ->save();
    
        // Assuming you have injected the dispatcher.
        $event = $this->dispatcher->dispatch('demo_form.save', $e);
    
        parent::submitForm($form, $form_state);
      }
    

    在你的块中,你可以访问配置,例如使用静态包装器或注入服务Simple Configuration API

    $config = \Drupal::config('mymodule.settings');
    $message = $config->get('email');
    

    请注意,您始终只能设置一个电子邮件地址。我不知道这是否是你的目的。如果您想收集多封电子邮件,那么您应该将它们存储在数据库中而不是配置中。

    【讨论】:

    • 谢谢,确实如此,使用 config 就可以了。但是,假设我不想使用配置,那么您认为获取块内电子邮件地址的唯一方法是将其存储在数据库中?
    • 持久存储它的唯一方法是在数据库中,是的。还有 State API,您可以使用它来存储状态信息。如果您将电子邮件保存在那里,它可能会显示在块中,直到状态被清除。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    相关资源
    最近更新 更多