0

How to get the customer email by customer id in magento2 admin grid. in my table I have customer id based on customer id get the email id in the admin custom grid.

namespace Vendor\Module\Model\ResourceModel\RewardPointsReportdata\Grid;

use Magento\Framework\Api\Search\SearchResultInterface;
use Magento\Framework\Search\AggregationInterface;
use Vendor\Module\Model\ResourceModel\RewardPointsReportdata\Collection as RewardPointsReportCollection;

/**
 * Collection for displaying grid of banners slider
 */
class Collection extends RewardPointsReportCollection 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 \Magento\Framework\EntityManager\MetadataPool $metadataPool
     * @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,
        $mainTable,
        $eventPrefix,
        $eventObject,
        $resourceModel,
        $model = 'Magento\Framework\View\Element\UiComponent\DataProvider\Document',
        \Magento\Framework\DB\Adapter\AdapterInterface $connection = null,
        \Magento\Framework\Model\ResourceModel\Db\AbstractDb $resource = null
    ) {
        parent::__construct(
            $entityFactory,
            $logger,
            $fetchStrategy,
            $eventManager,
            $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;
    }
}

anyone please help me.

Thanks

2
  • provide grid collection code
    – Amit Bera
    Commented Jan 12, 2022 at 10:17
  • added the collection code. Commented Jan 12, 2022 at 10:25

1 Answer 1

1

Create File:

Vendor\Module\Ui\Component\Listing\Column\CustomerEmail.php

use Magento\Framework\UrlInterface;
use Magento\Framework\View\Element\UiComponentFactory;
use Magento\Framework\View\Element\UiComponent\ContextInterface;
use Magento\Ui\Component\Listing\Columns\Column;
/**
 * Class CustomerEmail
*/
 class CustomerEmail extends Column
 {
    private $urlBuilder;

    protected $helper;

    const CUSTOMER_URL_PATH_EDIT = 'customer/index/edit';
    
    public function __construct(
       ContextInterface $context,
       UiComponentFactory $uiComponentFactory,
       \Vendor\Module\Helper\Data $helper,
       UrlInterface $urlBuilder,
       array $components = [],
       array $data = []
    ) {
       parent::__construct($context, $uiComponentFactory, 
       $components, $data
    );
       $this->urlBuilder = $urlBuilder;
       $this->helper = $helper;
  public function prepareDataSource(array $dataSource)
   {
       if (isset($dataSource['data']['items'])) {
         foreach ($dataSource['data']['items'] as &$item) {
             $name = $this->getData('name');
             if (isset($item['customer_id'])) {
                $CustomerEmail = $this->helper->getCustomerEmail($item['customer_id']);
                //@codingStandardsIgnoreStart
                $item[$name] = html_entity_decode(
                    '<a href="' .
                    $this->urlBuilder->getUrl(
                        self::CUSTOMER_URL_PATH_EDIT,
                        [
                            'id' => $item['customer_id'],
                        ]
                    )
                    . '" target="_blank" >' . $CustomerEmail . '</a>'
                );
                //@codingStandardsIgnoreEnd
            }
        }
    }
    return $dataSource;
  }
        

Add below code in your Grid XML

 <actionColumn name="customer_id" class="Vendor\Module\Ui\Component\Listing\Column\CustomerEmail">
<argument name="data" xsi:type="array">
    <item name="config" xsi:type="array">
        <item name="bodyTmpl" xsi:type="string">ui/grid/cells/html</item>
        <item name="filter" xsi:type="string">text</item>
        <item name="label" xsi:type="string" translate="true">Customer Email</item>
        <item name="sortOrder" xsi:type="number">20</item>
        <item name="resizeEnabled" xsi:type="boolean">true</item>
    </item>
</argument>

Create Helper File:

<?php

namespace Vendor\Module\Helper;

class Data extends AbstractHelper
{
  protected $_customers;

public function __construct(
    \Magento\Customer\Model\Customer $customers
) {
    $this->_customers = $customers;
}

public function getCustomerEmail($id)
{
    $customer = $this->_customers->load($id);
    return $customer->getEmail();
}
 }

Hope this helps!

4
  • where we use this getData() function ? Commented Jan 12, 2022 at 10:55
  • please check updated answer Commented Jan 13, 2022 at 10:40
  • email search filter not working Commented Jan 13, 2022 at 14:25
  • $customer = $this->_customers->load($id); try this on the grid with 500+ items and you'll see where the bottleneck is.
    – c0rewell
    Commented Nov 17, 2023 at 5:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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