10

This question already has an answer here:

I have created an admin form with phtml content and a ui component grid. Phtml section working fine. Now I want to filter the grid collection based on the url param. I have used the below code $this->getRequest()->getParam('id') to recieve the url param,but it gives error. Here is my grid collection code.

namespace Company\Module\Model\ResourceModel\Custom\Grid;

use Magento\Framework\Api\Search\SearchResultInterface;
use Magento\Framework\Search\AggregationInterface;
use Company\Module\Model\ResourceModel\Custom\Collection as CustomCollection;


class MyCollection extends CustomCollection implements SearchResultInterface{

     /**
     * @var AggregationInterface
     */
    protected $aggregations;

    /**
     * @param \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory
     * @param \Psr\Log\LoggerInterface $logger
     * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy
     * @param \Magento\Framework\Event\ManagerInterface $eventManager
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param string $mainTable
     * @param string $eventPrefix
     * @param string $eventObject
     * @param string $resourceModel
     * @param string $model
     * @param string|null $connection
     * @param \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource
     *
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct(
        \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory,       
        \Psr\Log\LoggerInterface $logger,
        \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
        \Magento\Framework\Event\ManagerInterface $eventManager,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        $mainTable,
        $eventPrefix,
        $eventObject,
        $resourceModel,
        $model = 'Magento\Framework\View\Element\UiComponent\DataProvider\Document',
        $connection = null,
        \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
    ) {
        $this->addFilterToMap('customer_name','firstname');
        parent::__construct(
            $entityFactory,
            $logger,
            $fetchStrategy,
            $eventManager,
            $storeManager,
            $connection,
            $resource
        );
        $this->_eventPrefix = $eventPrefix;
        $this->_eventObject = $eventObject;
        $this->_init($model, $resourceModel);
        $this->setMainTable($mainTable);
    }

    /**
     * @return AggregationInterface
     */
    public function getAggregations()
    {
        return $this->aggregations;
    }

    /**
     * @param AggregationInterface $aggregations
     * @return $this
     */
    public function setAggregations($aggregations)
    {
        $this->aggregations = $aggregations;
    }


    /**
     * Retrieve all ids for collection
     * Backward compatibility with EAV collection
     *
     * @param int $limit
     * @param int $offset
     * @return array
     */
    public function getAllIds($limit = null, $offset = null)
    {
        return $this->getConnection()->fetchCol($this->_getAllIdsSelect($limit, $offset), $this->_bindParams);
    }

    /**
     * Get search criteria.
     *
     * @return \Magento\Framework\Api\SearchCriteriaInterface|null
     */
    public function getSearchCriteria()
    {
        return null;
    }

    /**
     * Set search criteria.
     *
     * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
     * @return $this
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function setSearchCriteria(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria = null)
    {
        return $this;
    }

    /**
     * Get total count.
     *
     * @return int
     */
    public function getTotalCount()
    {
        return $this->getSize();
    }

    /**
     * Set total count.
     *
     * @param int $totalCount
     * @return $this
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function setTotalCount($totalCount)
    {
        return $this;
    }

    /**
     * Set items list.
     *
     * @param \Magento\Framework\Api\ExtensibleDataInterface[] $items
     * @return $this
     * @SuppressWarnings(PHPMD.UnusedFormalParameter)
     */
    public function setItems(array $items = null)
    {
        return $this;
    }

    protected function _renderFiltersBefore() {


        $custId = $this->getRequest()->getParam('id');

        $this->addFieldToFilter('main_table.customer_id',$custId);
        $joinTable = $this->getTable('customer_entity');
        $this->getSelect()->join($joinTable.' as customer','main_table.customer_id = customer.entity_id',
                            array('customer_name'=>"CONCAT(firstname,' ',lastname)"));

        parent::_renderFiltersBefore();
    }       

}

This is my extended class

namespace Company\Module\Model\ResourceModel\Custom;

