如何在Drupal中按提交后调用服务



我是Drupal的新手,我被要求创建一个带有提交按钮的表单和一个服务,该服务使用表单中的值向API发出get请求。API是一个简单的API,用户可以输入一个国家,它会返回一个带有该国家正确问候语的响应。

这是我的路由文件:

hello_world.salutation:
path: '/hello'
defaults:
_controller: Drupalhello_worldControllerHelloWorldSalutation::salutation
_form: Drupalhello_worldFormGreetingForm
_title: 'Get a greeting from a different language'
requirements:
_permission: 'administer site configuration'

第一个问题是,我不知道如何使表单和控制器处于同一路由中,第二,当用户输入submit时,我不知道如何调用该服务。

这是我的服务文件:

services:
hello_world.salutation:
class: Drupalhello_worldHelloWorldSalutation
arguments: [ '@config.factory' ,'@tempstore.private']
cache.nameofbin:
class: DrupalCoreCacheCacheBackendInterface
tags:
- { name: cache.bin }
factory: [ '@cache_factory', 'get' ]
arguments: [ nameofbin ]

为了简单起见,我会跳过GreetingFrom类中的一些行,但如果需要,我可以添加它们。

这是GreetingForm类中的submitForm函数。这个想法是把输入放在一个全局临时存储中,这样我就可以访问控制器中的值。

public function submitForm(array &$form, FormStateInterface $form_state)
{
$search_str = $form_state->getValue('greeting');
// check the input
$params['items'] = $form_state->getValue('greeting');
// 2. Create a PrivateTempStore object with the collection 'greetingForm_values'.
$tempstore = $this->tempStoreFactory->get('greetingForm_values');
// 3. Store the $params array with the key 'params'.
try {
$tempstore->set('params', $params);
} catch (Exception $error) {
// dump the error for now, read error, --fix this!
dpm($error);
}
}

控制器的问候功能如下:

public function salutation()
{
$tempstore = $this->tempStoreFactory->get('greetingForm_values');
$params = $tempstore->get('params'); // this value should come from the search form
return [
'#markup' => $this->salutation->getGreeting($params),
];
}

非常感谢您的帮助,如果需要,请询问更多信息。

路由文件

在您的用例中,我相信您可以坚持使用Form。请从hello_world.salutation路由中丢弃Controller规范,因为它应该是_form_controller,而不是对于单个路由都是。

服务方法调用

对于您的服务定义,您可以通过以下方式静态调用服务:

$salutation_service = Drupal::service('hello_world.salutation');
$salutation_service->somePublicMethodCall();

或者通过依赖注入,我认为当我看到this->salutation->getGreeting($params)时,你已经在做了?

Form x控制器

从提供的详细信息来看,我真的不知道你为什么需要Controller,但如果你需要重定向到Controller,那么你可以为你的HelloWorldSalutation::salutation()方法创建一个单独的路由,并通过$form_state对象从GreetingForm ::submitForm()重定向到它:

$url = DrupalCoreUrl::fromRoute('hello_world.salutation');
$form_state->setRedirectUrl($url);

最新更新