0

Everything is simple as an egg, but it does not work. Please help to figure out why. If you need more details - please let me know.

/**
 * @param int $customerId
 * @param int $addressId
 *
 * @return int
 */
public function setDefaultBillingAddress($customerId, $addressId)
{
    $customer = $this->customerRepository->getById($customerId);
    $customer->setDefaultBilling($addressId);
    $this->customerRepository->save($customer);
}

Customer is loading well, address with such ID exists. When I dived into customerRepository->save($customer) from the beginning everything is also well, but at some moment (probably when it saves customer to registry and tries to load it again - my new value is lost)

Upd.1 Is it core issue?

Magento\Customer\Model\ResourceModel\CustomerRepository (row. 236)

Magento removes customer from registry for some reason, then tries to load it from registry. It doesn't exist there and load from DB. Is it ok? Customer wasn't saved because it happen between beginTransaction() and commit()

Upd.2

It refers only to this particular attribute default_billing, saving customer firstname work well

Upd.3

The issue is near backend model of default_billing attribute. It has following code:

/**
 * @param \Magento\Framework\DataObject $object
 * @return void
 */
public function afterSave($object)
{
    if ($defaultBilling = $object->getDefaultBilling()) {
        $addressId = false;
        /**
         * post_index set in customer save action for address
         * this is $_POST array index for address
         */
        foreach ($object->getAddresses() as $address) {
            if ($address->getPostIndex() == $defaultBilling) {
                $addressId = $address->getId();
            }
        }
        if ($addressId) {
            $object->setDefaultBilling($addressId);
            $this->getAttribute()->getEntity()->saveAttribute($object, $this->getAttribute()->getAttributeCode());
        }
    }
}

It looks for some post_index flag, which doesn't exist anywhere. Searching for post_index or postIndex don't give more results, than those from backend models (billing, shipping)

0

Doesn't work described approach. Use following code:

/**
 * @param int $addressId
 *
 * @return int
 */
public function setDefaultBillingAddress($addressId)
{
    $address = $this->addressRepository->getById($addressId);
    $address->setIsDefaultBilling(1);
    $this->addressRepository->save($address);
}
| improve this answer | |

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.