2

I have a product collection and i have used below code to display in my template file as follows.

 <ol class="products list items product-items">
 <?php 
 $productCollectionSku = array('111', '222', '333', '444', '555', '666'); // these are the comma separated skus.

        foreach($productCollectionSku as  $productSku){ 
            $product =  $block->getProductBySku($productSku);
            $productName = $product->getName();
            $shortDescription = $product->getshortDescription();
            $productUrl = $product->getProductUrl();
            $productId = $product->getId(); 

            $productPrice = $product->getPrice();   
            $addtoCartUrl = $block->getAddToCartUrlForProduct($productSku);
        ?>
        <li class="item product product-item">              
            <div class="product-item-info" data-container="product-grid">
                <a href="<?php echo $productUrl; ?>" class="product photo product-item-photo">
                    <span class="product-image-wrapper">
                    <img class="product-image-photo" src="<?php echo $productImage; ?>" width="240" height="300" alt="<?php echo $productName; ?>"></span>
                </a>
                <div class="product details product-item-details">                      
                    <strong class="product name product-item-name">
                    <a class="product-item-link" href="<?php echo $productUrl; ?>">
                        <?php echo $productName; ?></a>
                    </strong>                    
                    <div class="price-box price-final_price">
                        <span class="price-container price-final_price">
                            <span class="price-wrapper ">
                                <span class="price"><?php echo $productPrice; ?></span>
                            </span>
                        </span>
                    </div>  
                    <form action="<?php echo $addtoCartUrl; ?>" method="post" class="best-items">   
                        <?php echo $block->getBlockHtml('formkey')?>
                        <input type="hidden" name="productId" value="<?php echo $productId; ?>">
                        <button type="submit" title="Add to Cart" class="action tocart primary">                        
                            <span>Add to Cart</span>
                        </button>
                    </form>                     
                </div>
            </div>
        </li>
    <?php } ?>
    </ol>

Here is my getProductBysku function

  public function getProductBySku($sku)
   {
    return $this->productRepository->get($sku);// injecting this class in my block file \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,

   }

The above code working fine if all of the SKUs are simple products,

I need to prepare for configurable products also. Can we get the product info and display here config products with all the variations as swatches.

All I am looking here is how to display configurable products here exactly like in the category list page with the swatches being shown.

Where all the color and size swatches shows with clickable option.

Can anyone help me to implement this one?

Thanks in Advance!!

  • What is not working / showing exactly? My guess is that only price and the toCartUrl is not working, can you confirm that? – Arno Vande Cappelle Jul 15 at 10:28
  • @ArnoVandeCappelle, If any of the sku in array config product, I need to list that product with all combination selection like in default category list page. where color and size shown. – jafar pinjar Jul 15 at 10:30
  • @ArnoVandeCappelle, Are you clear with it now? – jafar pinjar Jul 15 at 10:34
  • Share your $block->getProductBySku($productSku); code – Chirag Patel Jul 17 at 10:41
  • @ChiragPatel, I have updated the code – jafar pinjar Jul 17 at 10:48
1
    <ol class="products list items product-items">
     <?php 
     $productCollectionSku = array('111', '222', '333', '444', '555', '666'); // these are the comma separated skus.

            foreach($productCollectionSku as  $productSku){ 
                $product =  $block->getProductBySku($productSku);
                $productName = $product->getName();
                $shortDescription = $product->getshortDescription();
                $productUrl = $product->getProductUrl();
                $productId = $product->getId(); 

                $productPrice = $product->getPrice();   
                $addtoCartUrl = $block->getAddToCartUrlForProduct($productSku);
            ?>
            <li class="item product product-item">              
                <div class="product-item-info" data-container="product-grid">
                    <a href="<?php echo $productUrl; ?>" class="product photo product-item-photo">
                        <span class="product-image-wrapper">
                        <img class="product-image-photo" src="<?php echo $productImage; ?>" width="240" height="300" alt="<?php echo $productName; ?>"></span>
                    </a>
                    <div class="product details product-item-details">                      
                        <strong class="product name product-item-name">
                        <a class="product-item-link" href="<?php echo $productUrl; ?>">
                            <?php echo $productName; ?></a>
                        </strong>                    
                        <div class="price-box price-final_price">
                            <span class="price-container price-final_price">
                                <span class="price-wrapper ">
                                    <span class="price"><?php echo $productPrice; ?></span>
                                </span>
                            </span>
                        </div>  
                        <form action="<?php echo $addtoCartUrl; ?>" method="post" class="best-items">   
                            <?php echo $block->getBlockHtml('formkey')?>
                            <input type="hidden" name="productId" value="<?php echo $productId; ?>">

$productTypeInstance = $product->getTypeInstance();
$productTypeInstance->setStoreFilter($product->getStoreId(), $product);


if($product->getTypeId() == "configurable"):
$productTypeInstance = $_objectManager->get('Magento\ConfigurableProduct\Model\Product\Type\Configurable');
$productAttributeOptions = $productTypeInstance->getConfigurableAttributesAsArray($product);
foreach ($productAttributeOptions as $attribute):
$attributeId = $attribute["attribute_id"];
?>   
<div class="control">
    <span><?=$attribute["label"]?></span>
    <select name="super_attribute[<?=$attributeId?>]" id="select_<?=$attributeId?>" class=" required super-attribute-selectadmin__control-select" title="<?=$attribute["label"] ?>" aria-required="true">
        <option value="">-- Please Select --</option>
        <?php foreach ($attribute["options"] as $attrOption):?>
        <option value="<?=$attrOption["value"]?>" ><?= $attrOption["label"]?></option>
        <?php endforeach;?>
    </select>
</div>
<?php endforeach;?>
<?php endif;?>

<?php 
$customOptions = $_objectManager->get('Magento\Catalog\Model\Product\Option')->getProductOptionCollection($product);
foreach ($customOptions as $option):
$optionId = $option->getOptionId();
?>
<div class="control">
<span><?=$option->getTitle()?></span>
    <select name="options[<?php echo $optionId?>]" id="select_<?php echo $optionId?>" class=" required product-custom-option admin__control-select" title="<?=$option->getTitle()?>" data-selector="options[<?php echo $optionId?>]" aria-required="true">
        <option value="">-- Please Select --</option>
<?php 
    foreach ($option->getValues() as $value) :
        $optionData = $value->getData();
        $optionTypeId = $optionData["option_type_id"];
        $optionPrice = $optionData["price"];
        $optionTitle = $optionData["title"]; 
 ?>
<option value="<?=$optionTypeId?>" price="<?= $optionPrice?>"><?= $optionTitle?></option>
<?php endforeach; ?>
</select>
        </div>
 <?php endforeach;?>

                            <button type="submit" title="Add to Cart" class="action tocart primary">                        
                                <span>Add to Cart</span>
                            </button>
                        </form>                     
                    </div>
                </div>
            </li>
        <?php } ?>
        </ol>
  • hello @Sagar, can you please update me the code for swatches, i am looking for swatches to show over there – jafar pinjar Jul 23 at 9:01
