向 Magento 的订阅模块添加自定义字段

发布于 2024-09-07 23:14:10 字数 102 浏览 9 评论 0原文

Magento 中的新闻通讯订阅模块默认只有一个字段(电子邮件)。在我向表单添加额外字段(例如国家/地区)后,如何让表单数据显示在 Magento 后端并作为电子邮件发送给预设收件人?谢谢。

The newsletter subscription module in Magento has only one field (email) by default. After I add an extra field to the form (say country), how can I get the form data to show up in the Magento back-end and be sent as an email to a preset recipient? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

我的痛♀有谁懂 2024-09-14 23:14:10

如果您想为 Magento 新闻通讯订阅者添加一些自定义字段(例如 subscriber_name),您应该执行以下操作:

  • newsletter_subscriber 表添加新列
  • 将文本输入添加到新闻通讯模板
  • newsletter_subscriber_save_before 事件创建观察者

在观察者中,您可以从请求中获取自定义字段的值并将其分配给订阅者的对象:

public function newsletterSubscriberSave(Varien_Event_Observer $observer)
{
    $subscriber = $observer->getEvent()->getSubscriber();
    $name = Mage::app()->getRequest()->getParam('subscriber_name');

    $subscriber->setSubscriberName($name);

    return $this;
}

更新

这是详细解释的文章如何添加国家/地区字段
另外,我创建了一个免费模块,可以在 GitHub 上找到

If you want to add some custom fields for Magento newsletter subscriber (for example subscriber_name), you should do the following:

  • Add new column for newsletter_subscriber table
  • Add text input to newsletter template
  • Create observer for newsletter_subscriber_save_before event

In the observer you can get your custom field's value from request and assign it to subscriber's object:

public function newsletterSubscriberSave(Varien_Event_Observer $observer)
{
    $subscriber = $observer->getEvent()->getSubscriber();
    $name = Mage::app()->getRequest()->getParam('subscriber_name');

    $subscriber->setSubscriberName($name);

    return $this;
}

UPDATE:

Here is the detailed article explaining how to add Country field
Also, I have created a free module, it is available on the GitHub

迷荒 2024-09-14 23:14:10

要完成这项工作,您需要注意以下几件事:

  1. 将数据的新列添加到相应的数据库表中
  2. 确保 Magento 将新字段保存到数据库
  3. 中 在管理后端中显示数据
  4. 记录数据当您订阅新的时事通讯时,

您可以执行以下操作:

广告。 1)

使用 phpMyAdmin、MySQL 命令行或任何您喜欢的数据库操作方法,向 newsletter_subscriber 表添加一个新列“country”,例如 varchar(100)。

广告。 2)

Magento 将自动让您通过 Mage_Newsletter_Model_Subscriber 对象上的 getCountry()setCountry() 方法访问新字段。它唯一不会做的就是在使用系统中某处的代码更改字段后将其保存回数据库。要保存它,您需要修改 Mage_Newsletter_Model_Mysql4_Subscriber (app/code/core/Mage/Newsletter/Model/Mysql4/Subscriber.php) 中找到的 _prepareSave(Mage_Newsletter_Model_Subscriber $subscriber) 函数。 请务必先制作该文件的本地副本,并且不要修改核心文件。以下是您需要添加的内容:

protected function _prepareSave(Mage_Newsletter_Model_Subscriber $subscriber)
{
    $data = array();
    $data['customer_id'] = $subscriber->getCustomerId();
    $data['store_id'] = $subscriber->getStoreId()?$subscriber->getStoreId():0;
    $data['subscriber_status'] = $subscriber->getStatus();
    $data['subscriber_email']  = $subscriber->getEmail();
    $data['subscriber_confirm_code'] = $subscriber->getCode();

    //ADD A NEW FIELD START

    //note that the string index for the $data array
    //must match the name of the column created in step 1
    $data['country'] = $subscriber->getCountry();

    //ADD A NEW FIELD END
    (...)
}

广告。 3)

您需要修改文件 app/code/core/Mage/Adminhtml/Block/Newsletter/Subscriber/Grid.php(本地副本)。您正在寻找的方法称为 _prepareColumns()。在那里你会看到一系列对 $this->addColumn() 的调用。您需要使用以下代码为“国家/地区”字段添加相应的调用:

$this->addColumn('country', array(
    'header'    => Mage::helper('newsletter')->__('Country'),
    //the index must match the name of the column created in step 1
    'index'     => 'country',
    'default'   =>    '----'
));

如果您希望该字段出现在网格的末尾(作为最后一列),请将其添加为最后一个调用,否则,将其挤压在现有的呼叫正是您希望它最终出现在管理员中的位置。

广告。 4)

这是我在定制 Magento 时事通讯时不需要做的部分,所以它主要是理论性的。订阅发生在位于 app/code/core/Mage/Newsletter/controllers/SubscriberController.php 的控制器中。以下是 newAction 方法的代码以及我建议的更改:

