1

My custom module has certain categories that are linked to certain customers and should return that customer's company name instead of the category name, I have written a plugin like this:

public function afterGetName(Category $subject, $result) {
    $customerCollection = $this->customerCollectionFactory
        ->create()
        ->addFieldToFilter('custom_category_id', $subject->getId())
        ->setPageSize(1);

    if ($customerCollection->getSize()) {
        return $this->customerRepository->getById($customerCollection->getFirstItem()->getId())->getAddresses()[0]->getCompany();
    }

    return $result;
}

This works perfectly, but when I clear the cache the server starts using 100% memory and will slow to a crawl. I have narrowed it down to the $this->customerRepository->getById call, but I don't see how this seemingly results in an infinite recursion. I have tried using an AddressRepository instead, but that somehow breaks all $customer->getCustomAttribute calls.

  • Couldn't you just get the customer from the currently logged in session in that case? – Christoph Farnleitner Jan 13 '18 at 0:32
  • The customer that's linked to the category is usually different from the currently logged in customer – Kaascroissant Jan 13 '18 at 11:20
0

While I still don't understand how using customer or address repositories in a $category->getName plugin breaks your entire Magento installation, I managed to make it work by making a custom customer collection that also includes the default biling address' company, which allows me to simply call $customer->getCompany.

<?php

namespace {Namespace}\{Module}\Model\ResourceModel\Customer;

/**
 * Class Collection
 * @package {Namespace}\{Module}\Model\ResourceModel\Customer
 */
class Collection extends \Magento\Sales\Model\ResourceModel\Order\Customer\Collection {
    /**
     * @return $this
     */
    protected function _initSelect() {
        parent::_initSelect();
        $this->joinAttribute(
            'company',
            'customer_address/company',
            'default_billing',
            null,
            'left'
        );

        return $this;
    }
}

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.