0

I want to create plugin for contact form with two custom fields first-name and last-name to send email. anyone can help with this?

Thanks in advance.

in di.xml

    <config xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
  <type name="Magento\Contact\Controller\Index\Post">
         <plugin name="Convert_CustomContact_Plugin" type="Convert\CustomContact\Plugin\Post" sortOrder="10" disabled="false"  />
    </type>      
</config>

In plugin

<?php

namespace Convert\CustomContact\Plugin;
use Magento\Framework\App\Request\DataPersistorInterface ;
use Magento\Framework\App\Action\Context;
use Magento\Contact\Model\MailInterface;
use Magento\Framework\Escaper;
use Magento\Framework\Translate\Inline\StateInterface; 

class Post
{
    protected $inlineTranslation;
    protected $_escaper;

    public function __construct(
     DataPersistorInterface  $dataPersistor,
     Context $context,
     Escaper $escaper,
     StateInterface $inlineTranslation
    ) {
        $this->dataPersistor = $dataPersistor;
        $this->context = $context;
        $this->_escaper = $escaper;
        $this->inlineTranslation= $inlineTranslation;
    }


    public function afterExecute(\Magento\Contact\Controller\Index\Post $subject, $result)
    {
        // In the original method, dataPersistor is cleared if a message has been sent
        // so we can use it as an indicator to whether a user can be redirected somewhere else
        // or fall back to the result of the original method
         $post = $subject->getRequest()->getPostValue();   

        if ($post) { 
        $this->inlineTranslation->suspend();
        // $this->inlineTranslation->suspend();
        $postObject = new \Magento\Framework\DataObject();
        $postObject->setData($post);
        $error = false;
        $sender = [
            'firstname' => $this->_escaper->escapeHtml($post['firstname']),
            'lastname' => $this->_escaper->escapeHtml($post['lastname']),

            ];





        }
        return $result;
    }

}

2 Answers 2

0

Please try with below url : which have to create module for custom form.

https://magenticians.com/add-custom-field-in-magento-2-contact-page/

Please try with below code :

public function __construct(
    \Magento\Framework\App\Action\Context $context,
    \Magento\Framework\Mail\Template\TransportBuilder $transportBuilder,
    \Magento\Framework\Translate\Inline\StateInterface $inlineTranslation,
    \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfig,
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Framework\Escaper $escaper
) {
    parent::__construct($context);
    $this->_transportBuilder = $transportBuilder;
    $this->inlineTranslation = $inlineTranslation;
    $this->scopeConfig = $scopeConfig;
    $this->storeManager = $storeManager;
    $this->_escaper = $escaper;
}

/**
 * Post user question
 *
 * @return void
 * @throws \Exception
 */
public function execute()
{
    $post = $this->getRequest()->getPostValue();
    if (!$post) {
        $this->_redirect('*/*/');
        return;
    }

    $this->inlineTranslation->suspend();

    try {
        $postObject = new \Magento\Framework\DataObject();
        $postObject->setData($post);
        $error = false;

        $sender = [
            'firstname' => $this->_escaper->escapeHtml($post['firstname']),
            'lastname' => $this->_escaper->escapeHtml($post['lastname']),'email' => $this->_escaper->escapeHtml($post['email']),
        ];

        $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE; 
        $transport = $this->_transportBuilder
            ->setTemplateIdentifier('send_email_email_template') // this code we have mentioned in the email_templates.xml
            ->setTemplateOptions(
                [
                    'area' => \Magento\Framework\App\Area::AREA_FRONTEND, // this is using frontend area to get the template file
                    'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
                ]
            )
            ->setTemplateVars(['data' => $postObject])
            ->setFrom($sender)
            ->addTo($this->scopeConfig->getValue(self::XML_PATH_EMAIL_RECIPIENT, $storeScope))
            ->getTransport();

            $transport->sendMessage();
            $this->inlineTranslation->resume();
            $this->messageManager->addSuccess(
                __('Mail send successfully')
            );
            $this->_redirect('*/*/');
            return;
    } catch (\Exception $e) {
        $this->inlineTranslation->resume();
        $this->messageManager->addError(__('Something wrong.'.$e->getMessage())
        );
        $this->_redirect('*/*/');
        return;
    }
}

I hope its very helpful to you.

6
  • thanks for your help, but i have to use plugin for it. Can you suggest me with this?
    – trem jenny
    Commented Aug 1, 2019 at 8:22
  • yes please update que with your code. Commented Aug 1, 2019 at 8:26
  • i have updated my code, thanks.
    – trem jenny
    Commented Aug 1, 2019 at 8:37
  • where you are facing the issue ? Commented Aug 1, 2019 at 8:40
  • i want to create plugin for two fields last name and first name to send email in contact form , but the thing is that i dont know how to do ít, with the code above, i just get the value of the fields. I want to send email with these custom fields.
    – trem jenny
    Commented Aug 1, 2019 at 8:46
0

Plugin is not the right route with this particular change. Reason being if you add a field to the contact form template the magento contact controller will automatically catch values for these new fields.

In my extension I add a file field to the contact us form

https://github.com/DominicWatts/ContactAttachment

xml override

https://github.com/DominicWatts/ContactAttachment/blob/master/view/frontend/layout/contact_index_index.xml

New field

https://github.com/DominicWatts/ContactAttachment/blob/master/view/frontend/templates/form.phtml#L45-L50

You are going to have to create a new email template with the new fields

https://github.com/DominicWatts/ContactAttachment/blob/master/view/frontend/email/submitted_form.html#L25-L28

Then within magento add the transactional email. Then under system configuration use the contacts section to configure the use of the new template.

You shouldn't need to touch the controller as shown in other answer as magento automatically picks up other submitted fields.

Although as I've typed all this up I've realised that I've more or less summaried what's covered in the tutorial https://magenticians.com/add-custom-field-in-magento-2-contact-page/

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.