Magento 2检查客户是否订阅了新闻通讯


8

我正在开发此自定义xml导出/导入。在magento 2中,如何检查客户是否订阅了新闻通讯?现在,我正在加载客户工厂。

\Magento\Framework\App\ObjectManager::getInstance()->create('Magento\Customer\Model\Customer');

但这并没有提供有关新闻通讯的信息,我是否还需要加载其他模型?

Answers:


21

首先将\Magento\Newsletter\Model\Subscriber类注入您的构造函数中:

protected $_subscriber;

public function __construct(
    ...
    \Magento\Newsletter\Model\Subscriber $subscriber
    ...
){
    ...
    $this->_subscriber= $subscriber;
    ...
}

那你有两种可能的情况

假设您有客户电子邮件

然后,在您的代码中,可以调用以下代码来检查客户是否已订阅新闻通讯:

$checkSubscriber = $this->_subscriber->loadByEmail($customerEmail);

if ($checkSubscriber->isSubscribed()) {
    // Customer is subscribed
} else {
    // Customer is not subscribed
}

假设您有客户ID

您可以调用以下代码:

$checkSubscriber = $this->_subscriber->loadByCustomerId($customerId);

if ($checkSubscriber->isSubscribed()) {
    // Customer is subscribed
} else {
    // Customer is not subscribed
}

您将在哪里执行此代码?
styzzz
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.