0

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

asked Feb 1, 2019 at 17:57

1 Answer 1

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>
 ............................

enter image description here

answered Feb 1, 2019 at 19:24
1
  • Thanks just surprised i have to create a custom source model Commented Feb 1, 2019 at 19:38

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.