How to override createpost controller magento 2
For adding custom functionality when we create customer account at that time Overriding createpost controller is needed because changing in core magento files are bad idea.
For overriding we have to create preference for it.
Create preference in di.xml file. Path can be Magesan/Extension/etc/frontend/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Customer\Controller\Account\CreatePost" type="Magesan\Extension\Controller\Account\CreatePost" />
</config>
Create CreatePost.php at Magesan\Extension\Controller\Account\CreatePost.php
<?php
namespace Magesan\Extension\Controller\Account;
use Magento\Customer\Model\Account\Redirect as AccountRedirect;
use Magento\Framework\Api\DataObjectHelper;
use Magento\Framework\App\Action\Context;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Message\MessageInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Customer\Api\AccountManagementInterface;
use Magento\Customer\Helper\Address;
use Magento\Framework\UrlFactory;
use Magento\Customer\Model\Metadata\FormFactory;
use Magento\Newsletter\Model\SubscriberFactory;
use Magento\Customer\Api\Data\RegionInterfaceFactory;
use Magento\Customer\Api\Data\AddressInterfaceFactory;
use Magento\Customer\Api\Data\CustomerInterfaceFactory;
use Magento\Customer\Model\Url as CustomerUrl;
use Magento\Customer\Model\Registration;
use Magento\Framework\Escaper;
use Magento\Customer\Model\CustomerExtractor;
use Magento\Framework\Exception\StateException;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Customer\Api\CustomerRepositoryInterface;
class CreatePost extends \Magento\Customer\Controller\Account\CreatePost
{
/**
* @var \Magento\Customer\Api\AccountManagementInterface
*/
protected $accountManagement;
/**
* @var \Magento\Customer\Helper\Address
*/
protected $addressHelper;
/**
* @var \Magento\Customer\Model\Metadata\FormFactory
*/
protected $formFactory;
/**
* @var \Magento\Newsletter\Model\SubscriberFactory
*/
protected $subscriberFactory;
/**
* @var \Magento\Customer\Api\Data\RegionInterfaceFactory
*/
protected $regionDataFactory;
/**
* @var \Magento\Customer\Api\Data\AddressInterfaceFactory
*/
protected $addressDataFactory;
/**
* @var \Magento\Customer\Model\Registration
*/
protected $registration;
/**
* @var \Magento\Customer\Api\Data\CustomerInterfaceFactory
*/
protected $customerDataFactory;
/**
* @var \Magento\Customer\Model\Url
*/
protected $customerUrl;
/**
* @var \Magento\Framework\Escaper
*/
protected $escaper;
/**
* @var \Magento\Customer\Model\CustomerExtractor
*/
protected $customerExtractor;
/**
* @var \Magento\Framework\UrlInterface
*/
protected $urlModel;
/**
* @var \Magento\Framework\Api\DataObjectHelper
*/
protected $dataObjectHelper;
/**
* @var Session
*/
protected $session;
/**
* @var AccountRedirect
*/
private $accountRedirect;
/**
* @var \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
*/
private $cookieMetadataFactory;
/**
* @var \Magento\Framework\Stdlib\Cookie\PhpCookieManager
*/
private $cookieMetadataManager;
/**
* @var Validator
*/
private $formKeyValidator;
public function __construct(
Context $context,
Session $customerSession,
ScopeConfigInterface $scopeConfig,
StoreManagerInterface $storeManager,
AccountManagementInterface $accountManagement,
Address $addressHelper,
UrlFactory $urlFactory,
FormFactory $formFactory,
SubscriberFactory $subscriberFactory,
RegionInterfaceFactory $regionDataFactory,
AddressInterfaceFactory $addressDataFactory,
CustomerInterfaceFactory $customerDataFactory,
CustomerUrl $customerUrl,
Registration $registration,
Escaper $escaper,
CustomerExtractor $customerExtractor,
DataObjectHelper $dataObjectHelper,
AccountRedirect $accountRedirect,
Validator $formKeyValidator = null,
CustomerRepositoryInterface $customerRepositoryInterface
) {
$this->formKeyValidator = $formKeyValidator ?: ObjectManager::getInstance()->get(Validator::class);
$this->accountRedirect = $accountRedirect;
$this->scopeConfig = $scopeConfig;
parent::__construct(
$context,
$customerSession,
$scopeConfig,
$storeManager,
$accountManagement,
$addressHelper,
$urlFactory,
$formFactory,
$subscriberFactory,
$regionDataFactory,
$addressDataFactory,
$customerDataFactory,
$customerUrl,
$registration,
$escaper,
$customerExtractor,
$dataObjectHelper,
$accountRedirect,
$customerRepositoryInterface
);
}
/**
* Retrieve cookie manager
*
* @deprecated 100.1.0
* @return \Magento\Framework\Stdlib\Cookie\PhpCookieManager
*/
private function getCookieManager()
{
if (!$this->cookieMetadataManager) {
$this->cookieMetadataManager = ObjectManager::getInstance()->get(
\Magento\Framework\Stdlib\Cookie\PhpCookieManager::class
);
}
return $this->cookieMetadataManager;
}
/**
* Retrieve cookie metadata factory
*
* @deprecated 100.1.0
* @return \Magento\Framework\Stdlib\Cookie\CookieMetadataFactory
*/
private function getCookieMetadataFactory()
{
if (!$this->cookieMetadataFactory) {
$this->cookieMetadataFactory = ObjectManager::getInstance()->get(
\Magento\Framework\Stdlib\Cookie\CookieMetadataFactory::class
);
}
return $this->cookieMetadataFactory;
}
/**
* Create customer account action
*
* @return void
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function execute()
{
var_dump('magesan execute');
exit;
/** @var Redirect $resultRedirect */
$resultRedirect = $this->resultRedirectFactory->create();
if ($this->session->isLoggedIn() || !$this->registration->isAllowed()) {
$resultRedirect->setPath('*/*/');
return $resultRedirect;
}
if (
!$this->getRequest()->isPost()
|| !$this->formKeyValidator->validate($this->getRequest())
) {
$url = $this->urlModel->getUrl('*/*/create', ['_secure' => true]);
return $this->resultRedirectFactory->create()
->setUrl($this->_redirect->error($url));
}
$this->session->regenerateId();
try {
$address = $this->extractAddress();
$addresses = $address === null ? [] : [$address];
$customer = $this->customerExtractor->extract('customer_account_create', $this->_request);
$customer->setAddresses($addresses);
$password = $this->getRequest()->getParam('password');
$confirmation = $this->getRequest()->getParam('password_confirmation');
$redirectUrl = $this->session->getBeforeAuthUrl();
$this->checkPasswordConfirmation($password, $confirmation);
$extensionAttributes = $customer->getExtensionAttributes();
$extensionAttributes->setIsSubscribed($this->getRequest()->getParam('is_subscribed', false));
$customer->setExtensionAttributes($extensionAttributes);
$customer = $this->accountManagement
->createAccount($customer, $password, $redirectUrl);
$this->_eventManager->dispatch(
'customer_register_success',
['account_controller' => $this, 'customer' => $customer]
);
$confirmationStatus = $this->accountManagement->getConfirmationStatus($customer->getId());
if ($confirmationStatus === AccountManagementInterface::ACCOUNT_CONFIRMATION_REQUIRED) {
$this->messageManager->addComplexSuccessMessage(
'confirmAccountSuccessMessage',
[
'url' => $this->customerUrl->getEmailConfirmationUrl($customer->getEmail()),
]
);
$url = $this->urlModel->getUrl('*/*/index', ['_secure' => true]);
$resultRedirect->setUrl($this->_redirect->success($url));
} else {
$this->session->setCustomerDataAsLoggedIn($customer);
$this->messageManager->addMessage($this->getMessageManagerSuccessMessage());
$requestedRedirect = $this->accountRedirect->getRedirectCookie();
if (!$this->scopeConfig->getValue('customer/startup/redirect_dashboard') && $requestedRedirect) {
$resultRedirect->setUrl($this->_redirect->success($requestedRedirect));
$this->accountRedirect->clearRedirectCookie();
return $resultRedirect;
}
$resultRedirect = $this->accountRedirect->getRedirect();
// $resultRedirect->setPath('customer/address/new'); // It will redirect to customer address after account creation
}
if ($this->getCookieManager()->getCookie('mage-cache-sessid')) {
$metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
$metadata->setPath('/');
$this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);
}
return $resultRedirect;
} catch (StateException $e) {
$this->messageManager->addComplexErrorMessage(
'customerAlreadyExistsErrorMessage',
[
'url' => $this->urlModel->getUrl('customer/account/forgotpassword'),
]
);
} catch (InputException $e) {
$this->messageManager->addErrorMessage($e->getMessage());
foreach ($e->getErrors() as $error) {
$this->messageManager->addErrorMessage($error->getMessage());
}
} catch (LocalizedException $e) {
$this->messageManager->addErrorMessage($e->getMessage());
} catch (\Exception $e) {
$this->messageManager->addExceptionMessage($e, __('We can\'t save the customer.'));
}
$this->session->setCustomerFormData($this->getRequest()->getPostValue());
$defaultUrl = $this->urlModel->getUrl('*/*/create', ['_secure' => true]);
return $resultRedirect->setUrl($this->_redirect->error($defaultUrl));
}
/**
* Retrieve success message manager message
*
* @return MessageInterface
* @throws \Magento\Framework\Exception\NoSuchEntityException
*/
private function getMessageManagerSuccessMessage(): MessageInterface
{
if ($this->addressHelper->isVatValidationEnabled()) {
if ($this->addressHelper->getTaxCalculationAddressType() == Address::TYPE_SHIPPING) {
$identifier = 'customerVatShippingAddressSuccessMessage';
} else {
$identifier = 'customerVatBillingAddressSuccessMessage';
}
$message = $this->messageManager
->createMessage(MessageInterface::TYPE_SUCCESS, $identifier)
->setData(
[
'url' => $this->urlModel->getUrl('customer/address/edit'),
]
);
} else {
$message = $this->messageManager
->createMessage(MessageInterface::TYPE_SUCCESS)
->setText(
__('Thank you for registering with %1.', $this->storeManager->getStore()->getFrontendName())
);
}
return $message;
}
}
Alexandr
Perfect example for overriding. Keep good work doing mate!
BennySoinO
Keep good working doing buddy. Nice article
skyreveryrax
Nice article to remember how we can increase the memory limit.
BennySoinO
Very well pointed.
BennySoinO
Nice