0

Hi i have a data of table coming in form of array in function inside my block class : What i want basically is to display that array form data on my homepage :

here's my code :

protected function _getAllProductProductCollection()
    {
       $collection = $this->productCollectionFactory->create();

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
        $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
        $collection2 = $resource->getConnection();
        $tableName = $resource->getTableName('catalog_product_flat_19'); //gives table name with prefix

        $sql = "Select name , image FROM " . $tableName . " where image IS NOT NULL " ;
        $result = $collection2->fetchAll($sql);

//         echo "<pre>";
//        var_dump($result);
//        echo "</pre>";

//basically i want to pass that $result below here but no idea how ?

        $conditions = $this->getConditions();
        $conditions->collectValidatedAttributes($collection);
        $this->sqlBuilder->attachConditionToCollection($collection, $conditions);
        return $collection;
    }

this is the data in form of array :

enter image description here

i want this list of products data to display over here , following products are coming from another function i would replace it from my function :

enter image description here

------------------Edit -------------------------- if i pass $result variable from here :

$conditions->collectValidatedAttributes($result);

It gives me following error on screen:

Fatal error: Uncaught Error: Call to a member function isEnabledFlat() on array in C:\xampp\htdocs\chase\vendor\magento\module-catalog-widget\Model\Rule\Condition\Product.php:

1

You should refrain from using direct sql queries and instead use collection classes, Use of object manager is also not recommended. Both of these comes under bad coding practices. Check the method in below custom class and see if helps you.

use Magento\Catalog\Block\Product\AbstractProduct;
use Magento\Catalog\Block\Product\Context;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Checkout\Model\ResourceModel\Cart;
use Magento\Checkout\Model\Session;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\Module\Manager;
use Magento\Catalog\Model\Product\Attribute\Source\Status;

class HomeProducts extends AbstractProduct
{
    /**
     * @var Collection
     */
    protected $itemCollection;

    /**
     * Checkout session
     *
     * @var Session
     */
    protected $checkoutSession;

    /**
     * Catalog product visibility
     *
     * @var Visibility
     */
    protected $catalogProductVisibility;

    /**
     * Checkout cart
     *
     * @var Cart
     */
    protected $checkoutCart;

    /**
     * @var Manager
     */
    protected $moduleManager;

    /**
     * @var CollectionFactory
     */
    protected $productCollectionFactory;

    /**
     * @var Status
     */
    protected $productStatus;

    /**
     * HomeProducts constructor.
     * @param Context $context
     * @param Cart $checkoutCart
     * @param Visibility $catalogProductVisibility
     * @param Session $checkoutSession
     * @param Manager $moduleManager
     * @param CollectionFactory $productCollectionFactory
     * @param Status $productStatus
     * @param array $data
     */
    public function __construct(
        Context $context,
        Cart $checkoutCart,
        Visibility $catalogProductVisibility,
        Session $checkoutSession,
        Manager $moduleManager,
        CollectionFactory $productCollectionFactory,
        Status $productStatus,
        array $data = []
    ) {
        $this->checkoutCart = $checkoutCart;
        $this->catalogProductVisibility = $catalogProductVisibility;
        $this->checkoutSession = $checkoutSession;
        $this->moduleManager = $moduleManager;
        $this->productStatus = $productStatus;
        $this->productCollectionFactory = $productCollectionFactory;
        parent::__construct(
            $context,
            $data
        );
    }