public function newAction()
{
    if ($this->getRequest()->isPost() && $this->getRequest()->getPost('email')) {
        $session   = Mage::getSingleton('core/session');
        $email     = (string) $this->getRequest()->getPost('email');

        try {
            if (!Zend_Validate::is($email, 'EmailAddress')) {
                Mage::throwException($this->__('Please enter a valid email address'));
            }

            $status = Mage::getModel('newsletter/subscriber')->subscribe($email);
            if ($status == Mage_Newsletter_Model_Subscriber::STATUS_NOT_ACTIVE) {
                $session->addSuccess($this->__('Confirmation request has been sent'));
            }
            else {
                $session->addSuccess($this->__('Thank you for your subscription'));
            }
                
                //ADD COUNTRY INFO START
                
                //at this point we may safly assume that subscription record was created
                //let's retrieve this record and add the additional data to it
                $subscriber = Mage::getModel('newsletter/subscriber')->loadByEmail($email);
                
                //assuming that the input's id is "country"
                $subscriber->setCountry((string) $this->getRequest()->getPost('country'));
                
                //don't forget to save the subscriber!
                $subscriber->save();
                
                //ADD COUNTRY INFO END
        }
        catch (Mage_Core_Exception $e) {
            $session->addException($e, $this->__('There was a problem with the subscription: %s', $e->getMessage()));
        }
        catch (Exception $e) {
            $session->addException($e, $this->__('There was a problem with the subscription'));
        }
    }
    $this->_redirectReferer();
}

通过上述步骤应该可以解决您的大部分问题。让我知道最后一部分的效果如何,因为我没有机会测试它。

一旦您在订阅者对象中添加了附加字段,您就可以用它做任何您想做的事情。我不太明白你的意思

作为电子邮件发送给预设收件人

如果您能解释一下,我也会尽力帮助您解决这部分问题。

编辑 - 当有人订阅时如何发送邮件

只需将以下代码添加到控制器中将国家/地区添加到订阅者对象的部分之后。

$mail = new Zend_Mail();
$mail->setBodyHtml("New subscriber: $email <br /><br />Country: ".$this->getRequest()->getPost('country'));
$mail->setFrom("[email protected]")
->addTo("[email protected]")
->setSubject("Your Subject here");
$mail->send(); 

There are a few things that you need to take care of to make this work:

  1. Add a new column for your data to the appropriate database table
  2. Make sure that Magento saves your new field to the database
  3. Present the data in the admin backend
  4. Record the data when you get a new newsletter subscription

Here's how you can do all those things:

Ad. 1)

Using phpMyAdmin, MySQL command line, or whatever is your preferred DB manipulation method, add a new column "country" as, say, varchar(100) to the newsletter_subscriber table.

Ad. 2)

Magento will automatically give you access to the new field through the getCountry() and setCountry() methods on the Mage_Newsletter_Model_Subscriber object. The only thing it won't do is save your field back to the DB after it has been changed with code somewhere in the system. To get it saved you need to modify _prepareSave(Mage_Newsletter_Model_Subscriber $subscriber) function found in Mage_Newsletter_Model_Mysql4_Subscriber (app/code/core/Mage/Newsletter/Model/Mysql4/Subscriber.php). Be sure to make a local copy of the file first and not modify the core file. Here's what you need to add:

protected function _prepareSave(Mage_Newsletter_Model_Subscriber $subscriber)
{
    $data = array();
    $data['customer_id'] = $subscriber->getCustomerId();
    $data['store_id'] = $subscriber->getStoreId()?$subscriber->getStoreId():0;
    $data['subscriber_status'] = $subscriber->getStatus();
    $data['subscriber_email']  = $subscriber->getEmail();
    $data['subscriber_confirm_code'] = $subscriber->getCode();

    //ADD A NEW FIELD START

    //note that the string index for the $data array
    //must match the name of the column created in step 1
    $data['country'] = $subscriber->getCountry();

    //ADD A NEW FIELD END
    (...)
}

Ad. 3)

You will need to modify (a local copy of) the file app/code/core/Mage/Adminhtml/Block/Newsletter/Subscriber/Grid.php. The method you are looking for is called _prepareColumns(). In there you will see a series of calls to $this->addColumn(). You need to add a corresponding call for your "Country" field with the following code:

$this->addColumn('country', array(
    'header'    => Mage::helper('newsletter')->__('Country'),
    //the index must match the name of the column created in step 1
    'index'     => 'country',
    'default'   =>    '----'
));

If you want the field to appear at the end of the grid (as the last column) add it as the last call, otherwise, squeeze it between the existing calls exactly where you want it to end up in the admin.

Ad. 4)

This is a part I did not have to do in my customization of the Magento newsletter, so it will be mostly theoretical. The subscription occurs in the controller located at app/code/core/Mage/Newsletter/controllers/SubscriberController.php. Here's the code of the newAction method with my proposed changes:

