Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento - no event for newsletter subscribe & unsubscribe

Tags:

magento

Why are there no events dispatched on or around the newsletter subscription/un-subscription process either in the customer or newsletter modules.

The only alternative i am faced with at the moment is to use a rewrite for the subscriber model to fit some code in around here.

Does anyone else have a good alternative to this - or am I missing something

like image 425
David Avatar asked Apr 29 '11 17:04

David


1 Answers

I encountered a situation where I needed to listen for subscription/unsubscription events. I encountered this question and thought I would leave this solution here for anyone that may need it:

By adding an observer to the event newsletter_subscriber_save_before in your config.xml:

<global>
    ....
    <events>
        ....
        <newsletter_subscriber_save_before>
            <observers>
                <your_unique_event_name>
                    <class>yourgroupname/observer</class>
                    <method>newsletterSubscriberChange</method>
                </your_unique_event_name>
            </observers>
        </newsletter_subscriber_save_before>
    </events>
</global>

You can then call getSubscriber() (in the context of $observer->getEvent(), see next code block) in your observer to get the Mage_Newsletter_Model_Subscriber model that allows you get data about the subscriber. This works for occurrences of subscription and unsubscriptions.

public function newsletterSubscriberChange(Varien_Event_Observer $observer) {
    $subscriber = $observer->getEvent()->getSubscriber();
    //now do whatever you want to do with the $subscriber

    //for example
    if($subscriber->isSubscribed()) {
        //...
    }

    //or
    if($subscriber->getStatus() == Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED) {
        //...
    } elseif($subscriber->getStatus() == Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED) {
        //..
    }

}

So it turns out this is really easy. These model events are super powerful and let you do things like this super easily. Can't turn down free functionality!

For quick reference, here is what data the Mage_Newsletter_Model_Subscriber model provides (1.7)

like image 66
Josh Davenport-Smith Avatar answered Dec 03 '22 14:12

Josh Davenport-Smith