0

I want to create a table to show stock status if all products. This table will contains following fields: => Product Name => Product SKU => Quantity => Stock Status (In Stock / Out of Stock)

I tried using object manager.. but not able to find mistake in Stock Status.

Here is my code:

<?php

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$productCollection = $objectManager
    ->create('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory');

    

$collection = $productCollection->create()
    ->addAttributeToSelect('*')
    ->addAttributeToFilter('type_id', array('neq' => 'configurable'))
    ->joinField('stock_item', 'cataloginventory_stock_item', 'qty', 'product_id=entity_id') // add 'qty=0' to get outofstock products
    ->load();
 
?>

<table>
    <thead>
        <tr>
            <td>Sr.</td>
            <td>Name</td>
            <td>SKU</td>
            <td>Quantity</td>
            <td>Stock Status</td>
        </tr>
    </thead>
    <tbody>
        <?php
        $count = 1;
        foreach ($collection as $product) {
        ?>
            <tr>
                <td><?php echo $count; ?></td>
                <td><?php echo $product->getName(); ?></td>
                <td><?php echo $product->getSku(); ?></td>
                <td><?php if($product->getStockItem()==NULL){echo "-";} else { echo $product->getStockItem(); } ?></td>
                <td>
                <?php
                 
                if($product->getStockItem() > 0)
                { 
                    echo '<span style="color:green;">In Stock</span>';
                } 
                elseif($product->getStockItem() == NULL)
                {
                    echo '<span style="color:blue;">N/A</span>';

                } 
                else 
                {
                    echo '<span style="color:red;">Out of Stock</span>';
                } ?>
                </td>
            </tr>
        <?php $count++;
        } ?>
    </tbody>
</table>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.