You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在模块的hook_webform_handler_invoke_post_save_alter中获取remote post handler返回的响应

获取Remote Post Handler响应的解决方案

Webform的RemotePost类型handler会自动将请求执行后的响应存储在自身属性中,你只需在钩子内先校验handler类型,再调用内置方法即可获取响应内容,修改后的实现代码如下:

function hook_webform_handler_invoke_post_save_alter(\Drupal\webform\Plugin\WebformHandlerInterface $handler, array &$args) {
 $webform = $handler->getWebform();
 $webform_submission = $handler->getWebformSubmission();
 $webform_id = $webform->id();
 $handler_id = $handler->getHandlerId();
 // 匹配指定webform、handler,同时校验handler为远程提交类型
 if ($webform_id == 'webform_id' && $handler_id == 'handler_id' && $handler instanceof \Drupal\webform\Plugin\WebformHandler\RemotePostWebformHandler) {
  // 获取远程请求返回的响应对象,请求失败时返回NULL
  $response = $handler->getResponse();
  
  if (!empty($response)) {
    // 获取响应状态码
    $status_code = $response->getStatusCode();
    // 读取响应体内容,需转为字符串格式
    $response_content = (string) $response->getBody();
    // 获取全部响应头
    $response_headers = $response->getHeaders();
    
    // 此处填写你的业务逻辑,例如记录日志、将响应内容存入提交记录等
    \Drupal::logger('custom_webform')->info('远程提交响应:@content | 状态码:@code', [
      '@content' => $response_content,
      '@code' => $status_code,
    ]);
  } else {
    // 远程请求发送失败的处理逻辑
    \Drupal::logger('custom_webform')->error('远程提交请求发送失败');
  }
 }
}

注意事项

  • 请将代码中的webform_id替换为你的目标Webform的机器名,handler_id替换为你创建的Remote Post handler的机器名
  • 若响应为JSON格式,可使用json_decode($response_content, TRUE)将响应内容转为数组处理
  • 请避免直接打印二进制类型的响应内容,防止出现乱码或异常报错

内容的提问来源于stack exchange,提问作者Arif

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 04:36:07