In this tutorial we learn how to use plugin in magento 2.
In below code we create a plugin to make a ajax hit for newsletter subscription for users rest of all setting are same as default magento provides.
Di.xml
1 2 3 4 5 6 7 8 |
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\Newsletter\Controller\Subscriber\NewAction"> <plugin name="Newsletter_Subscriber_NewAction" type="Arpitk\AjaxNewsLetter\Controller\Plugin\Subscriber\NewAction" sortOrder="10" disabled="false" /> </type> </config> |
New Controller extended from Magento\Newsletter\Controller\Subscriber\NewAction
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
<?php namespace Arpitk\AjaxNewsLetter\Controller\Plugin\Subscriber; use Magento\Customer\Api\AccountManagementInterface as CustomerAccountManagement; use Magento\Customer\Model\Session; use Magento\Customer\Model\Url as CustomerUrl; use Magento\Framework\App\Action\Context; use Magento\Store\Model\StoreManagerInterface; use Magento\Newsletter\Model\SubscriberFactory; /** * Class NewAction */ class NewAction extends \Magento\Newsletter\Controller\Subscriber\NewAction { /** * @var CustomerAccountManagement */ protected $customerAccountManagement; protected $resultJsonFactory; /** * Initialize dependencies. * * @param Context $context * @param SubscriberFactory $subscriberFactory * @param Session $customerSession * @param StoreManagerInterface $storeManager * @param CustomerUrl $customerUrl * @param CustomerAccountManagement $customerAccountManagement */ public function __construct( Context $context, SubscriberFactory $subscriberFactory, Session $customerSession, StoreManagerInterface $storeManager, CustomerUrl $customerUrl, CustomerAccountManagement $customerAccountManagement, \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory ) { $this->customerAccountManagement = $customerAccountManagement; $this->resultJsonFactory = $resultJsonFactory; parent::__construct( $context, $subscriberFactory, $customerSession, $storeManager, $customerUrl, $customerAccountManagement ); } /** * Retrieve available Order fields list * * @return array */ public function aroundExecute($subject, $procede) { $response = []; if ($this->getRequest()->isPost() && $this->getRequest()->getPost('email')) { $email = (string)$this->getRequest()->getPost('email'); try { // $this->validateEmailFormat($email); $this->validateGuestSubscription(); $this->validateEmailAvailable($email); $status = $this->_subscriberFactory->create()->subscribe($email); if ($status == \Magento\Newsletter\Model\Subscriber::STATUS_NOT_ACTIVE) { $response = [ 'status' => 'OK', 'msg' => 'The confirmation request has been sent.', ]; } else { $response = [ 'status' => 'OK', 'msg' => 'Thank you for your subscription.', ]; } } catch (\Magento\Framework\Exception\LocalizedException $e) { $response = [ 'status' => 'ERROR', 'msg' => __('There was a problem with the subscription: %1', $e->getMessage()), ]; } catch (\Exception $e) { $response = [ 'status' => 'ERROR', 'msg' => __('Something went wrong with the subscription. %1',$e->getMessage()), ]; } } return $this->resultJsonFactory->create()->setData($response); } } |
newsletter_subscripe.phtml (Override it for core newsletter_subscripe.phtml)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<div class="block newsletter"> <div class="title"><strong>Newsletter </strong></div> <div class="content"> <form class="form subscribe" method="post" data-mage-init='{"validation": {"errorClass": "mage-error"}}' id="newsletter-validate-detail"> <div class="field newsletter"> <label class="label" for="newsletter"><span><?php /* @escapeNotVerified */ echo __('Sign Up for Our Newsletter:') ?></span></label> <div class="control"> <input name="email" type="email" id="newsletter" placeholder="<?php /* @escapeNotVerified */ echo __('Enter your email address') ?>" data-validate="{required:true, 'validate-email':true}"/> </div> </div> <div class="actions"> <button class="action subscribe primary submit" title="<?php /* @escapeNotVerified */ echo __('Subscribe sad') ?>" type="submit"> <span><?php /* @escapeNotVerified */ echo __('Subscribe') ?></span> </button> </div> <div class="scg-msg"> <div class="messages"> </div> </div> </form> </div> </div> <?php $ajaxurl = $block->escapeHtml($block->getFormActionUrl()); $formid = "#newsletter-validate-detail"; ?> <script type="text/x-magento-init"> { "#newsletter-validate-detail": { "Arpitk_AjaxNewsLetter/js/formsubmitnow": { "AjaxUrl": "<?php echo $ajaxurl; ?>", "FormId": "<?php echo $formid; ?>" } } } </script> |
formsubmitnow.js file for Ajax request
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
define([ "jquery", "jquery/ui" ], function($){ "use strict"; function main(config, element) { var $element = $(element); var AjaxUrl = config.AjaxUrl; var FormId = config.FormId; $(document).on('click','.submit',function() { event.preventDefault(); var dataForm = $(FormId); dataForm.mage('validation', {}); if (dataForm.valid()){ var param = dataForm.serialize(); ajaxformsubmit(param,AjaxUrl,FormId); } }); }; function ajaxformsubmit(param,AjaxUrl,formId){ $.ajax({ url: AjaxUrl, prefilterUrl: function(url) { return url && url.replace(new RegExp('^https://'), 'http://'); }, type: 'POST', data: param, success: function (data){ if(data.status != "ERROR"){ $(".submit").attr("disabled", false); $('.input-blank').val(''); $(formId+' .scg-msg > .messages').html('<div class="message-success success message" ><div >' + data.msg + '</div></div>'); }else{ $(formId+' .scg-msg > .messages').html('<div class="message-error error message" >' + '<div>'+data.msg +'</div></div>'); } loadingMessage.html(data.msg); }, }); } return main; }); |
Welcome to our blog!