我目前正试图围绕Drupal 8模块开发最佳实践。我试图做的就是在用户可以输入电子邮件地址的页面上使用简单的表单Demoform
。表单提交后,我想发送一个事件demo_form.save
。此外,我需要一个块,然后在块中显示用户的电子邮件地址(让我们再说侧边栏)。我之前已经实现了一个EventSubscriber
作为测试,所以事件得到了适当的调度等等我也订阅了这个事件(但是如何获取一个块内的信息)现在我的问题:什么' s此工作流程的最佳实践:
File DemoForm.php
class DemoForm extends ConfigFormBase {
...
$event = $dispatcher->dispatch('demo_form.save', $e);
...
}
File 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
}
}
如何组合eventsubscriber和块标记? Blockbase
本身可以实现EventSubscriberInterface
并独立于DemoEventSubscriber.php
吗?或者我是否需要注册传输表单数据的服务,然后访问块build()
功能中的服务?或者还有另一种我失踪的方式吗?
感谢您的任何意见。
答案 0 :(得分:1)
我不确定您需要该事件,但是为了调度该事件,请使用您已经在DemoForm类的submitForm()函数中显示的代码。
因为您使用的是ConfigFormBase,我假设您要将提交的电子邮件地址存储在配置中,请使用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');
请注意,使用此功能,您始终只能设置一个电子邮件地址。我不知道这是不是你的目的。如果您想收集多封电子邮件,那么您应该将它们存储在数据库中,而不是存储在配置中。