2

I'm working on functionality that cares about the customer group. Currently we are loading the group code whenever we need it:

Mage::getModel('customer/group')->load(Mage::getSingleton('customer/session')->getcustomerGroupId())->getCustomerGroupCode();

What I'd like to do is just go ahead and have the customer model get this bit of data when the customer is being loaded. How can I accomplish this? Further, is it the most practical way to handle this?

1 Answer 1

2

This should be fairly simple. Create an observer on the customer_load_after event. As the method to run, use the following snippet of code (untested) to load the group code from the DB, and then to set it on the newly-loaded customer object.

public function customerLoadAfter($observer) 
{
    $customer = $observer->getCustomer();
    $resource = $customer->getResource();
    $select = $resource->getReadConnection()
        ->select()
        ->from($resource->getTable('customer/group'), ['customer_group_code'])
        ->where('entity_id = ?', $customer->getGroupId();

    $customer->setGroupCode($resource->fetchOne($select);
}

You can then retreive it with $customer->getGroupCode();.

This is probably the most practical way to do this. You could rewrite the customer resource model to join the data in when loading the model, and while it would be a tad bit more performant, it would definitely take a lot longer/be more complicated to write, and wouldn't be as clean as the event-based approach.

1
  • I was hoping it would be simply adding to the list of entities the customer model loads, but it makes sense that I'd have to rewrite the resource model and do a join. This is very clean, thanks!
    – callmetwan
    Sep 14, 2016 at 13:57

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.