0

Iam Getting the below error

Recoverable Error: Object of class Magento\Framework\App\ObjectManager could not be converted to string in /var/www/html/development/amt/app/code/vendor/RequestForQuote/Controller/Index/Index.php on line 153 {"exception":"[object] (Exception(code: 0): Recoverable Error: Object of class Magento\Framework\App\ObjectManager could not be converted to string in /var/www/html/development/amt/app/code/vendor/RequestForQuote/Controller/Index/Index.php on line 153 at /var/www/html/development/amt/vendor/magento/framework/App/ErrorHandler.php:61)"} []

My Controller :

<?php

namespace Sm\RequestForQuote\Controller\Index;

use \Magento\Framework\App\Action\Context;
use \Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
use Magento\Contact\Model\ConfigInterface;
use Magento\Contact\Model\MailInterface;
use Magento\Framework\App\Request\DataPersistorInterface;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Exception\LocalizedException;
use Psr\Log\LoggerInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\DataObject;

class Index extends \Magento\Framework\App\Action\Action {
    /** @var  \Magento\Framework\View\Result\Page */

    protected $resultPageFactory;
     /**
     * @var DataPersistorInterface
     */
    private $dataPersistor;

    /**
     * @var Context
     */
    private $context;

    /**
     * @var MailInterface
     */
    private $mail;

    /**
     * @var LoggerInterface
     */
    private $logger;
    /*** @param \Magento\Framework\App\Action\Context $context*/

    protected $scopeConfig;

    protected $emailHelper;

     public function __construct(
        Context $context,
        ConfigInterface $contactsConfig,
        \Magento\Checkout\Model\Session $checkoutSession,
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
        \Sm\RequestForQuote\Helper\Email $emailHelper,
        PageFactory $resultPageFactory,
        MailInterface $mail,
        DataPersistorInterface $dataPersistor,
        LoggerInterface $logger = null
    ) {
        parent::__construct($context);
        $this->context = $context;
        $this->mail = $mail;
        $this->dataPersistor = $dataPersistor;
        $this->logger = $logger ?: ObjectManager::getInstance()->get(LoggerInterface::class);
        $this->resultPageFactory = $resultPageFactory;
        $this->customerRepositoryInterface = $customerRepositoryInterface;
        $this->_checkoutSession = $checkoutSession;
        $this->scopeConfig = $scopeConfig;
        $this->emailHelper = $emailHelper;
    }

