PrestaShop 1.7获取结账当前步骤 区分配送/账单地址州限制方法
实现思路评估
你原本想通过结账步骤区分地址类型的思路可行,但稳定性较差,更推荐直接通过地址类型判断的实现方案,适用场景更全面。
CheckoutProcess方法调用方式
如果你仍要使用该思路,可通过PrestaShop的Symfony服务容器获取CheckoutProcess实例,代码示例如下:
public function getFormat() { $format = parent::getFormat(); // 仅在结账流程下执行判断 if (\PrestaShop\PrestaShop\Adapter\SymfonyContainer::getInstance()->has('checkout.process')) { $checkoutProcess = \PrestaShop\PrestaShop\Adapter\SymfonyContainer::getInstance()->get('checkout.process'); $currentStep = $checkoutProcess->getCurrentStep(); // 判断当前步骤为配送地址步骤时才限制州选项 if ($currentStep->getIdentifier() === 'delivery-address') { $format['id_state']->setAvailableValues( [999 => 'CustomState'], ); } } return $format; }
注意:该方案仅在结账流程下生效,用户在个人中心新增/编辑配送地址时不会触发限制,存在逻辑漏洞,且自定义结账步骤后可能出现标识符不匹配的问题。
更优解决方案
直接通过地址类型判断是否限制州选项,不需要依赖结账流程,覆盖所有使用场景,代码示例如下:
public function getFormat() { $format = parent::getFormat(); // 仅当为配送地址时限制州选项 if ($this->getAddressType() === 'delivery') { $format['id_state']->setAvailableValues( [999 => 'CustomState'], ); } return $format; }
如果部分版本无法通过getAddressType()获取类型,可通过当前地址和购物车配送地址ID匹配的方式判断:
public function getFormat() { $format = parent::getFormat(); $context = \Context::getContext(); // 购物车存在且当前格式化的地址为配送地址时,限制州选项 if (isset($context->cart) && $this->address->id == $context->cart->id_address_delivery) { $format['id_state']->setAvailableValues( [999 => 'CustomState'], ); } return $format; }
该方案满足需求:配送地址仅可选指定州,账单地址保留全球任意国家、对应州可选的原有逻辑,且兼容所有地址编辑场景。
内容的提问来源于stack exchange,提问作者rosuandreimihai
相关产品推荐
相关产品推荐

