Is there a Magento 2 function like loadByCode for admin created Newsletter templates?
If not, how are you supposed to retrieve newsletter created in admin?
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityThis method is not available. So try following way:
Inject using DI:
public function __construct( \Magento\Newsletter\Model\TemplateFactory $newsletterFactory ) { $this->newsletterFactory = $newsletterFactory; }
Now use following way:
$template_code = 'abc'; $newsletter = $this->newsletterFactory->create()->load($template_code, 'template_code'); print_r($newsletter->getData());
Another Way
Inject using DI:
public function __construct( \Magento\Newsletter\Model\ResourceModel\Template\CollectionFactory $newsletterCollectionFactory ) { $this->newsletterCollectionFactory = $newsletterCollectionFactory; }
Now use following way:
$template_code = 'abc'; $newsletterCollection = $this->newsletterCollectionFactory->create()->addFieldToFilter('template_code', $template_code); foreach ($newsletterCollection as $newsletter) { print_r($newsletter->getData()); }
[Update]
how do you actually send the newsletter template after loading it?
$template_code = 'abc'; $newsletter = $this->newsletterFactory->create()->load($template_code, 'template_code'); $this->transportBuilder->setTemplateData( [ 'template_subject' => $newsletter->getTemplateSubject(), 'template_text' => $this->getTemplateText(), 'template_styles' => $this->getTemplateStyles(), 'template_filter' => $this->templateFilter, 'template_type' => 2, // 2 for html ] ); /* Magento\Newsletter\Model\ResourceModel\Subscriber\CollectionFactory*/ $collection = $this->subscriberCollectionFactory->create()->useOnlyUnsent()->showCustomerInfo()->setPageSize( 20 )->setCurPage( 1 )->load(); /** @var \Magento\Newsletter\Model\Subscriber $item */ foreach ($collection->getItems() as $item) { $transport = $this->transportBuilder->setTemplateOptions( ['area' => \Magento\Framework\App\Area::AREA_FRONTEND, 'store' => $item->getStoreId()] )->setTemplateVars( ['subscriber' => $item] )->setFrom( ['name' => 'sent from name', 'email' => '[email protected]'] )->addTo( $item->getSubscriberEmail(), $item->getSubscriberFullName() )->getTransport(); try { $transport->sendMessage(); } catch (\Magento\Framework\Exception\MailException $e) { } }