本文介绍了在 Magento2 中如何从购物车或者订单中获取产品的自定义选项。这里有两个例子:
第一个是使用 ObjectManager:
- 获取当前购物车中产品的自定义选项
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart');
// get cart items
$items = $cart->getItems();
// get custom options value of cart items
foreach ($items as $item) {
$options = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
$customOptions = $options['options'];
if (!empty($customOptions)) {
foreach ($customOptions as $option) {
$optionTitle = $option['label'];
$optionId = $option['option_id'];
$optionType = $option['type'];
$optionValue = $option['value'];
}
}
}
- 获取任意一个订单中的产品的自定义选项
$orderObject = $objectManager->get('\Magento\Sales\Model\Order');
// load by order id
$orderId = 1; // YOUR ORDER ID
$order = $orderObject->load($orderId);
// load by order increment id
// $incrementId = '000000001'; // YOUR ORDER INCREMENT ID
// $order = $orderObject->loadByIncrementId($incrementId);
$items = $order->getAllVisibleItems(); // get all items aren't marked as deleted and that do not have parent item; for e.g. here associated simple products of a configurable products are not fetched
// Order items can also be fetched with the following functions
// $items = $order->getAllItems(); // get all items that are not marked as deleted
// $items = $order->getItems(); // get all items
foreach ($items as $item) {
$options = $item->getProductOptions();
if (isset($options['options']) && !empty($options['options'])) {
foreach ($options['options'] as $option) {
echo 'Title: ' . $option['label'] . '<br />';
echo 'ID: ' . $option['option_id'] . '<br />';
echo 'Type: ' . $option['option_type'] . '<br />';
echo 'Value: ' . $option['option_value'] . '<br />' . '<br />';
}
}
}
然而,直接使用 ObjectManager 不是一个很好的解决方案。
还可以像下面一样使用依赖注入:
- 在块类 Mageplaza_HelloWorld 中,在它的构造函数中注入对象 \Magento\Sales\Model\Order
app/code/Mageplaza/HelloWorld/Block/HelloWorld.php
<?php
namespace Mageplaza\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $_orderModel;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Sales\Model\Order $orderModel,
array $data = []
)
{
$this->_orderModel = $orderModel;
parent::__construct($context, $data);
}
public function getOrderItems($orderId)
{
$order = $this->_orderModel->load($orderId);
return $order->getAllVisibleItems();
}
}
?>
- 然后,可以在 .phtml 文件中使用这个函数
$orderId = 1; // YOUR ORDER ID
$items = $block->getOrderItems($orderId);
foreach ($items as $item) {
$options = $item->getProductOptions();
if (isset($options['options']) && !empty($options['options'])) {
foreach ($options['options'] as $option) {
echo 'Title: ' . $option['label'] . '<br />';
echo 'ID: ' . $option['option_id'] . '<br />';
echo 'Type: ' . $option['option_type'] . '<br />';
echo 'Value: ' . $option['option_value'] . '<br />' . '<br />';
}
}
}
以上就是如何从购物车或者订单中获取产品的自定义选项。