    /**
     * @return $this
     */
    public function _getAllProductProductCollection()
    {
            $productCollectionFactory = $this->productCollectionFactory->create();
            $this->itemCollection = $productCollectionFactory->addAttributeToSelect(
                ['name','sku','status','small_image', 'image', 'thumbnail_image', 'visibility','url']
            )->addAttributeToFilter('image', array('null' => false))
                ->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()])
                ->addAttributeToFilter('visibility', ['in' => $this->catalogProductVisibility->getVisibleInSiteIds()]);

           $items =  $this->itemCollection->load();   

        return $items ;
    }

}
  • please look at the code above i pasted as an answer i do same you tell me it's giving me error ------------------------------( Uncaught TypeError: Argument 12 passed to Codazon\ProductFilter\Block\Product\ProductsList::__construct() must be an instance of Codazon\ProductFilter\Block\Product\Status, array given, called in C:\xampp\htdocs\chase\generated\code\Codazon\ProductFilter\Block\Product\ProductsList\Interceptor.php on line 14 and defined in C:\xampp\htdocs\chase\app\code\Codazon\ProductFilter\Block\Product\ProductsList.php: ) – Hamza Mustafa Feb 7 '18 at 9:45
  • Did you delete var/generation folder? you should do that in order to reflect the class changes. – Shireen N Feb 7 '18 at 9:48
  • alright i re run all commands compile , upgrade , deploy etc , now getting this error ---------------- (Error filtering template: Class Codazon\ProductFilter\Block\Product\Status does not exist in [Codazon\ProductFilter\Block\Product\ProductsList\Interceptor]) – Hamza Mustafa Feb 7 '18 at 10:43
  • its because you haven't used it add the below line, also check my code in answer (use Magento\Catalog\Model\Product\Attribute\Source\Status;). Use all the classes, I see in your code you have given incorrect class path for all the classes which were in contruct – Shireen N Feb 7 '18 at 10:45
0

it's giving me error ------------------------------

