我的magento版本是2.1.0。如何获得所有有效的运送方式清单?
任何帮助将不胜感激
我的magento版本是2.1.0。如何获得所有有效的运送方式清单?
任何帮助将不胜感激
Answers:
或者,您可以使用Magento \ Shipping \ Model \ Config \ Source \ Allmethods做到这一点!
除了回答keyur shah
您可以使用以下代码获得所有有效的运输:
protected $scopeConfig;
protected $shipconfig;
public function __construct(
\Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
\Magento\Shipping\Model\Config $shipconfig
) {
$this->shipconfig=$shipconfig;
$this->scopeConfig = $scopeConfig;
}
public function getShippingMethods(){
$activeCarriers = $this->shipconfig->getActiveCarriers();
$storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
foreach($activeCarriers as $carrierCode => $carrierModel)
{
$options = array();
if( $carrierMethods = $carrierModel->getAllowedMethods() )
{
foreach ($carrierMethods as $methodCode => $method)
{
$code= $carrierCode.'_'.$methodCode;
$options[]=array('value'=>$code,'label'=>$method);
}
$carrierTitle =$this->scopeConfig->getValue('carriers/'.$carrierCode.'/title');
}
$methods[]=array('value'=>$options,'label'=>$carrierTitle);
}
return $methods;
}
使用下面的代码,您将在phtml文件中获得载体列表。这$block
与我们定义了上述功能的块有关
<?php $carriers = $block->getShippingMethods(); ?>
<select name="shipping" class="control-select">
<option value=""><?php /* @escapeNotVerified */ echo __('Please Select'); ?></option>
<?php foreach ($carriers as $carrier): ?>
<optgroup label="<?php /* @escapeNotVerified */ echo $carrier['label'] ?>">
<?php foreach ($carrier['value'] as $child): ?>
<option value="<?php /* @escapeNotVerified */ echo $child['value'] ?>">
<?php /* @escapeNotVerified */ echo $child['label']; ?>
</option>
<?php endforeach; ?>
</optgroup>
<?php endforeach; ?>
</select>
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$activeShipping = $objectManager->create('Magento\Shipping\Model\Config')->getActiveCarriers();
注意:我反对使用$ objectManager直接加载对象,为了产生更好的影响,您可以将其注入到构造函数中。我刚刚给出了示例,您如何实现它。`
更好的方法
protected $_shippingConfig;
public function __construct(
\Magento\Shipping\Model\Config $shippingConfig
) {
$this->_shippingConfig=$shippingConfig
}
现在,您可以通过以下方式获取所有有效的送货方式
$this->_shippingConfig->getActiveCarriers();
如果要store
特定,active shipping method
则可以在中传递$store
对象parameter
,如下面的方法所示,accept $store
参数
public function getActiveCarriers($store = null)
{
$carriers = [];
$config = $this->_scopeConfig->getValue('carriers', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store);
foreach (array_keys($config) as $carrierCode) {
if ($this->_scopeConfig->isSetFlag('carriers/' . $carrierCode . '/active', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $store)) {
$carrierModel = $this->_carrierFactory->create($carrierCode, $store);
if ($carrierModel) {
$carriers[$carrierCode] = $carrierModel;
}
}
}
return $carriers;
}