public function newAction()
{
    if ($this->getRequest()->isPost() && $this->getRequest()->getPost('email')) {
        $session   = Mage::getSingleton('core/session');
        $email     = (string) $this->getRequest()->getPost('email');

        try {
            if (!Zend_Validate::is($email, 'EmailAddress')) {
                Mage::throwException($this->__('Please enter a valid email address'));
            }

            $status = Mage::getModel('newsletter/subscriber')->subscribe($email);
            if ($status == Mage_Newsletter_Model_Subscriber::STATUS_NOT_ACTIVE) {
                $session->addSuccess($this->__('Confirmation request has been sent'));
            }
            else {
                $session->addSuccess($this->__('Thank you for your subscription'));
            }
                
                //ADD COUNTRY INFO START
                
                //at this point we may safly assume that subscription record was created
                //let's retrieve this record and add the additional data to it
                $subscriber = Mage::getModel('newsletter/subscriber')->loadByEmail($email);
                
                //assuming that the input's id is "country"
                $subscriber->setCountry((string) $this->getRequest()->getPost('country'));
                
                //don't forget to save the subscriber!
                $subscriber->save();
                
                //ADD COUNTRY INFO END
        }
        catch (Mage_Core_Exception $e) {
            $session->addException($e, $this->__('There was a problem with the subscription: %s', $e->getMessage()));
        }
        catch (Exception $e) {
            $session->addException($e, $this->__('There was a problem with the subscription'));
        }
    }
    $this->_redirectReferer();
}

Going through the above steps should take care of the most part of your problem. Let me know how that last part worked out, as I did not have a chance to test it.

Once you have your additional field in the Subscriber object you can do whatever you want with it. I did not really get what you mean by

be sent as an email to a preset recipient

If you can explain that I will try to help you out with this part too.

Edit - how to send a mail when someone subscribes

Just add the following code to the controller after the part which adds country to a subscriber object.

$mail = new Zend_Mail();
$mail->setBodyHtml("New subscriber: $email <br /><br />Country: ".$this->getRequest()->getPost('country'));
$mail->setFrom("[email protected]")
->addTo("[email protected]")
->setSubject("Your Subject here");
$mail->send(); 
兔姬 2024-09-14 23:14:10

除了已接受的答案之外,如果您要添加日期、日期时间或时间戳类型列,您还可以更轻松地解决此问题。

就我而言,我想将“订阅日期”添加到我的网格中。为此,我编写了升级脚本,列类型为 TIMESTAMP,默认值为 CURRENT_TIMESTAMP。这样,当添加行时,将记录当前日期/时间。

然后,您所要做的就是添加块自定义。我建议通过扩展 Magento 的网格块来实现这一点,而不是进行本地代码池覆盖。这样,你只需要重写 _prepareColumns();

Adding to the accepted answer, you can also get away with this a little easier if you're adding a date, datetime, or timestamp-type column.

In my case, I wanted to add a "Subscribed at Date" to my grid. To do this, I wrote my upgrade script, column type being TIMESTAMP and the default value being CURRENT_TIMESTAMP. This way, when the row is added, the current date/time is recorded.

Then, all you have to do is add your block customizations. I'd suggest doing it by extending Magento's grid block rather than doing the local codepool override though. This way, you only need to override _prepareColumns();

楠木可依 2024-09-14 23:14:10

旧线程,但如果有人有同样的问题,有一个免费扩展,它添加性别、名字和姓氏字段,并使其在后端网格中可通过 xml/csv 导出: http://www.magentocommerce.com/magento-connect/extended-newsletter-subscription-for-guests .html

也许您可以扩展代码以满足您的需要。

Old thread but if someone has the same question, there is a free extension, that adds fields for gender, firstname and lastname and makes it available in the backend grid for export via xml/csv: http://www.magentocommerce.com/magento-connect/extended-newsletter-subscription-for-guests.html

Perhaps you can extend the code to fit your needs.

撩起发的微风 2024-09-14 23:14:10

这是对安装了 Ebizmarts_MailChimp 扩展程序的任何人的警告。

这是一个很棒的扩展。但它将 subscriber_firstnamesubscriber_lastname 添加到 newsletter_subscriber 表中。

如果您打算创建这些字段,则应该“需要”Ebizmarts_MailChimp 扩展程序或检查在您的扩展创建字段之前,这些字段并不存在。

相反,您创建了它们并希望在创建后安装 Ebizmarts_MailChimp 扩展创建这些字段后,您必须在安装过程中注释掉这两个字段的 addColumn 代码。

This is a warning for anyone who's installed the Ebizmarts_MailChimp extension.

It's a great extension. But it adds subscriber_firstname and subscriber_lastname to the newsletter_subscriber table.

If you intend to create these fields, you should either "require" the Ebizmarts_MailChimp extension or check the fields don't exist before your extension creates them.

In the opposite, where you've created them and want to install the the Ebizmarts_MailChimp extension after you've created these fields, you will have to comment out the addColumn code for these two fields during installation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文