Uncaught TypeError: Argument 12 passed to Codazon\ProductFilter\Block\Product\ProductsList::__construct() must be an instance of Codazon\ProductFilter\Block\Product\Status, array given, called in C:\xampp\htdocs\chase\generated\code\Codazon\ProductFilter\Block\Product\ProductsList\Interceptor.php on line 14 and defined in C:\xampp\htdocs\chase\app\code\Codazon\ProductFilter\Block\Product\ProductsList.php: ) –


 <?php
    /**
     * Copyright © 2015 Magento. All rights reserved.
     * See COPYING.txt for license details.
     */

    // @codingStandardsIgnoreFile

    namespace Codazon\ProductFilter\Block\Product;
    /**
     * Catalog Products List widget block
     * Class ProductsList
     * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
     */
    class ProductsList extends \Magento\CatalogWidget\Block\Product\ProductsList
    {
        protected $urlHelper;
        protected $productCollectionFactory;
        protected $bestSellerCollectionFactory;
        protected $imageHelperFactory;
        protected $productStatus;


        public function __construct(
            \Magento\Catalog\Block\Product\Context $context,
            \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
            \Codazon\ProductFilter\Model\ResourceModel\Bestsellers\CollectionFactory $bestSellerCollectionFactory,
            \Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,
            \Magento\Framework\App\Http\Context $httpContext,
            \Magento\Rule\Model\Condition\Sql\Builder $sqlBuilder,
            \Magento\CatalogWidget\Model\Rule $rule,
            \Magento\Widget\Helper\Conditions $conditionsHelper,
            \Magento\Catalog\Helper\ImageFactory $imageHelperFactory,
            \Magento\Framework\Url\Helper\Data $urlHelper,
            \Codazon\ProductFilter\Block\ImageBuilderFactory $customImageBuilderFactory,
            \Codazon\ProductFilter\Block\Product\Status $productStatus,
            array $data = []
        ) {

            $this->productCollectionFactory = $productCollectionFactory;
            $this->bestSellerCollectionFactory = $bestSellerCollectionFactory;
            $this->catalogProductVisibility = $catalogProductVisibility;
            $this->httpContext = $httpContext;
            $this->sqlBuilder = $sqlBuilder;
            $this->rule = $rule;
            $this->urlHelper = $urlHelper;
            $this->conditionsHelper = $conditionsHelper;
            $this->imageHelperFactory = $imageHelperFactory;
            $this->productStatus = $productStatus;

            //$this->reviewFactory = $reviewFactory;
            $this->customImageBuilderFactory = $customImageBuilderFactory;
            parent::__construct(
                $context,
                $productCollectionFactory,
                $catalogProductVisibility,
                $httpContext,
                $sqlBuilder,
                $rule,
                $conditionsHelper

            );
        }

        public function getCacheKeyInfo()
        {
            $conditions = $this->getData('conditions')
                ? $this->getData('conditions')
                : $this->getData('conditions_encoded');
            $conditions = json_encode($this->getData());
            return [
                'PRODUCT_FILTER_WIDGET',
                $this->_storeManager->getStore()->getId(),
                $this->_design->getDesignTheme()->getId(),
                $this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_GROUP),
                intval($this->getRequest()->getParam(self::PAGE_VAR_NAME, 1)),
                $this->getProductsPerPage(),
                $conditions
            ];
        }

        public function getAddToCartUrl($product, $additional = [])
        {
            /*if ($product->getTypeInstance()->hasRequiredOptions($product)) {
                if (!isset($additional['_escape'])) {
                    $additional['_escape'] = true;
                }
                if (!isset($additional['_query'])) {
                    $additional['_query'] = [];
                }
                $additional['_query']['options'] = 'cart';

                return $this->getProductUrl($product, $additional);
            }*/

            return $this->_cartHelper->getAddUrl($product, $additional);
        }

        public function getAddToCartPostParams(\Magento\Catalog\Model\Product $product, $additional = [])
        {
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

            $listBlock = $objectManager->get('\Magento\Catalog\Block\Product\ListProduct');
            $url =  $listBlock->getAddToCartUrl($product);
            //$url = $this->getAddToCartUrl($product,$additional);
            return [
                'action' => $url,
                'data' => [
                    'product' => $product->getEntityId(),
                    \Magento\Framework\App\ActionInterface::PARAM_NAME_URL_ENCODED =>
                        $this->urlHelper->getEncodedUrl($url),
                ]
            ];
        }

        protected function _getBestSellerProductCollection()
        {
            $collection = $this->bestSellerCollectionFactory->create();
            $bestSellerTable = $collection->getTable('sales_bestsellers_aggregated_daily');
            $collection->getSelect()->join(array('r' => $bestSellerTable), 'r.product_id=e.entity_id', array('*'))->group('e.entity_id');
            $collection = $this->_addProductAttributesAndPrices($collection)
                ->addStoreFilter()
                ->setPageSize($this->getPageSize())
                ->setCurPage($this->getRequest()->getParam(self::PAGE_VAR_NAME, 1));

            $conditions = $this->getConditions();
            $conditions->collectValidatedAttributes($collection);
            $this->sqlBuilder->attachConditionToCollection($collection, $conditions);

            return $collection;
        }

    //    protected function _getAllProductProductCollection()
    //    {
        //   $collection = $this->productCollectionFactory->create();
          //  $collection->setVisibility($this->catalogProductVisibility->getVisibleInCatalogIds());

          //   $hamzaTable = $collection->getTable('catalog_product_flat_19');
           //  echo $hamzaTable;
         //   $collection2 = "select * from catalog_product_flat_19 where image IS NOT NULL";
    //        $collection->getSelect()
    //            ->array($hamzaTable)
    //            ->addAttributeToFilter('image', array('notnull' => true));
        //  echo $collection2;

           // echo "hamza";

           // $collection = $this->collection2;
              //  ->addAttributeToFilter('image', array('notnull' => true));

    //        $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
    //        $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
    //        $collection2 = $resource->getConnection();
    //        $tableName = $resource->getTableName('catalog_product_flat_19'); //gives table name with prefix
    //
    //        $sql = "Select name , image FROM " . $tableName . " where image IS NOT NULL " ;
    //        $collection  = $collection2->fetchAll($sql);

    //         echo "<pre>";
    //        var_dump($result);
    //        echo "</pre>";

    //        $collection = $this->_addProductAttributesAndPrices($collection)
    //            ->addStoreFilter()
    //            ->setPageSize($this->getPageSize())
    //            ->setCurPage($this->getRequest()->getParam(self::PAGE_VAR_NAME, 1));

    //        $conditions = $this->getConditions();
    //        $conditions->collectValidatedAttributes($collection);
    //        $this->sqlBuilder->attachConditionToCollection($collection, $conditions);
    //
    //        return $collection;
    //
    //    }














        public function _getAllProductProductCollection()
        {
            $productCollectionFactory = $this->productCollectionFactory->create();
            $this->itemCollection = $productCollectionFactory->addAttributeToSelect(
                ['name','sku','status','small_image', 'image', 'thumbnail_image', 'visibility','url']
            )->addAttributeToFilter('image', array('null' => false))
                ->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()])
                ->addAttributeToFilter('visibility', ['in' => $this->catalogProductVisibility->getVisibleInSiteIds()]);

            $items =  $this->itemCollection->load();

            return $items ;
        }

        public function createCollection()
        {
            $displayType = $this->getDisplayType();
            $collection = null;
            switch($displayType)
            {
                case 'all_products': $collection = $this->_getAllProductProductCollection();break;
                case 'bestseller_products': $collection = $this->_getBestSellerProductCollection();break;
            }
            $sort = explode(' ', $this->getData('order_by'));
            $collection->addAttributeToSort($sort[0],$sort[1]);

            $this->_eventManager->dispatch(
                'catalog_block_product_list_collection',
                ['collection' => $collection]
            );
            return $collection;
        }

        /**
         * Return identifiers for produced content
         *
         * @return array
         */
        public function getIdentities()
        {
            return [\Magento\Catalog\Model\Product::CACHE_TAG];
        }

        /**
         * Get value of widgets' title parameter
         *
         * @return mixed|string
         */

        public function getTemplate()
        {
            $template = $this->getData('filter_template');
            if($template == 'custom')
            {
                return $this->getData('custom_template');
            }
            else
            {
                return $template;
            }
        }

        public function isShow($item)
        {
            $show = explode(",",$this->getData('show'));                
            if (in_array($item,$show) !== false) {
                return true;
            }else{
                return false;
            }
        }

        public function getImage($product, $imageId, $attributes = [])
        {
            $width = $this->getData('thumb_width');
            $height = $this->getData('thumb_height');
            $attributes = array('resize_width'=>$width,'resize_height'=>$height);

            $imageBuilder = $this->customImageBuilderFactory->create();
            return $imageBuilder->setProduct($product)
                ->setImageId($imageId)
                ->setAttributes($attributes)
                ->create();
            return $html;
        }

        public function getBlockId()
        {
            return uniqid("cdz_block_");
        }

        protected function _toHtml(){
            $isAjax = $this->getData('is_ajax');
            //$isAjax = true;
            if($isAjax){
                return parent::_toHtml();
            }else{
                $data = [
                    'is_ajax'           =>  1,
                    'title'             =>  $this->getData('title'),
                    'display_type'      =>  $this->getData('display_type'),
                    'products_count'    =>  $this->getData('products_count'),
                    'order_by'          =>  $this->getData('order_by'),
                    'show'              =>  $this->getData('show'),
                    'thumb_width'       =>  $this->getData('thumb_width'),
                    'thumb_height'      =>  $this->getData('thumb_height'),
                    'filter_template'   =>  $this->getData('filter_template'),
                    'custom_template'   =>  $this->getData('custom_template'),
                    'show_slider'       =>  $this->getData('show_slider'),
                    'slider_item'       =>  $this->getData('slider_item'),
                    'conditions_encoded'        =>  $this->getData('conditions_encoded')
                ];
                $block = $this->getLayout()->createBlock('\Magento\Framework\View\Element\Template');
                $block->setTemplate('Codazon_ProductFilter::ajax/first_load.phtml');
                $block->setData('json_data',json_encode($data));
                return $block->toHtml();
            }
        }
    }

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.