0

You can check module-configurable-product in Magento

You can override configurable.phtml file to your module.

vendor/magento/module-configurable-product/view/frontend/templates/product/view/type/options/configurable.phtml

As i said in comments, you can check condition like this

$product->getTypeId()=="configurable"

and show your html according to the product.

Hope It helps.

  • hi @Mohit, is any chance to update as per my collection, I already have product object just need to display it, the above one is not complete answer.. – jafar pinjar Jul 18 at 8:01
  • hello @Mohit, can you please brief me how can i use your answer as per my requirement? – jafar pinjar Jul 22 at 7:42
  • I need to show swatches there, the approach u given is for drop downs, Also pls brief me your answer.. – jafar pinjar Jul 22 at 8:04
  • you can check in default magento to see how it's working in core magento /var/www/html/magento_226/vendor/magento/module-configurable-product/view/frontend/layout also check the module-catalog module – Mohit Rane Jul 22 at 9:36
  • yes i checked over there, that module is for showing option in dropdown but in my case i am using swatches. What code i need to use to make it work like default list page – jafar pinjar Jul 22 at 9:38
0

Please check with below code to do, get configurable products collection with options.

<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$repository = $obj->create('Magento\Catalog\Model\ProductRepository');
$product = $repository->getById('67');

$data = $product->getTypeInstance()->getConfigurableOptions($product);

$options = array();

foreach($data as $attr){
  foreach($attr as $p){
    $options[$p['sku']][$p['attribute_code']] = $p['option_title'];
  }
}


foreach($options as $sku =>$d){
  $pr = $repository->get($sku);
  foreach($d as $k => $v)
    echo $k.' - '.$v.' ';
  echo ' : '.$pr->getPrice()."\n";
}
  • hello, @Anas, yes above code will give the options that' fine, if you look into my code that will list collection with all info, same like how can i display in the same template, I am looking exactly for that, I need to fetch all option info if there is config product and display that like in category page, Pls dont share how to get the option info and all, that i can get it. Thanks. Help me to display the config product exactly like in category page, This is what i am looking for.. – jafar pinjar Jul 18 at 8:43
0

Try following way...

Create an extension simple and my code add in your helper file after you can get all data in phtml file

<?php
namespace Company\Module\Helper;

use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    /**
     * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
     */
    private $productCollection;

    public function __construct(
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollection
    ) {
        parent::__construct($context);
        $this->productCollection = $productCollection;
    }

    public function getProductCollection()
    {
        $productIds = [1,2,3,4];
        $collection = $this->productCollection->create()
        ->addAttributeToSelect('*')
        ->addStoreFilter()
        ->addFieldToFilter(
            'entity_id',
            ['in' => $productIds]
        );

        // sort categories by some value
        if ($sortBy) {
            $collection->addOrderField($sortBy);
        }

        // select certain number of categories
        if ($pageSize) {
            $collection->setPageSize($pageSize); 
        }    

        return $collection;

    }
} 
  • helllo @Rakesh, My question is to display the collection not to get the collection. Already i have collection just i need to display like product list as same like category page – jafar pinjar Jul 19 at 13:41
  • yes but you can add your product id in my collection after you can showing products like listing page – Rakesh Donga Jul 19 at 14:27
  • yes, pls share the code to display collection like category page – jafar pinjar Jul 19 at 14:33
0

You might be able to inject a \Magento\Swatches\Block\Product\Renderer\Configurable in to your block file (which is responsible for rendering the image/label variations of a product). You can then, in your AbstractBlock::_toHtml() function add something like so:

$this->configurable->setProduct($this->getProductBySku('my-sku');
$this->setChild('swatches', $this->configurable);
return parent::_toHtml();

You can then output the data of swatches in your template by using <?= $block->getChildHtml('swatches'); ?>

  • hello @Adam, this i got the idea about this, but of you could update to my question that will be a great help, is it possible to update to my question with the code i used there. – jafar pinjar Jul 22 at 5:56
  • hello @Adam, can you please elaborate? – jafar pinjar Jul 22 at 10:03

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.