I am creating a bespoke extension and I want to allow the admin to choose to restrict by product types eg Simple, Configurable, Bundle etc
The issue is I am not sure what source model to use.
I have the following code in my system.xml
<field id="product_types" translate="label" type="multiselect" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Product Type</label>
<source_model></source_model>
<comment>Restrict defined product types</comment>
</field>
Could anyone advise which source model I need to use so that the options in the multi-select are the product types eg Simple, Configurable, Bundle etc
1 Answer 1
You can create a custom source model as describe below.
Assume, your are using custom extension name "Vendor_Module"
File : ProductType.php under app/code/Vendor/Module/Model/Source
<?php
namespace Vendor\Module\Model\Source;
class ProductType implements \Magento\Framework\Data\OptionSourceInterface
{
//*
// @var \Magento\Catalog\Model\ProductTypeList
//
protected $_productTypeList;
//*
// Constructor
//
// @param \Magento\Catalog\Model\ProductTypeList
//
public function __construct(
\Magento\Catalog\Model\ProductTypeList $productTypeList
)
{
$this->_productTypeList = $productTypeList;
}
/**
* Get options
*
* @return array
*/
public function toOptionArray()
{
$options[] = ['label' => '', 'value' => ''];
$productType = $this->_productTypeList->getProductTypes();
foreach ($productType as $pType) {
$options[] = [
'label' => $pType->getName(),
'value' => $pType->getLabel(),
];
}
return $options;
}
}
update your system.xml as follows.
File : system.xml:
............................
<field id="product_types" translate="label" type="multiselect" sortOrder="1" showInDefault="1" showInWebsite="0" showInStore="0">
<label>Product Type</label>
<source_model>Vendor\Module\Model\Source\ProductType</source_model>
<comment>Restrict defined product types</comment>
</field>
............................
-
Thanks just surprised i have to create a custom source modelGoose84– Goose842019年02月01日 19:38:36 +00:00Commented Feb 1, 2019 at 19:38