Magento – Magento 2: Set Customer Account Confirmation Status

confirmationcustomermagento-2.1magento2

Following Problem.

I get customers with an interface in to my Magento 2.1.

They are stored with a placeholder email. In my controller I update the mail address and want to set confirmation, so that the customer has to confirm his email on login.

$customer->setEmail($email);
$customer->setConfirmation(true);
//$customer->setConfirmation("Random-string"); //Did not work too
$this->_customerRepository->save($customer);

The email is updated but the confirmation flag is still NULL in the DB. How can I update it?

Best Answer

Your code looks good.

I'm pretty sure this is caused by some condition not being filled in the resource model.

As you can see from the following, there's a _beforeSave method in Magento\Customer\Model\ResourceModel\Customer that has some code that might rewrite the value of the confirmation data:

    // set confirmation key logic
    if ($customer->getForceConfirmed() || $customer->getPasswordHash() == '') {
        $customer->setConfirmation(null);
    } elseif (!$customer->getId() && $customer->isConfirmationRequired()) {
        $customer->setConfirmation($customer->getRandomConfirmationKey());
    }
    // remove customer confirmation key from database, if empty
    if (!$customer->getConfirmation()) {
        $customer->setConfirmation(null);
    }

I reckon you should try to debug that bit and see if the method does not go in the first condition (force confirmed or password hash empty).

Try to check the data of your custom before you call the save() method. Hopefully that'll help you narrow down the issue

Related Topic