Magento - 无法使用newsletter_subscriber_save_before事件的观察者保存更改后的客户GroupId

时间:2013-05-08 15:14:24

标签: magento events observers

我为newsletter_subscriber_save_before event;构建了一个观察者,当客户订阅/取消订阅时事通讯时,这会被解雇。 我需要相应地更改此客户组ID。看来我可以改变GroupId,但我无法保存它。如果我在我的代码中调用$customer->save() - 方法,我会遇到无限循环;如果我尝试挂钩newsletter_subscriber_save_after事件,也会发生同样的情况。

任何人都可以帮助我吗?非常感谢!

这是我在Observer.php中的代码:

public function newsletter_subscriber_change($observer) {
    try {

        // get status of subscriber
        $subscriber = $observer->getEvent()->getSubscriber();

        $status = $subscriber->getStatus();
        $email = $subscriber->getEmail();

        $customer = Mage::getSingleton('customer/customer');
        $customer->setWebsiteId(Mage::app()->getWebsite()->getId());

        $customer->loadByEmail($email);

    // here i change the groupId
        $customer->setData( 'group_id', 9 );
    // if i check the group here, the change applied ...
        $customer_group = $customer->getGroupId();

        // i tried saving with following, but run into loop
        $customer->save(); 

    } catch (Exception $e) {
        Mage::log("newsletter_subscriber_change observer failed: " . $e->getMessage());
    }
}

1 个答案:

答案 0 :(得分:0)

你有无限循环,因为Mage_Newsletter还捕获customer_save_after事件以保存订阅数据。 您可以通过原始查询更新组ID,如下所示:

public function newsletter_subscriber_change($observer) {
    try {

        // get status of subscriber
        $subscriber = $observer->getEvent()->getSubscriber();

        $status = $subscriber->getStatus();
        $email = $subscriber->getEmail();

        $customer = Mage::getSingleton('customer/customer');
        $customer->setWebsiteId(Mage::app()->getWebsite()->getId());

        $customer->loadByEmail($email);

        $adapter = Mage::getSingleton('core/resource');

        /* @var $conn Varien_Db_Adapter_Interface */
        $conn = $adapter->getConnection('core_write');

        $update = 'UPDATE ' . $customer->getResource()->getTable('customer/customer_enity')
                . ' SET group_id = ? WHERE entity_id = ?';

        $conn->query($update, array(9, $customer->getId()));

    } catch (Exception $e) {
        Mage::log("newsletter_subscriber_change observer failed: " . $e->getMessage());
    }
}