0

I want to display email address stored in backend into my header part. How can i get email address into my header.phtml file in magento2

Nafsss
  • 760
  • 13
  • 43

3 Answers3

6

Use helper to get email address in phtml. You can do it by following way.

In phtml:

$helper = $this->helper('Vendorname\Modulename\Helper\Data');
$email = $helper->getEmails();
//pass storeId  in getEmails if you want to get email for specific store

In helper define any function, For example getEmails().

<?php
namespace Vendorname\Modulename\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Store\Model\ScopeInterface;

class Data extends AbstractHelper
{
   public function getEmails($storeId = null) {
      return $this->scopeConfig->getValue('trans_email/ident_general/email', ScopeInterface::SCOPE_STORE, $storeId);
   }
}

I hope this will help you.

Sameer Bhayani
  • 1,874
  • 19
  • 34
1

objectManager is not recommended so there a better way of implementing it.

Add Below code in phtml file:

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        
$conf = $objectManager->get('Magento\Framework\App\Config\ScopeConfigInterface')->getValue('trans_email/ident_general/email');

echo $conf //print email address

More reference check link

Vishal Baraiya
  • 2,816
  • 1
  • 11
  • 22
1

As per magento2 object manager is bad practice, use ScopeConfigInterface to get backend stored email address. Pass section_id/group_id/field_id from system.xml to get config value. Try below code and please let me know if got any issue.

<?php
namespace Vendorname\Modulename\Block;

use Magento\Framework\View\Element\Template;
use Magento\Framework\App\Config\ScopeConfigInterface;

class Email extends Template
{
protected $scopeConfig;
public function __construct(Template\Context $context, ScopeConfigInterface $scopeConfig)
{
  $this->scopeConfig = $scopeConfig;
  return parent::__construct($context);
}
   public function getEmails() {

   return $this->scopeConfig->getValue('path/of/config', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);

 }
}
Rakesh Donga
  • 5,344
  • 2
  • 24
  • 57
Manish Chaubey
  • 513
  • 2
  • 8