描述在多步骤表单中跨页引用值的方法
解读
国内企业在 Drupal 项目中常把“多步骤表单”拆成两类场景:
- 传统 page callback 多步,如政府办事大厅的“企业注册”流程,每一步都是独立路由,需把上一步数据带到下一步;
- 单页 wizard 多步,如银行信用卡申请,前端用 React/Vue 渲染,后端只暴露
/api/wizard/{step}接口,仍需把前面步骤的字段值暂存到某处。
面试官真正想验证的是:
- 你是否理解 Drupal 表单 API 的状态生命周期;
- 能否在不破坏“配置可导出、代码可回滚”原则的前提下,把值安全地跨请求传递;
- 对高并发、水平部署、Headless 场景有没有兜底方案。
因此,回答必须覆盖“存储位置、序列化方式、权限校验、缓存失效、回滚策略”五个维度,并给出可落地的代码骨架。
知识点
- Form API 的
$form_state与cache子系统:Drupal\Core\Form\FormStateInterface只能在当前请求内生效;- 跨请求需借助
\Drupal\Core\TempStore\SharedTempStore(私有临时存储)或\Drupal\Core\Cache\CacheBackendInterface(可标记缓存)。
- TempStore 的命名空间与所有权:
- 默认用
tempstore.private服务,键格式{owner}.{collection}.{key},owner 为当前用户 ID,collection 建议用multistep_{form_id}; - 生命周期默认 7 天,可在
settings.php里改$settings['tempstore_max_lifetime']。
- 默认用
- 水平部署与 Redis:
- 若用 Redis 做默认缓存,TempStore 自动落到 Redis,无需改代码;
- 需保证
cache_tags带上user:{uid},以便用户登出或权限变更时批量失效。
- Headless 场景:
- 前端不再发
form_build_id,而是带jwt或oauth2访问令牌; - 后端把
tempstore_key放进 jwt 的private_claims,避免 Cookie 跨域问题。
- 前端不再发
- 安全兜底:
- 每次取 TempStore 后,用
\Drupal\Core\Access\CsrfTokenGenerator校验X-CSRF-Token; - 敏感字段(如身份证号)先
\Drupal\Component\Utility\Crypt::hmacBase64再落盘,密钥放$settings['hash_salt']。
- 每次取 TempStore 后,用
答案
下面给出一套在“传统多路由”场景下可直接落地的方案,兼顾“配置即代码”与“水平扩展”。
-
定义路由与表单 ID
在my_module.routing.yml里声明三步路由:my_module.multistep.step1: path: '/apply/step1' defaults: _form: '\Drupal\my_module\Form\ApplyStep1Form' _title: '填写企业信息' requirements: _custom_access: '\Drupal\my_module\Access\MultiStepAccess::access' my_module.multistep.step2: path: '/apply/step2' defaults: _form: '\Drupal\my_module\Form\ApplyStep2Form' _title: '上传材料' requirements: _custom_access: '\Drupal\my_module\Access\MultiStepAccess::access' my_module.multistep.step3: path: '/apply/step3' defaults: _form: '\Drupal\my_module\Form\ApplyStep3Form' _title: '确认提交' requirements: _custom_access: '\Drupal\my_module\Access\MultiStepAccess::access' -
抽象一个基类,统一处理 TempStore
namespace Drupal\my_module\Form; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\TempStore\SharedTempStoreFactory; use Symfony\Component\DependencyInjection\ContainerInterface; abstract class ApplyBaseForm extends FormBase { protected SharedTempStoreFactory $tempStoreFactory; protected string $storeKey = 'my_module_apply'; public function __construct(SharedTempStoreFactory $temp_store_factory) { $this->tempStoreFactory = $temp_store_factory; } public static function create(ContainerInterface $container) { return new static($container->get('tempstore.private')); } protected function getStore() { // collection 用表单机名,owner 用当前用户 ID return $this->tempStoreFactory->get('multistep_apply'); } protected function setStepValue(string $step, array $values): void { $store = $this->getStore(); $all = $store->get($this->storeKey) ?? []; $all[$step] = $values; $store->set($this->storeKey, $all); } protected function getAllSteps(): array { return $this->getStore()->get($this->storeKey) ?? []; } protected function deleteStore(): void { $this->getStore()->delete($this->storeKey); } } -
Step1 表单把值写库
class ApplyStep1Form extends ApplyBaseForm { public function getFormId() { return 'apply_step1'; } public function buildForm(array $form, FormStateInterface $form_state) { $form['company_name'] = [ '#type' => 'textfield', '#title' => '企业名称', '#required' => TRUE, ]; $form['actions']['submit'] = [ '#type' => 'submit', '#value' => '下一步', ]; return $form; } public function submitForm(array &$form, FormStateInterface $form_state) { $this->setStepValue('step1', [ 'company_name' => $form_state->getValue('company_name'), ]); $form_state->setRedirect('my_module.multistep.step2'); } } -
Step2 表单读取上一步并继续追加
class ApplyStep2Form extends ApplyBaseForm { public function getFormId() { return 'apply_step2'; } public function buildForm(array $form, FormStateInterface $form_state) { // 跨页引用:把 step1 数据注入表单,供展示或校验 $all = $this->getAllSteps(); $form['step1_company'] = [ '#type' => 'item', '#title' => '企业名称', '#markup' => $all['step1']['company_name'] ?? '', ]; $form['upload'] = [ '#type' => 'managed_file', '#title' => '营业执照', '#upload_location' => 'private://apply/', '#required' => TRUE, ]; $form['actions']['submit'] = [ '#type' => 'submit', '#value' => '下一步', ]; return $form; } public function submitForm(array &$form, FormStateInterface $form_state) { $all = $this->getAllSteps(); $all['step2'] = ['fid' => $form_state->getValue('upload')[0]]; $this->setStepValue('step2', $all['step2']); $form_state->setRedirect('my_module.multistep.step3'); } } -
Step3 汇总并落库,清理 TempStore
class ApplyStep3Form extends ApplyBaseForm { public function getFormId() { return 'apply_step3'; } public function buildForm(array $form, FormStateInterface $form_state) { $all = $this->getAllSteps(); // 展示确认信息 $form['summary'] = [ '#theme' => 'item_list', '#items' => [ '企业名称:' . $all['step1']['company_name'], '营业执照文件 ID:' . $all['step2']['fid'], ], ]; $form['actions']['submit'] = [ '#type' => 'submit', '#value' => '提交', ]; return $form; } public function submitForm(array &$form, FormStateInterface $form_state) { $all = $this->getAllSteps(); // 事务落库 $entity = \Drupal::entityTypeManager() ->getStorage('apply_data') ->create([ 'name' => $all['step1']['company_name'], 'file_id' => $all['step2']['fid'], 'uid' => \Drupal::currentUser()->id(), ]); $entity->save(); // 清理临时存储 $this->deleteStore(); $this->messenger()->addMessage('申请已提交,记录 ID:' . $entity->id()); $form_state->setRedirect('<front>'); } } -
访问控制与缓存失效
namespace Drupal\my_module\Access; use Drupal\Core\Access\AccessResult; use Drupal\Core\Session\AccountInterface; use Drupal\Core\TempStore\SharedTempStoreFactory; class MultiStepAccess { public function access(AccountInterface $account) { // 只允许登录用户 if ($account->isAnonymous()) { return AccessResult::forbidden('请先登录')->setCacheMaxAge(0); } // 若需要额外权限,可再校验角色 return AccessResult::allowed()->setCacheMaxAge(0); } }在
my_module.module里加hook_user_logout(),用户退出时把cache_taguser:{uid}失效,防止 TempStore 被他人复用。 -
自动化测试覆盖
用BrowserTestBase模拟三步提交,断言:- Step2 页面能正确显示 Step1 输入的企业名称;
- 提交 Step3 后数据库存在记录且 TempStore 被清空;
- 并发两个浏览器窗口,以同一用户登录,A 窗口走完 Step1,B 窗口立即请求 Step2,数据不串号。
拓展思考
- 如果前端完全 Headless,TempStore 的 key 不再依赖 PHP Session,而是放在 JWT 的
jti声明里,后端需自定义TempStoreOwnershipInterface,把 owner 从uid换成jti,并配套写一个KernelEvents::REQUEST监听器,提前解析 JWT 注入到Drupal::service('current_user')的临时对象里。 - 当并发量达到 5 万 QPS,Redis 内存吃紧,可把“非敏感字段”转存到 Cookie,用
libsodium密封,减少 Redis 网络 IO;敏感字段仍走 TempStore,并设置volatile-lru淘汰策略。 - 若客户要求“断点续填”,即用户关闭浏览器三天后回来仍能继续,需把 TempStore 生命周期延长到 30 天,并写一个
drush my-module:cleanup-temp定时任务,把超过 30 天且未提交的垃圾数据批量删除,避免 Redis 膨胀。