class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
    /**
     * @var string
     */
    protected $_idFieldName = 'custom_id';

    /**
     * Store manager
     *
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $storeManager;

    /**
     * @param \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory
     * @param \Psr\Log\LoggerInterface $logger
     * @param \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy
     * @param \Magento\Framework\Event\ManagerInterface $eventManager
     * @param \Magento\Store\Model\StoreManagerInterface $storeManager
     * @param \Magento\Framework\DB\Adapter\AdapterInterface|null $connection
     * @param \Magento\Framework\Model\ResourceModel\Db\AbstractDb|null $resource
     */
    public function __construct(
        \Magento\Framework\Data\Collection\EntityFactoryInterface $entityFactory,
        \Psr\Log\LoggerInterface $logger,
        \Magento\Framework\Data\Collection\Db\FetchStrategyInterface $fetchStrategy,
        \Magento\Framework\Event\ManagerInterface $eventManager,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\DB\Adapter\AdapterInterface $connection = null,
        \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
    ) {
        parent::__construct($entityFactory, $logger, $fetchStrategy, $eventManager, $connection, $resource);
        $this->storeManager = $storeManager;
    }


    /**
     * Define model & resource model
    */
    protected function _construct()
    {
        $this->_init('Company\Module\Model\Custom', 'Company\Module\Model\ResourceModel\Custom');
    }



}

I got the following error

( ! ) Fatal error: Call to undefined method Company\Module\Model\ResourceModel\Custom\Grid\MyCollection::getParam() in /var/www/html/mage2/mage212/app/code/Company/Module/Model/ResourceModel/Custom/Grid/MyCollection.php on line 158

marked as duplicate by Siarhey Uchukhlebau, Keyul Shah, Rakesh Jesadiya, Murtuza Zabuawala, Khoa TruongDinh Jan 11 '17 at 9:08

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • your get parameter code is correct !!! so post the error which you are getting . – Manthan Dave Jan 11 '17 at 6:46
  • I have tried this $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $model = $objectManager->create('Magento\Framework\App\Request\Http')‌​; print_r( $model->getParams());exit; But it gives empty array. i.prntscr.com/28d3caccfb4d465691362c4fb760f207.png – Jancy Abraham Jan 11 '17 at 7:13
27

First, you need to inject \Magento\Framework\App\Request\Http at _construct function then using

Magento2 how to getRequest

$this->request->getParam('id'),you can your data

protected $request;
    public function __construct(
        \Magento\Framework\App\Request\Http $request,
        ....//rest of parameters here
    ) {
       $this->request = $request;
       ...//rest of constructor here
    }
    public function getIddata()
    {
    // use 
    $this->request->getParams(); // all params
        return $this->request->getParam('id');
    }
  • I have tried this $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); $model = $objectManager->create('Magento\Framework\App\Request\Http'); print_r( $model->getParams());exit; But it gives empty array. i.prntscr.com/28d3caccfb4d465691362c4fb760f207.png – Jancy Abraham Jan 11 '17 at 7:12
  • 2
    you have tried wrong once.. Please follow my once – Amit Bera Jan 11 '17 at 7:28
  • 1
    @JancyAbraham When you inject the \Magento\Framework\App\Request\Http in the construct method you receive current request (not new) with all parameters. When you use the ObjectManager you receive the new clear object without any params. – Siarhey Uchukhlebau Jan 11 '17 at 7:31
  • I have tried the construct method, Now I got this error Missing required argument $model of Company\Module\Model\ResourceModel\Custom\Grid\MyCollection. – Jancy Abraham Jan 11 '17 at 7:39
  • @JancyAbraham If the Company\Module\Model\ResourceModel\Custom\Grid\MyCollection extends the Company\Module\Model\ResourceModel\Custom\Collection you should add the similar modifications in the Company\Module\Model\ResourceModel\Custom\Grid\MyCollection::__construct too. – Siarhey Uchukhlebau Jan 11 '17 at 7:50
3

You are trying in correct way.

 $custId = $this->getRequest()->getParam('id');

You can try with below code also

 $params = $this->request->getParams();
 $custId = $params['id']; 
  • Got error : Notice: Undefined property: Company\Module\Model\ResourceModel\Custom\Grid\Collection::$request in /var/www/html/mage2/mage212/app/code/Company/Module/Model/ResourceModel/Custom/Grid/Collection.php on line 158 – Jancy Abraham Jan 11 '17 at 6:55
  • Can you show the \Company\Module\Model\ResourceModel\Custom\Collection extended class name only ? – zed Blackbeard Jan 11 '17 at 7:15
  • updated the code. please check – Jancy Abraham Jan 11 '17 at 7:30
  • This is correct. Share the module if you can. – zed Blackbeard Jan 11 '17 at 8:19

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