2

I'm trying to develop an extension. I want to select a product SKU in the admin to be able to display the product on the home page.

enter image description here

app\code\My\Mpanel\etc\adminhtml\system.xml

enter image description here

app\design\frontend\My\claue\Magento_Theme\templates\script.phtml

I use the code:

<?php $themeHelper = $this->helper('My\Mpanel\Helper\Data'); ?>

Everything works well.

I spent quite a bit of time. Please help.

Prince Patel
  • 22,708
  • 10
  • 97
  • 119
Vinh
  • 31
  • 6

1 Answers1

1

Add new field in system.xml with <source_model>

<field id="productsku" translate="label" type="multiselect" sortOrder="40" showInDefault="1" showInWebsite="0" showInStore="0">
    <label>Select Product</label>
    <source_model>My\Mpanel\Model\Config\Source\ProductSku</source_model>
</field>

Add ProductSku.php at

app/code/My/Mpanel/Model/Config/Source

<?php

namespace My\Mpanel\Model\Config\Source;

class ProductSku implements \Magento\Framework\Option\ArrayInterface
{

    protected $_productCollectionFactory;

    public function __construct(      
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
    ) {    
        $this->_productCollectionFactory = $productCollectionFactory;
    }

    public function toOptionArray()
    {
        $collection = $this->_productCollectionFactory->create();

        $sku = [];
        foreach ($collection as $product) {
            $sku[] = ['value' => $product->getId(), 'label' => $product->getSku()];
        }

        return $sku;
    }
}

OUTPUT:

enter image description here

Refer This Answer To Get Config Value: https://magento.stackexchange.com/a/108817/35758

Prince Patel
  • 22,708
  • 10
  • 97
  • 119
  • Thank you for your great help. I have encountered an error with this message. Please check.

    error: Uncaught TypeError: Argument 1 passed to MGS\Mpanel\Model\Config\Source\ProductSku::__construct() must be an instance of Magento\Catalog\Model\ResourceModel\Product\CollectionFactory, instance of Magento\Framework\ObjectManager\ObjectManager given, called in ...... .....\Compiled->create('MGS\Mpan in E:\XAMPP\htdocs\My\app\code\MGS\Mpanel\Model\Config\Source\ProductSku.php on line 10

    – Vinh Dec 26 '17 at 01:41
  • After i delete var, things are ok. Really thank you very much. Wish all good things will come to you <3 – Vinh Dec 26 '17 at 02:23
  • Can you tell me how to get the SKU in this admin and show a product to the home page? – Vinh Dec 26 '17 at 02:28