我对Drupal非常陌生,我被要求创建带有submit按钮的表单和一个使用表单的值向API发出get请求的服务。API是一个简单的API,用户可以输入一个国家,它将返回一个响应,并从那个国家返回正确的问候。
这是我的路由文件。
hello_world.salutation:
path: '/hello'
defaults:
_controller: Drupal\hello_world\Controller\HelloWorldSalutation::salutation
_form: Drupal\hello_world\Form\GreetingForm
_title: 'Get a greeting from a different language'
requirements:
_permission: 'administer site configuration'第一个问题是我不知道如何在同一个路由中创建表单和控制器,第二个问题是,当用户输入submit时,我不知道如何调用该服务。
这是服务文件。
services:
hello_world.salutation:
class: Drupal\hello_world\HelloWorldSalutation
arguments: [ '@config.factory' ,'@tempstore.private']
cache.nameofbin:
class: Drupal\Core\Cache\CacheBackendInterface
tags:
- { name: cache.bin }
factory: [ '@cache_factory', 'get' ]
arguments: [ nameofbin ]为了保持简单,我将跳过GreetingFrom类中的一些行,但如果需要,我可以添加它们。
下面是来自submitForm类的GreetingForm函数。这样做的目的是将输入放在一个全局的临时存储中,这样我就可以从控制器中访问这些值了。
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),
];
}发布于 2020-12-13 22:22:10
您正在尝试同时完成四件事情(表单、服务、与API的集成、缓存),因此您看不到问题所在。相反,将其分解为不同的步骤。
首先,编写代码并调试表单。在submit函数中,只需使用表单中的信使服务($this->messenger()->addMessage('this is a test message');)来显示问候的静态值。您应该达到访问/hello并提交表单将显示消息的程度。您可以稍后自定义该消息。先让它起作用。
其次,编写代码并调试您的服务类。我发现在这里使用drush php-script来执行访问您的服务的独立PHP脚本是有用的。这样,您就可以确保您的服务完全按照您的要求执行,并在尝试在表单中使用您的服务之前,了解如何与外部API进行通信。您不需要路由文件中的"_controller“。访问服务的方法是使用\Drupal::service('hello_world.salutation')->salutation()。与其将变量传递给salutation()方法,不如将它们作为参数传递给您的方法。因此,用于drush的独立PHP脚本应该如下所示:
salutation('some string entered on your form');
echo $greetings;将其保存为test.php,然后使用drush php-script test.php执行此操作。
第三,一旦您的服务按您的意愿工作,将您的服务与您的表单集成。您应该能够使用您在第二步中编写的PHP脚本,并将其插入表单submit函数中,几乎保持不变。(作为未来的增强,了解如何将服务注入表单,而不是使用静态\Drupal::service()调用,但这可以等到您完成此工作后才能完成)。
第四,(只有在完成上述工作之后才这样做),检查您对缓存数据的需求,然后在需要时在服务中实现某种类型的缓存。您还没有展示所有的代码,也没有完全解释您在做什么,但是我没有看到任何有理由使用cache.nameofbin或诱饵商店的东西。
发布于 2020-12-14 00:25:54
我建议你看看钩子_表格_更改
表单可以有多个提交函数,最好不要删除原始功能(除非这是您真正想要做的)。
您的代码可能如下所示
function yourmodule_YourFormID_form_alter(&$form, &$form_state) {
// conditions you execute custom code
$form['#submit'][] = 'yourmodule_submit_function';
}https://drupal.stackexchange.com/questions/298802
复制相似问题