My prepare collection code :
protected function _prepareCollection()
{
$store = $this->_getStore();
$collection = $this->productFactory->create()->getCollection()->addAttributeToSelect(
'sku'
)->addAttributeToSelect(
'name'
)->addAttributeToSelect(
'attribute_set_id'
)->addAttributeToSelect(
'type_id'
)->setStore(
$store
);
if ($this->moduleManager->isEnabled('Magento_CatalogInventory')) {
$collection->joinField(
'qty',
'cataloginventory_stock_item',
'qty',
'product_id=entity_id',
'{{table}}.stock_id=1',
'left'
);
}
if ($store->getId()) {
$collection->setStoreId($store->getId());
$collection->addStoreFilter($store);
$collection->joinAttribute(
'name',
'catalog_product/name',
'entity_id',
null,
'inner',
Store::DEFAULT_STORE_ID
);
$collection->joinAttribute(
'status',
'catalog_product/status',
'entity_id',
null,
'inner',
$store->getId()
);
$collection->joinAttribute(
'visibility',
'catalog_product/visibility',
'entity_id',
null,
'inner',
$store->getId()
);
$collection->joinAttribute('price', 'catalog_product/price', 'entity_id', null, 'left', $store->getId());
} else {
$collection->addAttributeToSelect('price');
$collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner');
$collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner');
}
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns()
{
$this->addColumn(
'in_products',
[
'type' => 'checkbox',
'html_name' => 'products_id',
'required' => true,
'values' => $this->_getSelectedProducts(),
'align' => 'center',
'index' => 'entity_id',
]
);
$this->addColumn(
'entity_id',
[
'header' => __('ID'),
'width' => '50px',
'index' => 'entity_id',
'type' => 'number',
]
);
$this->addColumn(
'name',
[
'header' => __('Name'),
'index' => 'name',
'header_css_class' => 'col-type',
'column_css_class' => 'col-type',
]
);
$this->addColumn(
'sku',
[
'header' => __('SKU'),
'index' => 'sku',
'header_css_class' => 'col-sku',
'column_css_class' => 'col-sku',
]
);
$store = $this->_getStore();
$this->addColumn(
'price',
[
'header' => __('Price'),
'type' => 'price',
'currency_code' => $store->getBaseCurrency()->getCode(),
'index' => 'price',
'header_css_class' => 'col-price',
'column_css_class' => 'col-price',
]
);
$this->addColumn(
'position',
[
'header' => __('Position'),
'name' => 'position',
'width' => 60,
'type' => 'number',
'validate_class' => 'validate-number',
'index' => 'position',
'editable' => true,
'edit_only' => true,
]
);
$this->addColumn(
'brand',
[
'header' => __('Brand'),
'type' => 'options',
'index' => 'brand',
'name' => 'brand',
'options' => $this->getBrandsOptionArray(),
'header_css_class' => 'col-brand',
'column_css_class' => 'col-brand',
]
);
$this->addColumn('category_name',
array(
'header' => 'Category Name',
'type' => 'options',
'align' => 'left',
'index' => 'category_name'
)
);
return parent::_prepareColumns();
}