3

I have used below code in my controller

use Magento\Customer\Api\Data\CustomerInterfaceFactory;

class editPost extends \Magento\Framework\App\Action\Action
{
  protected $_customer; 
  protected $customerFactory;
  public function __construct( 
  \Magento\Framework\App\Action\Context $context, 
  \Magento\Customer\Model\Customer $customer,
  \Magento\Customer\Model\CustomerFactory $customerFactory
  ) { 
   $this->_customer = $customer; 
   $this->customerFactory  = $customerFactory;
   parent::__construct($context); 
  } 
public function execute()
{       
        if ($this->getRequest()->isPost() && $this->getRequest()->getParam('user_id', false)) {
        $userId = $this->getRequest()->getParam('user_id', false);

        $oldUser = $this->_getUser($userId);
        $user = $this->customerFactory->create();
        $user->load(null)
            ->setId($userId)
            ->setWebsiteId($oldUser->getWebsiteId());
        /* $user = $this->_customer->load()
                ->setId($userId)
                ->setWebsiteId($oldUser->getWebsiteId()); */

        $password = $oldUser->getPassword();

        $fields = $this->_fieldsetConfig->getFieldset('customer_account');
        $data = $this->getRequest()->getPost();

        $defaultFields = array();
        foreach ($fields as $code=>$node) {
            $defaultFields[] = $code;
            if ((isset($node['create'])) && isset($data[$code])){
                $user->setData($code, $data[$code]);
            }
        }
        $customerattr = $this->helperData->getCustomerUserDefinedAttributes();
        foreach ($customerattr as $_customerattr) {
            if (isset($data[$_customerattr->getAttributeCode()]) && (!in_array($_customerattr, $defaultFields))) {
                $user->setData($_customerattr->getAttributeCode(), $data[$_customerattr->getAttributeCode()]);
            }
        }

       // $errors = $user->validate();
        $errors = array();
        if (!is_array($errors)) {
            $errors = array();
        }
        if ($oldUser->getGroupId()) {
            $user->setGroupId($oldUser->getGroupId());
        }


        if ($this->getRequest()->getParam('change_password')) {
            $currPass = $this->getRequest()->getPost('current_password');
            $newPass  = $this->getRequest()->getPost('password');
            $confPass  = $this->getRequest()->getPost('confirmation');

            if (empty($currPass) || empty($newPass) || empty($confPass)) {
                $errors[] = $this->__('Password fields can\'t be empty.');
            }

            if ($newPass != $confPass) {
                $errors[] = $this->__('Please make sure your passwords match.');
            }

            $oldPass = $oldUser->getPasswordHash();
            $pos = strpos($oldPass, ':');
            if ($pos !== false) {
                list($_salt, $salt) = explode(':', $oldPass);
            } else {
                $salt = false;
            }

            if ($user->hashPassword($currPass, $salt) == $oldPass) {
                $user->setPassword($newPass);
            } else {
                $errors[] = $this->__('Invalid current password');
            }
        }

        if (!empty($errors)) {
            foreach ($errors as $message) {                
                $this->_messageManager->addError($message);
            }
            return $this->_redirect('inkindcustomer/subuser/viewuser/', array('user_id' => $userId));
        }

        try {
            $user->save();
            $this->_messageManager->addSuccess(__('User information was successfully saved.'));
            return $this->_redirect('inkindcustomer/subuser/listuser/');
        }               
        catch (\Exception $e){
           $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e->getMessage());
           $this->_messageManager->addError(__('Can\'t save user'));
           return $this->_redirect('inkindcustomer/subuser/listuser/');
        } 
    }
 }

private function _getUser($id)
{
    //$customerObj = $this->_objectManager->create('Magento\Customer\Model\Customer')->load($id);
    $customerObj = $this->_customer->load($id);
    return $customerObj;

 }
}

Customer is not saving