    /**
     *
     * @return \Magento\Framework\View\Result\PageFactory
     */
    public function execute()
    {
        if (!$this->getRequest()->isPost()) {
            return $this->resultRedirectFactory->create()->setPath('/customer/account/');
        }
        try {
            $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
            $cart = $objectManager->get('\Magento\Checkout\Model\Cart');
            $this->sendEmail($cart);
            $this->messageManager->addSuccessMessage(
                __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.')
            );
            $cartObject = $objectManager->create('Magento\Checkout\Model\Cart')->truncate(); 
            $cartObject->saveQuote();
        } catch (LocalizedException $e) {
            $this->messageManager->addErrorMessage($e->getMessage());
        } catch (\Exception $e) {
            $this->logger->critical($e);
            $this->messageManager->addErrorMessage(
                __('An error occurred while processing your form. Please try again later.')
            );
        }
        $resultPage = $this->resultPageFactory->create();
        return $resultPage;
    }
    public function sendEmail($cart)
    {
        $country = $street = $post = $city = " ";
        $ad = [];   
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $customerSession = $objectManager->create('Magento\Customer\Model\Session');
        if ($customerSession->isLoggedIn()) {
            $customerSession->getCustomer();
            $name =  $customerSession->getCustomer()->getName();  // get  Full Name
            $email = $customerSession->getCustomer()->getEmail();
            $number = $customerSession->getCustomer()->getId();
            $customer = $this->customerRepositoryInterface->getById($number);
            $customerNumber = $customer->getCustomAttribute('customer_number')->getValue();
            foreach ($customer->getAddresses() as $address) {
                $country = $address->getCountryId();
                $ad = $address->getStreet();
                $street = $ad[0];
                $post = $address->getPostcode();
                $city = $address->getCity();
            }
        }

         $sender_name = $this->scopeConfig->getValue('requestforquote/sender/sender_name', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
         $sender_mail = $this->scopeConfig->getValue('requestforquote/sender/sender_mail', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
         $receiver_name = $this->scopeConfig->getValue('requestforquote/receiver/receiver_name', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
         $receiver_mail = $this->scopeConfig->getValue('requestforquote/receiver/receiver_mail', \Magento\Store\Model\ScopeInterface::SCOPE_STORE);


        /* Here we prepare data for our email  */
        /* Receiver Detail  */
        $receiverInfo = [
            'name' => $receiver_name,
            'email' => "[email protected]"
        ];


        /* Sender Detail  */
        $senderInfo = [
            'name' => $sender_name,
            'email' => "[email protected]"
        ];

        /* Assign values for your template variables  */
        $emailTemplateVariables = array();
        $emailTempVariables['name'] = $name;
        $emailTempVariables['email'] = $email;
        $emailTempVariables['customerNumber'] = $customerNumber;
        $emailTempVariables['country'] = $country;
        $emailTempVariables['street'] = $street;
        $emailTempVariables['post'] = $post;
        $emailTempVariables['city'] = $city;
        $emailTempVariables['items'] = $cart->getQuote()->getAllItems();


        /* We write send mail function in helper because if we want to 
           use same in other action then we can call it directly from helper */  

        /* call send mail method from helper or where you define it*/  
    $this->emailHelper->yourCustomMailSendMethod($emailTempVariables,$senderInfo,$receiverInfo);
    }

}

My Helper :

<?php
namespace vendor\RequestForQuote\Helper;

/**
 * Custom Module Email helper
 */
class Email extends \Magento\Framework\App\Helper\AbstractHelper
{
    const XML_PATH_EMAIL_TEMPLATE_FIELD  = 'vendoe/RequestForQuote/quote_email_template';
    /* Here section and group refer to name of section and group where you create this field in configuration*/

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $_scopeConfig;

    /**
     * Store manager
     *
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    protected $_storeManager;

    /**
     * @var \Magento\Framework\Translate\Inline\StateInterface
     */
    protected $inlineTranslation;

    /**
     * @var \Magento\Framework\Mail\Template\TransportBuilder
     */
    protected $transportBuilder;

    /**
     * @var string
    */
    protected $temp_id;

    /**
    * @param Magento\Framework\App\Helper\Context $context
    * @param Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig
    * @param Magento\Store\Model\StoreManagerInterface $storeManager
    * @param Magento\Framework\Translate\Inline\StateInterface $inlineTranslation
    * @param Magento\Framework\Mail\Template\TransportBuilder $transportBuilder
    */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
        \vendor\RequestForQuote\Model\Mail\Template\TransportBuilder $transportBuilder
    ) {
        $this->_scopeConfig = $context;
        parent::__construct($context);
        $this->_storeManager = $storeManager;
        $this->inlineTranslation = $inlineTranslation;
        $this->transportBuilder = $transportBuilder; 
    }

    /**
     * Return store configuration value of your template field that which id you set for template
     *
     * @param string $path
     * @param int $storeId
     * @return mixed
     */
    protected function getConfigValue($path, $storeId)
    {
        return $this->scopeConfig->getValue(
            $path,
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE,
            $storeId
        );
    }

    /**
     * Return store 
     *
     * @return Store
     */
    public function getStore()
    {
        return $this->_storeManager->getStore();
    }

    /**
     * Return template id according to store
     *
     * @return mixed
     */
    public function getTemplateId($xmlPath)
    {
        return $this->getConfigValue($xmlPath, $this->getStore()->getStoreId());
    }

    /**
     * [generateTemplate description]  with template file and tempaltes variables values                
     * @param  Mixed $emailTemplateVariables 
     * @param  Mixed $senderInfo             
     * @param  Mixed $receiverInfo           
     * @return void
     */
    public function generateTemplate($emailTemplateVariables,$senderInfo,$receiverInfo)
    {
        $name = str_replace(' ', '_',$emailTemplateVariables['name']);
        $fileName = "quote_".strtolower($name)."_".time(). '.csv';

        $content = "S.no,Sku,Name,Qty,Price\n";
        $items = $emailTemplateVariables['items'];
        $counter = 0;
        foreach($items as $item){
            $sku = $item->getSku();
            $name = $item->getName();
            $Qty = $item->getQty();
            $Price = $item->getPrice();
            $content.= ++$counter.','.$sku.','.$name.','.$Qty.','.$Price."\n";
        }
        $template =  $this->transportBuilder->setTemplateIdentifier('vendor_RequestForQuote_quote_email_template')
                ->setTemplateOptions(
                    [
                        'area' => \Magento\Framework\App\Area::AREA_FRONTEND, /* here you can defile area and
                                                                                 store of template for which you prepare it */
                        'store' => $this->_storeManager->getStore()->getId(),
                    ]
                )
                ->setTemplateVars($emailTemplateVariables)
                ->setFrom($senderInfo)
                ->addTo($receiverInfo['email'],$receiverInfo['name'])
                ->addAttachment($content, $fileName, 'application/csv');
        return $this;        
    }
    /**
     * [sendInvoicedOrderEmail description]                  
     * @param  Mixed $emailTemplateVariables 
     * @param  Mixed $senderInfo             
     * @param  Mixed $receiverInfo           
     * @return void
     */
    /* your send mail method*/
    public function yourCustomMailSendMethod($emailTemplateVariables, $senderInfo, $receiverInfo)
    {
        $this->temp_id = $this->getTemplateId('vendor_RequestForQuote_quote_email_template');
        $this->inlineTranslation->suspend();    
        $this->generateTemplate($emailTemplateVariables,$senderInfo,$receiverInfo);    
        $transport = $this->transportBuilder->getTransport();
        $transport->sendMessage();        
        $this->inlineTranslation->resume();
    }

}

When I used helper function it's give me error.

0

1 Answer 1

1

please avoid obectManager

Add this into your My Controller

 protected $emamilHelper;

 public function __construct(
    ..........................................
    \vendor\RequestForQuote\Helper\Email  $emamilHelper,
    ..........................................
) {
    ..........................................
    $this->emamilHelper = $emamilHelper;
    ..........................................
}

Now you can call Your Helper function like this

 $this->emamilHelper->HelperFunctionName(); //  call your helper function 
11
  • Iam getting blank page when doing this type
    – Sabareesh
    Commented Mar 27, 2020 at 10:19
  • @Sabareesh above is not full code only that part how to call helper function.
    – Msquare
    Commented Mar 27, 2020 at 10:21
  • $this->emailHelper->yourCustomMailSendMethod($emailTempVariables,$senderInfo,$receiverInfo); i used in that same way
    – Sabareesh
    Commented Mar 27, 2020 at 10:28
  • yes this is right way to call helper function
    – Msquare
    Commented Mar 27, 2020 at 10:29
  • But iam getting blank page if take this line iam getting the page
    – Sabareesh
    Commented Mar 27, 2020 at 10:31

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.