I have a module where I have added an additional action on admin panel, under Customers -> All Customers grid. I show the new action by populating file: view/adminhtml/ui_component/customer_listing.xml
:
<listing xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<listingToolbar name="listing_top">
<massaction name="listing_massaction">
<action name="mynewaction">
<argument name="data" xsi:type="array">
<item name="config" xsi:type="array">
<item name="type" xsi:type="string">mynewaction</item>
<item name="label" xsi:type="string" translate="true">Execute a custom action</item>
<item name="url" xsi:type="url" path="modulename/customfolder/customAction"/>
<item name="confirm" xsi:type="array">
<item name="title" xsi:type="string" translate="true">Execute a custom action</item>
<item name="message" xsi:type="string" translate="true">Custom question to confirm my custom action?</item>
</item>
</item>
</argument>
</action>
</massaction>
</listingToolbar>
</listing>
The implementation of the custom mass action is on Controller/Adminhtml/Customfolder/CustomAction.php
<?php
namespace MyModule\Controller\Adminhtml\Customfolder;
use Magento\Framework\Controller\ResultFactory;
use Magento\Backend\App\Action\Context;
use Magento\Ui\Component\MassAction\Filter;
class CustomAction extends \Magento\Backend\App\Action
{
protected $filter;
protected $customerCollectionFactory;
protected $_helper;
public function __construct(Context $context, Filter $filter,
\MyModule\Helper\Data $helper,
\Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $customerCollectionFactory
) {
$this->filter = $filter;
$this->_helper = $helper;
$this->customerCollectionFactory = $customerCollectionFactory;
parent::__construct($context);
}
public function execute()
{
$collection = $this->filter->getCollection($this->customerCollectionFactory->create());
foreach ($collection as $item) {
$sms = $item->getEmail();
}
$resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
return $resultRedirect->setUrl($this->_redirect->getRefererUrl());
}
}
Instead of getEmail()
I need to get the customer's phone (if any). However function getTelephone()
doesn't seem to work. How can I access customer's phone?
Keep in mind that the customer is not associated with any order, so I can't get the phone from the order object
Best Answer
The telephone number is related to the customer's addresses and not to the customer's account. So a solution will be to get the customer's default billing or shipping and get the telephone number using the customerRepository
Magento\Customer\Api\CustomerRepositoryInterface
and the addressRepositoryMagento\Customer\Api\AddressRepositoryInterface
like