Here is the code used on m1.

 if ($this->getRequest()->isPost() && $this->getRequest()->getParam('user_id', false)) {
        $userId = $this->getRequest()->getParam('user_id', false);
        $oldUser = $this->_getUser($userId);
        $user = Mage::getModel('customer/customer')
            ->setId($userId)
            ->setWebsiteId($oldUser->getWebsiteId());

        $password = $oldUser->getPassword();




        $fields = Mage::getConfig()->getFieldset('customer_account');
        $data = $this->getRequest()->getPost();

        $defaultFields = array();
        foreach ($fields as $code=>$node) {
            $defaultFields[] = $code;
            if ($node->is('update') && isset($data[$code])){
                $user->setData($code, $data[$code]);
            }
        }
        $customerattr = Mage::helper('inkind_customer')->getCustomerUserDefinedAttributes();
        foreach ($customerattr as $_customerattr) {
            if (isset($data[$_customerattr->getAttributeCode()]) && (!in_array($_customerattr, $defaultFields))) {
                $user->setData($_customerattr->getAttributeCode(), $data[$_customerattr->getAttributeCode()]);
            }
        }

        $errors = $user->validate();
        if (!is_array($errors)) {
            $errors = array();
        }
        if ($oldUser->getGroupId()) {
            $user->setGroupId($oldUser->getGroupId());
        }


        if ($this->getRequest()->getParam('change_password')) {
            $currPass = $this->getRequest()->getPost('current_password');
            $newPass  = $this->getRequest()->getPost('password');
            $confPass  = $this->getRequest()->getPost('confirmation');

            if (empty($currPass) || empty($newPass) || empty($confPass)) {
                $errors[] = $this->__('Password fields can\'t be empty.');
            }

            if ($newPass != $confPass) {
                $errors[] = $this->__('Please make sure your passwords match.');
            }

            $oldPass = $oldUser->getPasswordHash();
            $pos = strpos($oldPass, ':');
            if ($pos !== false) {
                list($_salt, $salt) = explode(':', $oldPass);
            } else {
                $salt = false;
            }

            if ($user->hashPassword($currPass, $salt) == $oldPass) {
                $user->setPassword($newPass);
            } else {
                $errors[] = $this->__('Invalid current password');
            }
        }

        if (!empty($errors)) {
            foreach ($errors as $message) {
                $this->_getSession()->addError($message);
            }
            $this->_redirect('*/*/view', array('user_id' => $userId));
            return $this;
        }

        try {
            $user->save();
            $this->_getSession()->addSuccess($this->__('User information was successfully saved'));

            $this->_redirect('*/*/list');
            return;
        }
        catch (Mage_Core_Exception $e) {
            $this->_getSession()->addError($e->getMessage());
        }
        catch (Exception $e) {
            $this->_getSession()->addException($e, $this->__('Can\'t save user'));
        }
    }

Where is mistake please anyone suggest me

  • Hi, you should try $this->_customer->load($userId) instead of setId($userId) in your execute function. – Taschert Aug 7 '18 at 15:54
  • I am converting m1 code to m2, there it is used like that only, i am attaching that code also, please check my updated question – jafar pinjar Aug 7 '18 at 15:56
4

Use factory pattern that is bridge to connect incomplete object in magento 2.

use below code. I have changed customer model to factory pattern class. That is auto generated code concept of magento 2 you do not need to write any factory class. Magento managed by itself.

<?php 

use Magento\Customer\Model\ResourceModel\CustomerFactory as CustomerResourceFactory;

class editPost extends \Magento\Framework\App\Action\Action
{
    protected $_customer; 

    /**
     * @var CustomerResourceFactory
     */
    protected $customerResourceFactory;

    public function __construct( 
        \Magento\Framework\App\Action\Context $context,
        CustomerResourceFactory $customerResourceFactory,
        \Magento\Customer\Model\CustomerFactory $customer
    ) { 
        $this->_customer = $customer;
        $this->customerResourceFactory = $customerResourceFactory;
        parent::__construct($context); 
    }

    public function execute()
    {       
        $userId = $this->getRequest()->getParam('user_id', false);
        $oldUser = $this->_getUser($userId);
        $oldUser->setEmail("email@domain.com"); //update attribute as per your need
        $oldUser->setFirstname("First Name");
        $oldUser->setLastname("Last name");

        $customerData = $oldUser->getDataModel();
        $customerData->setCustomAttribute('attribute_code', 'attribute_value');
        $oldUser->updateData($customerData);

        $customerResource = $this->customerResourceFactory->create();
        $customerResource->saveAttribute($oldUser, 'attribute_code');


        $oldUser->save();
    }

    private function _getUser($id)
    {
        //$customerObj = $this->_objectManager->create('Magento\Customer\Model\Customer')->load($id);
        $customerObj = $this->_customer->create();
        $customerObj->load($id);
        return $customerObj; 
     }
}
  • Used your code, error is removed but customer is not saving – jafar pinjar Aug 7 '18 at 16:06
  • @jafar updated code. You need to set data which is mandatory required for customer like email, firstname, lastname – Prashant Valanda Aug 7 '18 at 16:09
  • That will take from the old userId is it? we are taking from parameter – jafar pinjar Aug 7 '18 at 16:15
  • if there is already user available in database then what you want to do? – Prashant Valanda Aug 7 '18 at 16:17
  • I am doing update, with the parameter coming from browser – jafar pinjar Aug 7 '18 at 16:18
3

I think problem with your customer object

 $userId = $this->getRequest()->getParam('user_id', false);
 $oldUser = $this->_getUser($userId);

    $user = $this->customerFactory->create();
    if($userId):
      $user->load($userId)->setWebsiteId($oldUser->getWebsiteId());      
    endif; 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.