I disabled the customer register from the frontend and I want only to create customers from backend. when I create customer in (Customers -> All Customers -> Add New Customer) I want to specify the password for the customer, I found a free module from kiwicommerce called Customer Password, but it only work in edit customer.
4 Answers
You need to create the custom customer attributes programmatically as the Password and Confirm Password fields so please follow this referral link.
or
https://www.truecodex.com/course/magento-2/how-to-add-custom-field-in-magento-2-registration-form
-
I saw this solution before but its for a custom attribute, I want to add password in the create customer form in backend only, if you do this there will be: 1- Duplicate data in database. 2- 2 more passwords field in registration page. 3- Need to handle the registration event by creating observer and handle the logic, that's why I asked the question. Thanks for your answer. Commented Sep 30, 2021 at 9:58
You can get this functionality easily by installing this extension click here
Hope this will help you.
Happy Coding
-
I already mentioned this extension in the question, I already had this module installed, but it only shows in the edit user page, I want to extend it's functionality to be shown in the add customer page in backend. Commented Sep 30, 2021 at 10:02
namespace VendorName\ModuleName\Block\Adminhtml\Customer\Edit;
use Magento\Customer\Controller\RegistryConstants;
use Magento\Ui\Component\Layout\Tabs\TabInterface;
use Magento\Backend\Block\Widget\Form;
use Magento\Backend\Block\Widget\Form\Generic;
/**
* Customer account form block
*/
class Tabs extends Generic implements TabInterface
{
/**
* @var \Magento\Store\Model\System\Store
*/
protected $_systemStore;
/**
* Core registry
*
* @var \Magento\Framework\Registry
*/
protected $_coreRegistry;
/**
* @param \Magento\Backend\Block\Template\Context $context
* @param \Magento\Framework\Registry $registry
* @param array $data
*/
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Framework\Registry $registry,
\Magento\Framework\Data\FormFactory $formFactory,
\Magento\Store\Model\System\Store $systemStore,
array $data = []
) {
$this->_coreRegistry = $registry;
$this->_systemStore = $systemStore;
parent::__construct($context, $registry, $formFactory, $data);
}
/**
* @return string|null
*/
public function getCustomerId()
{
return $this->_coreRegistry->registry(RegistryConstants::CURRENT_CUSTOMER_ID);
}
/**
* @return \Magento\Framework\Phrase
*/
public function getTabLabel()
{
return __('Demo Tab');
}
/**
* @return \Magento\Framework\Phrase
*/
public function getTabTitle()
{
return __('Demo Tab');
}
/**
* @return bool
*/
public function canShowTab()
{
if ($this->getCustomerId()) {
return true;
}
return false;
}
/**
* @return bool
*/
public function isHidden()
{
if ($this->getCustomerId()) {
return false;
}
return true;
}
/**
* Tab class getter
*
* @return string
*/
public function getTabClass()
{
return '';
}
/**
* Return URL link to Tab content
*
* @return string
*/
public function getTabUrl()
{
return '';
}
/**
* Tab should be loaded trough Ajax call
*
* @return bool
*/
public function isAjaxLoaded()
{
return false;
}
public function initForm()
{
if (!$this->canShowTab()) {
return $this;
}
/**@var \Magento\Framework\Data\Form $form */
$form = $this->_formFactory->create();
$form->setHtmlIdPrefix('myform_');
$fieldset = $form->addFieldset('base_fieldset', ['legend' => __('Fields Information')]);
$fieldset->addField(
'demo_field',
'text',
[
'name' => 'demo_field',
'data-form-part' => $this->getData('target_form'),
'label' => __('Demo Field in Customer Section'),
'title' => __('Demo Field in Customer Section')
]
);
$this->setForm($form);
return $this;
}
/**
* @return string
*/
protected function _toHtml()
{
if ($this->canShowTab()) {
$this->initForm();
return parent::_toHtml();
} else {
return '';
}
}
}
After that, you can able to get this field
/** @var \Magento\Framework\App\RequestInterface $request */
$request = $this->getRequest();
$originalRequestData = $request->getPostValue();
echo $originalRequestData['demo_field'];
Create Plugin for getting data during save.
<?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\Customer\Controller\Adminhtml\Index\Save">
<plugin name="sr_customer_save" type="VendorName\ModuleName\Plugin\Customer\Controller\Adminhtml\Index\Save" sortOrder="1"/>
</type>
</config>
namespace VendorName\ModuleName\Plugin\Customer\Controller\Adminhtml\Index;
class Save
{
public function afterExecute(
\Magento\Customer\Controller\Adminhtml\Index\Save $subject,
$result
) {
$demoField = $subject->getRequest()->getParam('demo_field');
error_log($demoField);
return $result;
}
}
Hope it will help you. Thank you.
-
I don't understand these blocks of code, I tried to understand it but I trying to understand where to put these codes. 1- Create a block file Block\Adminhtml\Customer\Edit in my custom module. 2- The Second block of code didn't understand it at all, all I got that it's an interface. 3- The Third is for creating a plugin, as I think it could be done with an observer better as done in the module. 4- The fourth code is overriding the save action in the index controller. That's not what I need, I need to add password filed when create customer from backend. Thanks for your time and help :) Commented Sep 30, 2021 at 10:18
you can reset Password from customer edit form instead of customer create form.
-> VENDOR/MODULE/view/adminhtml/layout/customer_index_edit.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="admin-2columns-left"
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceContainer name="customer_edit_tab_view">
<block class="VENDOR\MODULE\Block\Adminhtml\Customer\Edit\Tab\View\SetPassword" name="update-customer-password" after="customer_form" template="VENDOR_MODULE::update_password.phtml"/>
</referenceContainer>
</body>
</page>
-> VENDOR/MODULE/view/adminhtml/templates/update_password.phtml
<div class="admin__scope-old">
<div class="fieldset-wrapper customer-set-password">
<div class="fieldset-wrapper-title">
<span class="title"><?= $block->escapeHtml(__('Set customer password')) ?></span>
</div>
<div class="fieldset-wrapper-content">
<form method="POST" action="<?= $block->getUrl('admincustomroute/index/setpassword') ?>">
<?= $block->getBlockHtml('formkey') ?>
<input type="hidden" name="id" value="<?= $block->getCustomerId() ?>"/>
<input type="password" name="password" id="newPassword" class="admin__control-text"/>
<span onclick="togglePasswordVisibility('newPassword')" class="action-default toggle-password" title="<?= $block->escapeHtml(__('Toggle password visibility')) ?>">👁</span>
<button type="submit" class="primary"><?= $block->escapeHtml(__('Set password')) ?></button>
</form>
</div>
</div>
</div>
<script>
function togglePasswordVisibility(id) {
var el = document.getElementById(id);
if (el.type === "password") {
el.type = "text";
} else {
el.type = "password";
}
}
</script>
-> VENDOR/MODULE/etc/adminhtml/routes.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<router id="admin">
<route id="admincustomroute" frontName="admincustomroute">
<module name="VENDOR_MODULE"/>
</route>
</router>
</config>
-> VENDOR/MODULE/Block/Adminhtml/Customer/Edit/Tab/View/SetPassword.php
<?php
namespace VENDOR\MODULE\Block\Adminhtml\Customer\Edit\Tab\View;
use Magento\Customer\Block\Adminhtml\Edit\Tab\View\PersonalInfo;
class SetPassword extends PersonalInfo
{
protected function _toHtml()
{
return parent::_toHtml();
}
}
-> VENDOR/MODULE/Controller/Adminhtml/Index/SetPassword.php
<?php
namespace VENDOR\MODULE\Controller\Adminhtml\Index;
use Magento\Backend\App\Action\Context;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Customer\Model\CustomerRegistry;
use Magento\Framework\Encryption\EncryptorInterface;
use Magento\Framework\Exception\InputException;
class SetPassword extends \Magento\Backend\App\Action
{
private $customerRegistry;
private $customerRepository;
private $encryptor;
public function __construct(
Context $context,
CustomerRegistry $customerRegistry,
CustomerRepositoryInterface $customerRepository,
EncryptorInterface $encryptor
) {
parent::__construct($context);
$this->customerRegistry = $customerRegistry;
$this->customerRepository = $customerRepository;
$this->encryptor = $encryptor;
}
protected function _isAllowed()
{
return true;
}
public function execute()
{
$customerId = (int)$this->getRequest()->getPost('id');
$newPassword = (string)$this->getRequest()->getPost('password');
try {
$this->validateNewPassword($newPassword);
$newPasswordHash = $this->encryptor->getHash($newPassword, true);
$customer = $this->customerRepository->getById($customerId);
$customerSecure = $this->customerRegistry->retrieveSecureData($customer->getId());
$customerSecure->setPasswordHash($newPasswordHash);
$this->customerRepository->save($customer);
$this->messageManager->addSuccessMessage(__("You updated this customer's password."));
}
catch (InputException $e) {
$this->messageManager->addErrorMessage($e->getMessage());
}
catch (\Exception $exception) {
$this->messageManager->addErrorMessage(__('Something went wrong while saving the new password.'));
}
return $this->_redirect('customer/index/edit', ['id' => $customerId]);
}
protected function validateNewPassword($password)
{
if (iconv_strlen($password) <= 0) {
throw new InputException(__('Please enter a new password.'));
}
}
}