Magento 2で製品画像とURLを取得する方法は?


16

これは私のオブザーバーです:

public function execute(\Magento\Framework\Event\Observer $observer)
{
    $orderIds = $observer->getEvent()->getOrderIds();
    $order = $this->_orderRepositoryInterface->get($orderIds[0]);
    $items =$order->getAllVisibleItems();
    $productQuantity = array();
    $productPrice = array();
    $productName = array();
    $productIds = array();
    foreach($items as $item) {
        $productIds[]= $item->getProductId();
        $productName[]= $item->getSku(); 
        $productPrice[] = $item->getPrice();
        $productQuantity[]= floor($item->getQtyOrdered());
    }
}

アイテムから製品画像と製品URLを取得するにはどうすればよいですか?


どのイベントをキャッチしましたか?
コアトゥオンディン

checkout_onepage_controller_success_action
Ramkishan Suthar

回答:


23

この方法は、製品イメージを取得する最良の方法ではない場合があります。

\Magento\Catalog\Api\ProductRepositoryInterfaceFactoryコンストラクターに注入します。

protected $_productRepositoryFactory;

public function __construct(
        \Magento\Catalog\Api\ProductRepositoryInterfaceFactory $productRepositoryFactory
) {

    $this->_productRepositoryFactory = $productRepositoryFactory;
}

画像を取得できます:

$product = $this->_productRepositoryFactory->create()->getById($item->getProductId());
$product->getData('image');
$product->getData('thumbnail');
$product->getData('small_image');

あなたの答えは正しいですが、カートに複数の製品がある場合はどうすればいいですか?複数の製品イメージを表示するにはどうすればよいですか
-Ramkishan Suthar

わかった。@ khoa。複数の生産イメージがある場合。
たくさん

これは機能していません。返される値は、この「/w/s/wsh10-orange_main.jpg」のような文字列のいくつかの種類である
ホアンチン

2
@piavghそれはイメージへの道です:pub/media/catalog/product
Khoa TruongDinh

1
私は実際の画像を読み込むことができるようにので、どのように私は<IMG SRC =「」/>属性で/w/s/wsh10-orange_main.jpgを使用しない
Lachezar Raychev

17

特定のストアビューの画像の公開/キャッシュフロントエンドURLが必要な場合(私がしたように)、これは私のために働いています:

/**
 * @var \Magento\Store\Model\App\Emulation
 */
protected $appEmulation;

/**
 * @var \Magento\Store\Model\StoreManagerInterface
 */
protected $storeManager;

/**
 * @var \Magento\Catalog\Api\ProductRepositoryInterfaceFactory
 */
protected $productRepositoryFactory;

/**
 * @var \Magento\Catalog\Helper\ImageFactory
 */
protected $imageHelperFactory;

/**
 * @param \Magento\Store\Model\StoreManagerInterface $storeManager
 * @param \Magento\Store\Model\App\Emulation $appEmulation
 * @param \Magento\Catalog\Api\ProductRepositoryInterfaceFactory $productRepositoryFactory
 * @param \Magento\Catalog\Helper\ImageFactory $helperFactory
 */
public function __construct(
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Store\Model\App\Emulation $appEmulation,
    \Magento\Catalog\Api\ProductRepositoryInterfaceFactory $productRepositoryFactory,
    \Magento\Catalog\Helper\ImageFactory $imageHelperFactory
)
{
    $this->storeManager = $storeManager;
    $this->appEmulation = $appEmulation;
    $this->productRepositoryFactory = $productRepositoryFactory;
    $this->imageHelperFactory = $imageHelperFactory;
}

次に、画像フロントエンドURLを取得する必要がある場所:

$sku = "my-sku";
// get the store ID from somewhere (maybe a specific store?)
$storeId = $this->storeManager->getStore()->getId();
// emulate the frontend environment
$this->appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true);
// load the product however you want
$product = $this->productRepositoryFactory->create()->get($sku);
// now the image helper will get the correct URL with the frontend environment emulated
$imageUrl = $this->imageHelperFactory->create()
  ->init($product, 'product_thumbnail_image')->getUrl();
// end emulation
$this->appEmulation->stopEnvironmentEmulation();

他の画像タイプを選択できます。利用可能な製品画像のリストをproduct_thumbnail_image参照magento/theme-frontend-luma/etc/view.xmlするか、view.xmlファイルに独自の画像を作成します。


1
WTF?それはちょうど病気です:D
ラチェザールRaychev

この解決策を試してみましたが、返されたURLは存在せず、文字列は空ですが、エラーは発生していません。「product_base_image」、「product_small_image」、「product_thumbnail_image」で試しましたが、どれも機能しません。アドバイスしてもらえますか?または、製品リポジトリを使用してこれを行う効率的な方法はありますか?私はすでにブロックのどこかにそれをロードしているので。
ジョシュア洪水

11

製品のURLを返す必要がある場合は、次のようになります。

//todo get product object $product 

$objectManager =\Magento\Framework\App\ObjectManager::getInstance();
$helperImport = $objectManager->get('\Magento\Catalog\Helper\Image');

$imageUrl = $helperImport->init($product, 'product_page_image_small')
                ->setImageFile($product->getSmallImage()) // image,small_image,thumbnail
                ->resize(380)
                ->getUrl();
echo $imageUrl;

6

それが私がした方法です。それは非常に効率的できれいです:

1)最初に、次のクラスを注入する必要があります。

protected $_storeManager;
protected $_appEmulation;
protected $_blockFactory;

public function __construct(
    ...
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Framework\View\Element\BlockFactory $blockFactory,
    \Magento\Store\Model\App\Emulation $appEmulation)
{
    $this->_storeManager = $storeManager;
    $this->_blockFactory = $blockFactory;
    $this->_appEmulation = $appEmulation;
}

2)次に、以下のコードを使用してgetImageUrlメソッドを作成します。

protected function getImageUrl($product, string $imageType = '')
{
    $storeId = $this->_storeManager->getStore()->getId();

    $this->_appEmulation->startEnvironmentEmulation($storeId, \Magento\Framework\App\Area::AREA_FRONTEND, true);

    $imageBlock =  $this->_blockFactory->createBlock('Magento\Catalog\Block\Product\ListProduct');
    $productImage = $imageBlock->getImage($product, $imageType);
    $imageUrl = $productImage->getImageUrl();

    $this->_appEmulation->stopEnvironmentEmulation();

    return $imageUrl;
}

注:「appEmulation」コードは、管理者またはAPIからこの呼び出しを行う場合にのみ必要です。そうしないと、以下のエラー(または同様のエラー)が表示されます。

Unable to resolve the source file for 'webapi_rest/_view/en_AU/Magento_Catalog/images/product/placeholder/.jpg'

3)製品オブジェクトと必要な画像のタイプを渡すgetImageUrlを呼び出します(view.xmlファイルに基づいて)

...
$smallImage = $this->getImageUrl($productObject, 'product_page_image_small');
...

1

カスタムイメージのURLを取得するには、このコードを使用しました。そのため、画像が終了しない場合、デフォルトのテーマ画像がロードされます。

$product = $block->getProduct();

$productImageAttr = $product->getCustomAttribute('product_banner_image');

if ($productImageAttr && $productImageAttr->getValue() != 'no_selection') {

    $productImage = $this->helper('Magento\Catalog\Helper\Image')
    ->init($product, 'product_banner_image')
    ->setImageFile($productImageAttr->getValue());

    $imageUrl = $productImage->getUrl();

} else {

    $imageUrl = $this->getViewFileUrl('images/cat-img1.jpg'); // Theme/web/images

}
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.