1

I am working on a custom magento admin module with grids. When you add a new entry, I perform custom validation and throw an error (when & if it occurs) using Mage::getSingleton('adminhtml/session')->addError() method.

The error message I set does not appear, when I redirect back to the edit form.

This is my save action on the grid controller:

public function saveAction()
{
    // Look For HTTP Post
    if ($data = $this->getRequest()->getPost())
    {
        // Load Data
        $manualOrderSyncModel = Mage::getModel('mycompany_mymodule/manualordersync')
            ->setData($data)
            ->setId($this->getRequest()->getParam('id'));

        // Anticipate Errors
        try
        {
            // Get If Order Number Is Valid
            $order = Mage::getModel('sales/order')->load($manualOrderSyncModel->getOrderNumber(), 'increment_id');
            if (null === $order->getId())
                throw new Exception('No such order exists in the system. Check that order number.');

            // Check If This Order Already Exists In Queue
            $existingManualOrderSyncModel = Mage::getModel('mycompany_mymodule/manualordersync')
                ->load($manualOrderSyncModel->getOrderNumber(), 'order_number');
            if (null !== $existingManualOrderSyncModel->getId())
            {
                // Update Existing Entry
                $existingManualOrderSyncModel
                    ->setCreatedAt(now())
                    ->setCreatedBy(Mage::getSingleton('admin/session')->getUser()->getUsername())
                    ->setIsSynced(Mycompany_Mymodule_Model_Yesno::NO)
                    ->save();
            }
            else
            {
                // Update Timestamps
                if ($manualOrderSyncModel->getCreatedAt() == NULL) {
                    $manualOrderSyncModel
                        ->setCreatedAt(now())
                        ->setCreatedBy(Mage::getSingleton('admin/session')->getUser()->getUsername());
                }
                $manualOrderSyncModel->save();
            }

            // Set Success
            Mage::getSingleton('adminhtml/session')->addSuccess($this->__('Manual order sync updated.'));
            Mage::getSingleton('adminhtml/session')->setManualordersyncData(false);

            // Handle Redirect
            $this->_redirect('*/*/');
            return;
        }
        catch (Exception $e)
        {
            // Error
            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            Mage::getSingleton('adminhtml/session')->setManualordersyncData($data);
            $this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
            return;
        }
    }

    // Error
    Mage::getSingleton('adminhtml/session')->addError($this->__('Invalid request - unable to find manual order sync to save.'));
    $this->_redirect('*/*/');
}

I have noticed, the issue only occurs when I do this:

// Error
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setManualordersyncData($data);
$this->_redirect('*/*/edit', array('id' => $this->getRequest()->getParam('id')));
return;

However, If set error and redirect back to grid like this, the error message shows:

// Error
Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
Mage::getSingleton('adminhtml/session')->setManualordersyncData($data);
$this->_redirect('*/*/');
return;

This is not ideal because I am no longer in the edit form and I have lost the old data from the form.

3
  • It sounds like the error message container is not on the form, but by obviously is on the grid. You can prove this by adding something like B error or success on the editAction when the form loads up. If it fails to do so try adding the messages to your form template. Jan 6, 2016 at 1:36
  • @RussellAlbin I am using this method: markshust.com/2012/07/05/… (there are no html involved).
    – Latheesan
    Jan 6, 2016 at 11:08
  • You guide is a bit old but it should still work. I am not sure why its broken. I thought adding my example may be helpful but it may be too complicated for your question. If you need this sample code, or something similar to use a model, I can provide it. I tried to include it here, but it was very very long, sorry for making it more complicated that it needed to be. Hopefully you can use some of my code to fix your issue. Jan 6, 2016 at 16:20

6 Answers 6

0

Here is an example of how I use admin sessions on my forms. I use a protected function to get the adminhtml session

/**
 * Retrieve adminhtml session model object
 *
 * @return Mage_Adminhtml_Model_Session
 */
protected function _getSession()
{
    return Mage::getSingleton('adminhtml/session');
}

Then, when I need it, for error messages I call it this way, from inside a controller

    $order          = $this->_getOrder();
    if(!(int)$order->getId())
    {
        $this->_getSession()->addError('Unable to load test order');
        $this->_redirect('*/*/index');
        return false;
    }

That should produce a message like this on the redirect enter image description here

Here is my process on creating forms in Magento for the admin. this example is to send emails from our site to test them rather than having to do the action like place an order, or add a comment to a shipment for example.

Step 1, create the module declaration in app/etc/modules This should be named something like Russell_Emaillog.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Russell_Emaillog>
            <active>true</active>
            <codePool>local</codePool>                
        </Russell_Emaillog>
    </modules>
</config>

Step 2: Create the Namespace folder to contain our code in app/code/local

Russell so it should look like app/code/local/Russell

Step 3: create all the folders needed for this module in app/code/local/Russell

Emaillog Then inside Emaillog create several folders here is the structure

app/code/local/Russell/Emaillog/Block
app/code/local/Russell/Emaillog/Block/Adminhtml
app/code/local/Russell/Emaillog/Block/Adminhtml/Abstract
app/code/local/Russell/Emaillog/Block/Adminhtml/Entry
app/code/local/Russell/Emaillog/Block/Adminhtml/Entry/Edit
app/code/local/Russell/Emaillog/Block/Adminhtml/Entry/Edit/Tab
app/code/local/Russell/Emaillog/Controller
app/code/local/Russell/Emaillog/Controller/Entry
app/code/local/Russell/Emaillog/controllers
app/code/local/Russell/Emaillog/controllers/Adminhtml
app/code/local/Russell/Emaillog/controllers/Adminhtml/Emaillog
app/code/local/Russell/Emaillog/etc
app/code/local/Russell/Emaillog/Helper
app/code/local/Russell/Emaillog/Model
app/code/local/Russell/Emaillog/Model/Email
app/code/local/Russell/Emaillog/Model/Resource
app/code/local/Russell/Emaillog/Model/Entry
app/code/local/Russell/Emaillog/sql
*** These next two are in app/design/adminhtml/default/default/ ***
app/design/adminhtml/default/default/template/russell/
app/design/adminhtml/default/default/layout/russell/

Step 4: Now that you have all the folders in place you need to put the PHP files in each, I will just put the names of the files for this step so you can create empty php and xml files for now

app/code/local/Russell/Emaillog/Block/Adminhtml/Abstract/Entry/Edit/Tab/General.php
app/code/local/Russell/Emaillog/Block/Adminhtml/Abstract/Entry/Edit/Form.php
app/code/local/Russell/Emaillog/Block/Adminhtml/Abstract/Entry/Edit/Tabs.php
app/code/local/Russell/Emaillog/Block/Adminhtml/Abstract/Entry/Edit.php
app/code/local/Russell/Emaillog/Block/Adminhtml/Abstract/Entry/Grid.php
app/code/local/Russell/Emaillog/Block/Adminhtml/Abstract/Entry.php
app/code/local/Russell/Emaillog/Block/Emailtemplate.php
app/code/local/Russell/Emaillog/Controller/Entry/Abstract.php
app/code/local/Russell/Emaillog/controllers/Adminhtml/Emaillog/EntryController.php
app/code/local/Russell/Emaillog/controllers/Adminhtml/Emaillog/TestemailController.php
app/code/local/Russell/Emaillog/etc/adminhtml.xml
app/code/local/Russell/Emaillog/etc/config.xml
app/code/local/Russell/Emaillog/etc/system.xml
app/code/local/Russell/Emaillog/Helper/Data.php
app/code/local/Russell/Emaillog/Model/Email/Template.php
app/code/local/Russell/Emaillog/Model/Resource/Entry/Collection.php
app/code/local/Russell/Emaillog/Model/Resource/Entry.php
app/code/local/Russell/Emaillog/Model/Entry.php
app/code/local/Russell/Emaillog/sql/russell_emaillog_setup/install-0.0.1.php
app/design/adminhtml/default/default/template/russell/emaillog/view.phtml
app/design/adminhtml/default/default/layout/russell/emaillog.xml

My response was too large to have this all in one Answer, this is part 1

0

Step 5: Content for all our php and xml pages app/code/local/Russell/Emaillog/Block/Adminhtml/Abstract/Entry/Edit/Tab /General.php

/**
 * Class Russell_Emaillog_Block_Adminhtml_Abstract_Entry_Edit_Tab_General
 */
abstract class Russell_Emaillog_Block_Adminhtml_Abstract_Entry_Edit_Tab_General
    extends Mage_Adminhtml_Block_Widget_Form
{
    /**
     *
     */
    public function __construct() {
        parent::__construct();
        // This will load a new view that has the email with formatting as it was delivered
        // Otherwise you have the standard view of an admin form with form elements
        $this->setTemplate('russell/emaillog/view.phtml');
    }

    /**
     * @return array
     */
    protected function _getFormData()
    {
        $data = Mage::getSingleton('adminhtml/session')->getFormData();

        if (! $data && Mage::registry('current_entry')->getData()) {
            $data = Mage::registry('current_entry')->getData();
        }

        return (array) $data;
    }

    /**
     * @return mixed
     */
    public function getEntry()
    {
        return Mage::registry('current_entry')->getData();
    }

    /**
     * @return mixed
     */
    public function getTemplates()
    {
        return Mage::getModel('core/email_template')->getDefaultTemplates();
    }

}

app/code/local/Russell/Emaillog/Block/Adminhtml/Abstract/Entry/Edit/Form.php

/**
 * Class Russell_Emaillog_Block_Adminhtml_Abstract_Entry_Edit_Form
 */
abstract class Russell_Emaillog_Block_Adminhtml_Abstract_Entry_Edit_Form
    extends Mage_Adminhtml_Block_Widget_Form
{
    /**
     * Prepare the inner form wrapper
     */
    protected function _prepareForm()
    {
        $form = new Varien_Data_Form(array(
            'id' => 'edit_form',
            'action' => $this->getUrl('*/*/save',
                array('id' => $this->getRequest()->getParam('id'))),
            'method' => 'post',
            'enctype' => 'multipart/form-data',
        ));
        $form->setUseContainer(true); // <- Render the <form> tag

        $this->setForm($form);

        return parent::_prepareForm();
    }
}

app/code/local/Russell/Emaillog/Block/Adminhtml/Abstract/Entry/Edit/Tabs.php

/** * Class Russell_Emaillog_Block_Adminhtml_Abstract_Entry_Edit_Tabs */ abstract class Russell_Emaillog_Block_Adminhtml_Abstract_Entry_Edit_Tabs extends Mage_Adminhtml_Block_Widget_Tabs { protected $_generalTabClass;

    /**
     *
     */
    protected function _construct()
    {
        parent::_construct();
        $this->setId('switch_tabs');
        $this->setDestElementId('edit_form');
        $this->setTitle($this->__('Entry'));
    }

    /**
     * Add tabs content
     *
     * @return Russell_Emaillog_Block_Adminhtml_Entry_Edit_Tabs
     */
    protected function _beforeToHtml()
    {
        $this->addTab('general_section', array(
            'label'   => $this->__('Review'),
            'title'   => $this->__('Review'),
            'content' => $this->getLayout()
                ->createBlock($this->_generalTabClass)
                ->toHtml(),
        ));

        return parent::_beforeToHtml();
    }
}

app/code/local/Russell/Emaillog/Block/Adminhtml/Abstract/Entry/Edit.php

/**
 * Class Russell_Emaillog_Block_Adminhtml_Abstract_Entry_Edit
 */
abstract class Russell_Emaillog_Block_Adminhtml_Abstract_Entry_Edit
    extends Mage_Adminhtml_Block_Widget_Form_Container
{
    protected $_objectId = 'id';
    protected $_blockGroup = 'russell_emaillog';
    protected $_mode = 'edit';

    abstract protected function _getEntryType();

    /**
     * @return Mage_Core_Block_Abstract
     */
    protected function  _prepareLayout()
    {
        $this->_removeButton('save');
        $this->_removeButton('reset');
        $this->_updateButton('delete', 'label', $this->__('Delete Email Log Entry'));
        return parent::_prepareLayout();
    }

    /**
     * Return the title string to show above the form
     *
     * @return string
     */
    public function getHeaderText()
    {
        $model = Mage::registry('current_entry');
        if ($model && $model->getId()) {
            return $this->__('Review %s Email Log Entry # %s',
                $this->_getEntryType(),
                $this->escapeHtml($model->getId())
            );
        } else {
            return $this->__('New %s Entry', $this->_getEntryType());
        }
    }
}

app/code/local/Russell/Emaillog/Block/Adminhtml/Abstract/Entry/Grid.php

/**
 * Class Russell_Emaillog_Block_Adminhtml_Abstract_Entry_Grid
 */
abstract class Russell_Emaillog_Block_Adminhtml_Abstract_Entry_Grid
    extends Mage_Adminhtml_Block_Widget_Grid
{
    /**
     * Initialize grid settings
     */
    protected function _construct()
    {
        parent::_construct();

        $this->setId('russell_emaillog_list');
        $this->setDefaultSort('entity_id');
        $this->setDefaultDir('DESC');

        /*
         * Override method getGridUrl() in this class to provide URL for ajax
         */
        $this->setUseAjax(true);
    }

    /**
     * Return Grid URL for AJAX query
     *
     * @return string
     */
    public function getGridUrl()
    {
        return $this->getUrl('*/*/grid', array('_current' => true));
    }

    /**
     * Return URL where to send the user when he clicks on a row
     *
     * @return string
     */
    public function getRowUrl($row)
    {
        return $this->getUrl('*/*/edit', array('id' => $row->getId()));
    }

    /**
     * Prepare grid columns
     *
     * @return Russell_Emaillog_Block_Adminhtml_Abstract_Entry_Grid
     */
    protected function _prepareColumns()
    {
        $this->addColumn('entity_id', array(
            'header' => $this->__('ID'),
            'sortable' => true,
            'width' => '60px',
            'index' => 'entity_id'
        ));

        $this->addColumn('recipient_email', array(
            'header' => $this->__('Recipient Email'),
            'index' => 'recipient_email',
        ));

        $this->addColumn('recipient_name', array(
            'header' => $this->__('Recipient Name'),
            'index' => 'recipient_name',
        ));
        $this->addColumn('email_subject', array(
            'header' => $this->__('Email Subject'),
            'index' => 'email_subject',
        ));

        $this->addColumn('template_id', array(
            'header' => $this->__('Email Template'),
            'index' => 'template_id',
        ));

        /*
                $this->addColumn('admin', array(
                    'header' => $this->__('Admin'),
                    'sortable' => false,
                    'getter' => array($this, 'getCustomerNameCallback'),
                    'filter_condition_callback' => array($this, 'filterConditionCallback')
                ));
        */
        $this->addColumn('created_at', array(
            'header' => $this->__('Created At'),
            'index' => 'created_at',
            'type' => 'datetime'
        ));

        $this->addColumn('action', array(
            'header' => $this->__('Action'),
            'width' => '100px',
            'type' => 'action',
            'getter' => 'getId',
            'actions' => array(
                array(
                    'caption' => $this->__('Review'),
                    'url' => array('base' => '*/*/edit'),
                    'field' => 'id',
                ),
                array(
                    'caption' => $this->__('Delete'),
                    'url' => array('base' => '*/*/delete'),
                    'field' => 'id',
                ),
            ),
            'filter' => false,
            'sortable' => false,
        ));

        return parent::_prepareColumns();
    }

    public function getCustomerNameCallback(Varien_Object $entry)
    {
        $name = '';
        if ($entry->getCustomerId()) {
            $name = $entry->getCustomerFirstname() . ' ' . $entry->getCustomerLastname();
        }
        return $name;
    }

    abstract public function filterConditionCallback(Varien_Data_Collection_Db $collection, Mage_Adminhtml_Block_Widget_Grid_Column $column);
}

app/code/local/Russell/Emaillog/Block/Adminhtml/Abstract/Entry.php

/**
 * Class Russell_Emaillog_Block_Adminhtml_Abstract_Entry
 */
abstract class Russell_Emaillog_Block_Adminhtml_Abstract_Entry
    extends Mage_Adminhtml_Block_Widget_Grid_Container
{
    protected $_blockGroup = 'russell_emaillog';

    /**
     *
     */
    protected function _construct()
    {
        parent::_construct();

    }

}

app/code/local/Russell/Emaillog/Block/Emailtemplate.php

/**
 * Class Russell_Emaillog_Block_Emailtemplate
 */
class Russell_Emaillog_Block_Emailtemplate extends Mage_Core_Block_Template {

    /**
     * @return mixed
     */
    public function getEmailTemplates()
    {
        return Mage::getModel('russell_emaillog/email_template')->getEmailTemplates();
    }
}

app/code/local/Russell/Emaillog/Controller/Entry/Abstract.php

/**
 * Class Russell_Emaillog_Controller_Entry_Abstract
 */
abstract class Russell_Emaillog_Controller_Entry_Abstract extends Mage_Adminhtml_Controller_Action
{
    abstract protected function getEntityModelClass();

    /*
     *  @TODO Using         $config = Mage::getConfig()->loadModulesConfiguration('config.xml')->getNode('global/models/core/rewrite/email_template');
        Make sure that another extension is not already rewriting email_template
     */
    /**
     * @return mixed
     */
    protected function _isAllowed()
    {
        return Mage::getSingleton('admin/session')
            ->isAllowed('emaillog/russell_entry');
    }

    /**
     *
     */
    public function indexAction()
    {
        /*
        * Redirect user via 302 http redirect (the browser url changes)
        */
        $this->_redirect('*/*/list');
    }

    /**
     *
     */
    public function errorAction()
    {
        $this->_getSession()->setFormData(array());

        $this->_title($this->__('Catalog'))->_title($this->__('Entries'));

        $this->loadLayout();

        $this->_setActiveMenu('russell_emaillog');

        $this->renderLayout();

    }

    /**
     * Display grid
     */
    public function listAction()
    {
        $this->_getSession()->setFormData(array());

        $this->_title($this->__('Catalog'))->_title($this->__('Entries'));

        $this->loadLayout();

        $this->_setActiveMenu('russell_emaillog');

        $this->renderLayout();
    }

    /**
     * Grid action for ajax requests
     */
    public function gridAction()
    {
        $this->loadLayout(false);
        $this->renderLayout();
    }


    /**
     * Create or edit entry
     */
    public function editAction()
    {
        $model = Mage::getModel($this->getEntityModelClass());
        Mage::register('current_entry', $model);
        $id = $this->getRequest()->getParam('id');

        try
        {
            if ($id) {
                if (!$model->load($id)->getId()) {
                    Mage::throwException($this->__('No record with ID "%s" found.', $id));
                }
            }

            /*
             * Build the emaillog_type title
             */
            if ($model->getId()) {
                $blog_typeTitle = $this->__('Review Entry %d', $model->getId());
            }
            else
            {
                $blog_typeTitle = $this->__('New Entry');
            }
            $this->_title($this->__('Email Log'))->_title($this->__('Entries'))->_title($blog_typeTitle);

            $this->loadLayout();

            $this->_setActiveMenu('russell_emaillogg/russell_entry');

            $this->renderLayout();
        }
        catch (Exception $e)
        {
            Mage::logException($e);
            $this->_getSession()->addError($e->getMessage());
            $this->_redirect('*/*/list');
        }
    }


    /*
     *  function massDeleteAction
     *  Used to delete many at one time
     */
    public function massDeleteAction()
    {
        $ids = $this->getRequest()->getParam('ids');
        if(!is_array($ids)) {
            Mage::getSingleton('adminhtml/session')->addError(Mage::helper('adminhtml')->__('Please select Log(s).'));
        } else {
            try {
                $model = Mage::getModel($this->getEntityModelClass());
                foreach ($ids as $_id) {
                    $model->load($_id)
                        ->delete();
                }
                Mage::getSingleton('adminhtml/session')->addSuccess(
                    Mage::helper('adminhtml')->__('Total of %d record(s) were deleted.', count($ids))
                );
            } catch (Exception $e) {
                Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            }
        }

        $this->_redirect('*/*/index');

    }

    /**
     * Delete entry entity
     */
    public function deleteAction()
    {
        $model = Mage::getModel($this->getEntityModelClass());
        $id = $this->getRequest()->getParam('id');

        try
        {
            if ($id) {
                if (!$model->load($id)->getId()) {
                    Mage::throwException($this->__('No record with ID "%s" found.', $id));
                }
                $model->delete();
                $this->_getSession()->addSuccess($this->__('Entry (ID %d) was successfully deleted', $id));
            }
        }
        catch (Exception $e)
        {
            Mage::logException($e);
            $this->_getSession()->addError($e->getMessage());
        }

        $this->_redirect('*/*');
    }

}

app/code/local/Russell/Emaillog/controllers/Adminhtml/Emaillog/EntryController.php

/**
 * Class Russell_Emaillog_Adminhtml_Emaillog_EntryController
 */
class Russell_Emaillog_Adminhtml_Emaillog_EntryController
    extends Russell_Emaillog_Controller_Entry_Abstract
{
    /**
     * @return string
     */
    protected function getEntityModelClass()
    {
        return 'russell_emaillog/entry';
    }
}

End of part 2

0

app/code/local/Russell/Emaillog/controllers/Adminhtml/Emaillog/TestemailController.php

/**
 * Class Russell_Emaillog_Adminhtml_Emaillog_TestemailController
 */
class Russell_Emaillog_Adminhtml_Emaillog_TestemailController
    extends Mage_Adminhtml_Controller_Action
{

    private $_errors            = false;
    private $_testStoreId       = 3;
    private $_analyticsStoreId  = 4;
    private $_incrementId       = 200000911;
    private $_languageCode      = 'en-US';
    private $_recipient_email   = '[email protected]';
    private $_emailTemplates    = array();
    private $_orders            = array();

    const ENTITY                        = 'order';
    const EMAIL_EVENT_NAME_NEW_ORDER    = 'new_order';
    const EMAIL_EVENT_NAME_UPDATE_ORDER = 'update_order';

    /**
     * @return mixed
     */
    protected function _isAllowed()
    {
        return Mage::getSingleton('admin/session')
            ->isAllowed('emaillog/emaillog_testemail');
    }

    /**
     *
     */
    protected function _construct()
    {
        $this->_emailTemplates  = Mage::getModel('russell_emaillog/email_template')->getEmailTemplates();
        $this->_orders          = Mage::getModel('sales/order')->getCollection()
            ->addFieldToFilter('increment_id', array('in'=> array('200000039', '200000040', '200000041', '200000042', '200000043', '200000044', '400000007')))->setPageSize(30)->setCurPage(1);
        parent::_construct();

    }

    /**
     *
     */
    public function indexAction()
    {
        $this->loadLayout();

        $this->renderLayout();
    }

    /**
     * @return $this|Mage_Core_Controller_Varien_Action
     */
    public function testemailPostAction()
    {
        // Validate the form key to prevent someone posting to our controller without being on our site
        if (!$this->_validateFormKey()) {
            $this->_getSession()->addError('Problem with form, please try again');
            return $this->_redirect('*/*');
        }
        $recipient_email = Mage::app()->getRequest()->getParam('recipient_email');

        // check for a recipient email
        if ($recipient_email)
        {
            $email_templates = Mage::app()->getRequest()->getParam('email_templates');
            $this->_emailTemplates = $email_templates;
            if(!count($this->_emailTemplates))
            {
                $templates = array();
                foreach(Mage::getModel('russell_emaillog/email_template')->getEmailTemplates() as $_templateId => $_template)
                {
                    $templates[] = $_templateId;
                }
                // This should not ever happen, but in case we want to make sure at least 1 template was selected
                $this->_emailTemplates = $templates;
            }
            // reset our variable to have the email we have from the form
            $this->_recipient_email = $recipient_email;
            // Validate the email is a good format
            if (!Zend_Validate::is($this->_recipient_email, 'EmailAddress'))
            {
                // Its not a good email address add the error and redirect back
                $this->_getSession()->addError($this->__('Invalid email address ('.$this->_recipient_email.').'));
            }
            else
            {
                // Lets go ahead and start the process of sending the emails
                if($this->_sendTestEmails())
                {
                    // If all is good add the success message
                    $this->_getSession()->addSuccess('Emails sent');
                }
                else
                {
                    // Darn it, there was an issue, show a message to the user
                    $this->_getSession()->addError($this->__('Something went wrong when trying to send the emails, please try again.'));
                }
            }
        }

        // Do we have a custom redirect?
        if(Mage::app()->getRequest()->getParam('redirect_to'))
        {
            $this->_redirect(Mage::app()->getRequest()->getParam('redirect_to'));
        }
        else
        {
            // No custom redirect take them to the same module/controller/indexAction
            $this->_redirect('*/*/index');
        }
    }

    /**
     * @return bool
     */
    private function _sendTestEmails()
    {
        $errors = array();
        // go through all our templates and try to send that email
        foreach($this->_emailTemplates as $_templateId)
        {
            // Needed to get the exact template used
            //$_template        = Mage::getStoreConfig($_templateId, $this->_testStoreId);
            // Get the params needed for this email
            if(!$this->_sendEmail( $_templateId ))
            {
                $errors[] = true;
            }
        }
        // The $errors array should be empty unless an email failed to send.
        if(count($errors))
        {
            // Darn it we had some errors, return false so we ca present a message to the user
            return false;
        }else{
            // hooray! no issues, return true!
            return true;
        }
    }

    /**
     * @param $template_id
     * @return bool|void
     * @throws Exception
     */
    private function _sendEmail( $template_id )
    {
        switch( $template_id )
        {
            case 'sales_email/order/template':
                return $this->_sendNewOrderEmail( $template_id );
                break;              
            case 'russell_invoice_new/template':
                return $this->_sendRussellInvoiceNewEmail( $template_id );
                break;
            case 'sales_email/creditmemo/template':
                return $this->_sendCreditMemoNewEmail( $template_id );
                break;
            case 'sales_email/creditmemo_comment/template':
                return $this->_sendCreditMemoUpdateEmail( $template_id );
                break;
            case 'sales_email/shipment/template':
                return $this->_sendShipmentNewEmail( $template_id );
                break;
            case 'sales_email/shipment_comment/template':
                return $this->_sendShipmentCommentEmail( $template_id );
                break;
            case 'customer/create_account/email_template':
                return $this->_sendAccountNewEmail( $template_id );
                break;
            case 'customer/password/forgot_email_template':
                return $this->_sendForgotPasswordEmail( $template_id );
                break;
            case 'customer/password/remind_email_template':
                return $this->_sendNewPasswordEmail( $template_id );
                break;
            default:
                return false;
                break;
        }
    }

    /**
     * @param $template_id
     * @return bool
     */
    private function _sendForgotPasswordEmail( $template_id )
    {
        $customer       = $this->_getCustomer();
        $template       = $this->_getTemplate($template_id, $this->_testStoreId);
        $params         = array(
            'customer'          => $customer,
            'subject'           => 'TEST Forgot Password Email',
        );
        try{
            $this->_sendTestEmail($this->_testStoreId, $template, $params);
            return true;
        }catch ( Exception $e ){
            return false;
        }

    }

    /**
     * @param $template_id
     * @return bool
     */
    private function _sendNewPasswordEmail( $template_id )
    {
        $customer       = $this->_getCustomer();
        $template       = $this->_getTemplate($template_id, $this->_testStoreId);
        $params         = array(
            'customer'          => $customer,
            'subject'           => 'TEST New Password Email',
        );
        try{
            $this->_sendTestEmail($this->_testStoreId, $template, $params);
            return true;
        }catch ( Exception $e ){
            return false;
        }

    }
    /**
     * @param $template_id
     * @return bool
     */
    private function _sendAccountNewEmail( $template_id )
    {
        $customer       = $this->_getCustomer();
        $template       = $this->_getTemplate($template_id, $this->_testStoreId);
        $params         = array(
            'customer'          => $customer,
            'subject'           => 'TEST New Customer Email',
        );
        try{
            $this->_sendTestEmail($this->_testStoreId, $template, $params);
            return true;
        }catch ( Exception $e ){
            return false;
        }
    }
    /**
     * @param $template_id
     * @return bool
     * @throws Exception
     */
    private function _sendShipmentCommentEmail( $template_id )
    {

        $shipment               = $this->_getShipment();
        $order_id               = $shipment->getData('increment_id');
        $order                  = $this->_getOrder($order_id);
        $storeId                = $order->getData('store_id');
        if(!$storeId)
        {
            $storeId = $this->_testStoreId;
        }
        $emailSubject           = 'TEST Shipment Update # ' . $order_id;
        $template               = $this->_getTemplate($template_id, $storeId);
        $languageCode           = $this->_languageCode;
        $appEmulation           = Mage::getSingleton('core/app_emulation');
        $initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($storeId);

        try {
            // Retrieve specified view block from appropriate design package (depends on emulated store)
            $paymentBlock = Mage::helper('payment')->getInfoBlock($order->getPayment())
                ->setIsSecureMode(true);
            $paymentBlock->getMethod()->setStore($storeId);
            $paymentBlockHtml = $paymentBlock->toHtml();
        } catch (Exception $exception) {
            // Stop store emulation process
            $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);
            throw $exception;
        }
        // Stop store emulation process
        $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);

        // Setup the parameters
        $params             = array(
            'order'         => $order,
            'comment'       => 'TEST shipment update and comments',
            'order_id'      => $order->getId(),
            'subject'       => $emailSubject
        );

        try{
            // Send our test email
            $this->_sendTestEmail($storeId, $template, $params);
            return true;
        }catch (Exception $e){
            return false;
        }
    }
    /**
     * @param $template_id
     * @return bool
     * @throws Exception
     */
    private function _sendShipmentNewEmail( $template_id )
    {

        $shipment               = $this->_getShipment();
        $order_id               = $shipment->getData('increment_id');
        $order                  = $this->_getOrder($order_id);

        $storeId                = $order->getData('store_id');
        if(!$storeId)
        {
            $storeId = $this->_testStoreId;
        }
        $emailSubject           = 'TEST Shipment New # ' . $order_id;
        $template               = $this->_getTemplate($template_id, $storeId);
        $languageCode           = $this->_languageCode;

        // Setup the parameters
        $params             = array(
            'shipment'      => $shipment,
            'order'         => $order,
            'payment_html'  => $this->_getPaymentHtml($storeId, $order),
            'order_id'      => $order->getId(),
            'subject'       => $emailSubject
        );

        try{
            // Send our test email
            $this->_sendTestEmail($storeId, $template, $params);
            return true;
        }catch (Exception $e){
            return false;
        }
    }

    /**
     * @param $template_id
     * @return bool
     * @throws Exception
     */
    private function _sendCreditMemoUpdateEmail( $template_id )
    {

        $creditmemo             = $this->_getCreditMemo();
        $order                  = $this->_getOrder($creditmemo->getData('increment_id'));

        $storeId                = $order->getData('store_id');
        $emailSubject           = 'TEST Credit Memo Update # ';
        $template               = $this->_getTemplate($template_id, $storeId);
        $languageCode           = $this->_languageCode;
        $appEmulation           = Mage::getSingleton('core/app_emulation');
        $initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($storeId);

        try {
            // Retrieve specified view block from appropriate design package (depends on emulated store)
            $paymentBlock = Mage::helper('payment')->getInfoBlock($order->getPayment())
                ->setIsSecureMode(true);
            $paymentBlock->getMethod()->setStore($storeId);
            $paymentBlockHtml = $paymentBlock->toHtml();
        } catch (Exception $exception) {
            // Stop store emulation process
            $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);
            throw $exception;
        }
        // Stop store emulation process
        $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);

        // Setup the parameters
        $params             = array(
            'order'         => $order,
            'order_id'      => $order->getId(),
            'comment'       => 'Test Update and comment',
            'subject'       => $emailSubject
        );

        try{
            // Send our test email
            $this->_sendTestEmail($storeId, $template, $params);
            return true;
        }catch (Exception $e){
            return false;
        }
    }


    /**
     * @param $template_id
     * @return bool
     * @throws Exception
     */
    private function _sendCreditMemoNewEmail( $template_id )
    {

        $creditmemo             = $this->_getCreditMemo();
        $order                  = $this->_getOrder($creditmemo->getData('increment_id'));

        $storeId                = $order->getData('store_id');
        $emailSubject           = 'TEST New Credit Memo # ';
        $template               = $this->_getTemplate($template_id, $storeId);
        $languageCode           = $this->_languageCode;

        // Setup the parameters
        $params             = array(
            'order'         => $order,
            'creditmemo'    => $creditmemo,
            'payment_html'  => $this->_getPaymentHtml($storeId, $order),
            'language_code' => $languageCode,
            'subject'       => $emailSubject
        );

        try{
            // Send our test email
            $this->_sendTestEmail($storeId, $template, $params);
            return true;
        }catch (Exception $e){
            return false;
        }
    }

    /**
     * @param $template_id
     * @return bool
     * @throws Exception
     */
    private function _sendRussellInvoiceNewEmail( $template_id )
    {

        $invoice                = $this->_getInvoice();
        $order                  = $this->_getOrder();

        $storeId                = $order->getData('store_id');
        $emailSubject           = 'TEST New Russell Invoice # ';
        $template               = $this->_getTemplate($template_id, $storeId);
        $languageCode           = $this->_languageCode;

        // Setup the parameters
        $params             = array(
            'order'         => $order,
            'invoice'       => $invoice,
            'payment_html'  => $this->_getPaymentHtml($storeId, $order),
            'language_code' => $languageCode,
            'subject'       => $emailSubject
        );

        try{
            // Send our test email
            $this->_sendTestEmail($storeId, $template, $params);
            return true;
        }catch (Exception $e){
            return false;
        }

    }
    /**
     * @param $template_id
     * @return bool
     */
    private function _sendCreateOrderExceptionEmail( $template_id )
    {
        $template       = $this->_getTemplate($template_id, $this->_testStoreId);
        $params         = array(
            'stackTrace'        => $this->_getStackTrace(),
            'subject'           => 'TEST Create Order Exception',
        );
        try{
            $this->_sendTestEmail($this->_testStoreId, $template, $params);
            return true;
        }catch ( Exception $e ){
            return false;
        }
    }

    /**
     * @throws Exception
     */
    private function _sendNewOrderEmail( $template_id )
    {
        $order                  = $this->_getOrder();

        $storeId                = $order->getData('store_id');
        $emailSubject           = 'TEST New Order # ';
        $template               = $this->_getTemplate($template_id, $storeId);
        $languageCode           = $this->_languageCode;


        // Setup the parameters
        $params             = array(
            'order'         => $order,
            'billing'       => $order->getBillingAddress(),
            'payment_html'  => $this->_getPaymentHtml($storeId, $order),
            'language_code' => $languageCode,
            'subject'       => $emailSubject
        );

        try{
            // Send our test email
            $this->_sendTestEmail($storeId, $template, $params);
            return true;
        }catch (Exception $e){
            return false;
        }

    }

    private function _getPaymentHtml($store_id, $order)
    {
        if(!$store_id)
        {
            $store_id = $this->_testStoreId;
        }
        if(!(int)$order->getId())
        {
            $order = $this->_getOrder();
        }

        $appEmulation           = Mage::getSingleton('core/app_emulation');
        $orderPayment = $order->getPayment();

        $initialEnvironmentInfo = $appEmulation->startEnvironmentEmulation($store_id);
        try {
            // Retrieve specified view block from appropriate design package (depends on emulated store)
            $paymentBlock = Mage::helper('payment')->getInfoBlock($order->getPayment())
                ->setIsSecureMode(true);
            $paymentBlock->getMethod()->setStore($store_id);
            $paymentBlockHtml = $paymentBlock->toHtml();
        } catch (Exception $exception) {
            // Stop store emulation process
            $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);
            throw $exception;
        }
        // Stop store emulation process
        $appEmulation->stopEnvironmentEmulation($initialEnvironmentInfo);
        return $paymentBlockHtml;
    }







    private function _getCustomer()
    {
        return Mage::getModel('customer/customer')->load(53);
    }

    /**
     * @return Mage_Core_Model_Abstract
     */
    private function _getShipment()
    {
        return Mage::getModel('sales/order_shipment')->load(33);
    }
    /**
     * @return Mage_Core_Model_Abstract
     */
    private function _getCreditMemo( )
    {
        return Mage::getModel('sales/order_creditmemo')->load(100);
    }
    /**
     * @param null $increment_id
     * @return mixed
     */
    private function _getInvoice( $increment_id = null )
    {
        if( $increment_id )
        {
            $this->_incrementId = $increment_id;
        }
        return Mage::getModel('sales/order_invoice')->loadByIncrementId($increment_id);


    }

    /**
     * @return mixed
     */
    private function _getOrder( $increment_id = null )
    {

        if($increment_id)
        {
            return Mage::getModel('sales/order')->loadByIncrementId($increment_id);
        }
        $order = $this->_orders->getFirstItem();

        foreach($this->_orders as $_key => $_order)
        {
            // We want to remove this one from the collection
            if($_order->getId() == $order->getId())
            {
                $this->_incrementId = $_order->getData('increment_id');
                $this->_testStoreId = $_order->getData('store_id');
                $this->_orders->removeItemByKey($_key);
            }
        }
        return $order;
    }

    /**
     * @param $order
     * @return mixed
     */
    private function _getPaymentMethod($order)
    {
        return $order->getPayment()->getMethodInstance()->getCode();
    }

    /**
     * @param $template_id
     * @param $store_id
     * @return mixed
     */
    private function _getTemplate( $template_id, $store_id )
    {
        return Mage::getStoreConfig($template_id, $store_id);
    }

    /**
     * Example stack trace message
     * @return string
     */
    private function _getStackTrace()
    {
        return "exception 'Mage_Core_Exception' with message 'Invalid block type: Russell_Page_Block_Html_Head' in /var/www/nginx/ee114/app/Mage.php:595
Stack trace:
#0 /var/www/nginx/ee114/app/code/core/Mage/Core/Model/Layout.php(495): Mage::throwException('Invalid block t...')
#1 /var/www/nginx/ee114/app/code/core/Mage/Core/Model/Layout.php(437): Mage_Core_Model_Layout->_getBlockInstance('page/html_head', Array)
#2 /var/www/nginx/ee114/app/code/core/Mage/Core/Model/Layout.php(472): Mage_Core_Model_Layout->createBlock('page/html_head', 'head')
#3 /var/www/nginx/ee114/app/code/core/Mage/Core/Model/Layout.php(239): Mage_Core_Model_Layout->addBlock('page/html_head', 'head')
#4 /var/www/nginx/ee114/app/code/core/Mage/Core/Model/Layout.php(205): Mage_Core_Model_Layout->_generateBlock(Object(Mage_Core_Model_Layout_Element), Object(Mage_Core_Model_Layout_Element))
#5 /var/www/nginx/ee114/app/code/core/Mage/Core/Model/Layout.php(206): Mage_Core_Model_Layout->generateBlocks(Object(Mage_Core_Model_Layout_Element))
#6 /var/www/nginx/ee114/app/code/core/Mage/Core/Controller/Varien/Action.php(344): Mage_Core_Model_Layout->generateBlocks()
#7 /var/www/nginx/ee114/app/code/core/Mage/Cms/Helper/Page.php(113): Mage_Core_Controller_Varien_Action->generateLayoutBlocks()
#8 /var/www/nginx/ee114/app/code/core/Mage/Cms/Helper/Page.php(52): Mage_Cms_Helper_Page->_renderPage(Object(Mage_Cms_IndexController), 'home')
#9 /var/www/nginx/ee114/app/code/core/Mage/Cms/controllers/IndexController.php(45): Mage_Cms_Helper_Page->renderPage(Object(Mage_Cms_IndexController), 'home')
#10 /var/www/nginx/ee114/app/code/core/Mage/Core/Controller/Varien/Action.php(418): Mage_Cms_IndexController->indexAction()
#11 /var/www/nginx/ee114/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php(254): Mage_Core_Controller_Varien_Action->dispatch('index')
#12 /var/www/nginx/ee114/app/code/core/Mage/Core/Controller/Varien/Front.php(172): Mage_Core_Controller_Varien_Router_Standard->match(Object(Mage_Core_Controller_Request_Http))
#13 /var/www/nginx/ee114/app/code/core/Mage/Core/Model/App.php(354): Mage_Core_Controller_Varien_Front->dispatch()
#14 /var/www/nginx/ee114/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#15 /var/www/nginx/ee114/index.php(83): Mage::run('base', 'website')
#16 {main}";
    }

    /**
     * @param $storeId
     * @param $template_id
     * @param $params
     * @return bool
     */
    private function _sendTestEmail($storeId, $template_id, $params)
    {
        $sender_email           = '[email protected]';
        $sender                 = array("name" => "Russell", "email" => $sender_email);

        $mailer                 = Mage::getModel('core/email_template_mailer');
        $emailInfo              = Mage::getModel('core/email_info');
        $emailInfo->addTo($this->_recipient_email, 'TEST EMAIL RECIPIENT');

        $mailer->addEmailInfo($emailInfo);
        $mailer->setSender($sender);
        $mailer->setStoreId($storeId);
        $mailer->setTemplateId($template_id);
        $mailer->setTemplateParams($params);
        try{
            $mailer->send();
            return true;
        }catch (Exception $e){
            return false;
        }

    }
}

End part 3

0

app/code/local/Russell/Emaillog/etc/adminhtml.xml

<?xml version="1.0" encoding="UTF-8"?>
<config>

    <menu>
        <russell_admin_menu translate="title" module="russell_emaillog">
            <title>Russell Configurations</title>
            <sort_order>50</sort_order>
            <children>
                <russell_emaillog_entry translate="title" module="russell_emaillog">
                    <title>Email Log Config</title>
                    <children>
                        <emaillog translate="title" module="russell_emaillog">
                            <title>Review Logs Entries</title>
                            <action>adminhtml/emaillog_entry</action>
                            <sort_order>10</sort_order>
                        </emaillog>
                    </children>
                    <sort_order>250</sort_order>
                </russell_emaillog_entry>
                <russell_qa_options>
                    <title>QA Options</title>
                    <children>
                        <emailsend translate="title" module="russell_emaillog">
                            <title>Test Emails</title>
                            <action>adminhtml/emaillog_testemail</action>
                            <sort_order>10</sort_order>
                        </emailsend>
                    </children>
                    <sort_order>1000</sort_order>
                </russell_qa_options>
            </children>
        </russell_admin_menu>
    </menu>
    <!-- Add ACL Settings under System > Permissions > Roles -->
    <acl>
        <resources>
            <admin>
                <children>
                    <russell_admin_menu>
                        <children>
                            <russell_emaillog_entry translate="title" module="russell_emaillog">
                                <title>Manage Email Log Entries Section</title>
                                <sort_order>250</sort_order>
                            </russell_emaillog_entry>
                            <russell_qa_options>
                                <title>QA Options</title>
                                <sort_order>260</sort_order>
                            </russell_qa_options>
                        </children>
                    </russell_admin_menu>
                </children>
            </admin>
        </resources>
    </acl>
</config>

app/code/local/Russell/Emaillog/etc/config.xml

<?xml version="1.0"?>
<config>
    <modules>
        <Russell_Emaillog>
            <version>0.0.1</version>
        </Russell_Emaillog>
    </modules>
    <global>
        <blocks>
            <russell_emaillog>
                <class>Russell_Emaillog_Block</class>
            </russell_emaillog>
        </blocks>
        <models>
            <core>
                <rewrite>
                    <email_template>Russell_Emaillog_Model_Email_Template</email_template>
                </rewrite>
            </core>
            <russell_emaillog>
                <class>Russell_Emaillog_Model</class>
                <resourceModel>russell_emaillog_resource</resourceModel>
            </russell_emaillog>
            <russell_emaillog_resource>
                <class>Russell_Emaillog_Model_Resource</class>
                <entities>
                    <entry><table>russell_emaillog</table></entry>
                </entities>
            </russell_emaillog_resource>
        </models>
        <helpers>
            <russell_emaillog>
                <class>Russell_Emaillog_Helper</class>
            </russell_emaillog>
        </helpers>
        <resources>
            <russell_emaillog_setup>
                <setup>
                    <module>Russell_Emaillog</module>
                </setup>
            </russell_emaillog_setup>
        </resources>

    </global>
    <admin>
        <routers>
            <adminhtml>
                <args>
                    <modules>
                        <russell_emaillog before="Mage_Adminhtml">Russell_Emaillog_Adminhtml</russell_emaillog>
                    </modules>
                </args>
            </adminhtml>
        </routers>
    </admin>
    <!-- Admin Menu area -->
    <adminhtml>
        <layout>
            <updates>
                <russell_emaillog>
                    <file>russell/emaillog.xml</file>
                </russell_emaillog>
            </updates>
        </layout>
    </adminhtml>
</config>

app/code/local/Russell/Emaillog/etc/system.xml Russell 99999 Email Override and Log 200 1 0 0 russellconfig Email Override and Log General Configuration text 0 1 1 1 Log Emails select adminhtml/system_config_source_yesno Do you want to log all emails that are being sent?

                            <sort_order>90</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>0</show_in_website>
                            <show_in_store>0</show_in_store>
                        </log_emails>
                        <suppress_emails translate="label comment">
                            <label>Suppress All Emails</label>
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <comment>Do you want to suppress all emails from being sent?</comment>
                            <sort_order>90</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>0</show_in_website>
                            <show_in_store>0</show_in_store>
                        </suppress_emails>
                        <override_all_emails translate="label comment">
                            <label>Over-Ride Emails</label>
                            <frontend_type>select</frontend_type>
                            <source_model>adminhtml/system_config_source_yesno</source_model>
                            <comment>Do You want to override the default functionality and send the emails to a designated email address, instead of its intended recipient?  This is helpful if your testing your site and you do not want to accidentally spam your customers</comment>
                            <sort_order>100</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>0</show_in_website>
                            <show_in_store>0</show_in_store>
                        </override_all_emails>
                        <override_email_address translate="label">
                            <label>Over-Ride recipient Email address</label>
                            <frontend_type>text</frontend_type>
                            <validate>validate-email</validate>
                            <comment>If left empty, the default General Contact email will be used</comment>
                            <sort_order>120</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>0</show_in_website>
                            <show_in_store>0</show_in_store>
                        </override_email_address>
                        <override_name translate="label">
                            <label>Over-Ride recipient Name</label>
                            <frontend_type>text</frontend_type>
                            <comment>If left empty, a generic string similar to 'Russell Email Suppressed' will be used</comment>
                            <sort_order>120</sort_order>
                            <show_in_default>1</show_in_default>
                            <show_in_website>0</show_in_website>
                            <show_in_store>0</show_in_store>
                        </override_name>
                    </fields>
                </general>
            </groups>
        </russell_emaillog>
    </sections>
</config>

app/code/local/Russell/Emaillog/Helper/Data.php

/**
 * Class Russell_Emaillog_Helper_Data
 */
class Russell_Emaillog_Helper_Data extends Mage_Core_Helper_Abstract
{

}

app/code/local/Russell/Emaillog/Model/Email/Template.php

/**
 * Class Russell_Emaillog_Model_Email_Template
 */
class Russell_Emaillog_Model_Email_Template extends Mage_Core_Model_Email_Template
{

    protected $_name = 'Russell Email Suppressed';
    /**
     * Send mail to recipient
     *
     * @param   array|string       $email        E-mail(s)
     * @param   array|string|null  $name         receiver name(s)
     * @param   array              $variables    template variables
     * @return  boolean
     **/
    public function send($email, $name = null, array $variables = array())
    {

        if(Mage::getStoreConfig('russell_config/general/override_all_emails'))
        {
            $email = trim(Mage::getStoreConfig('russell_config/general/override_email_address'));
            if(strlen($email) == 0)
            {
                $email = Mage::getStoreConfig('trans_email/ident_general/email');
            }
        } 

        if(Mage::getStoreConfig('russell_config/general/override_all_emails') && Mage::getStoreConfig('russell_config/general/override_name'))
        {
            $name = Mage::getStoreConfig('russell_config/general/override_name');
            if(strlen($name) == 0)
            {
                $name = $this->_name;
            }
        }

        if (!$this->isValidForSend()) {
            Mage::logException(new Exception('This letter cannot be sent.')); // translation is intentionally omitted
            return false;
        }

        $emails     = array_values((array)$email);
        $names      = is_array($name) ? $name : (array)$name;
        $names      = array_values($names);
        foreach ($emails as $key => $email) {
            if (!isset($names[$key])) {
                $names[$key] = substr($email, 0, strpos($email, '@'));
            }
        }

        $variables['email'] = reset($emails);
        $variables['name']  = reset($names);

        ini_set('SMTP', Mage::getStoreConfig('system/smtp/host'));
        ini_set('smtp_port', Mage::getStoreConfig('system/smtp/port'));

        $mail = $this->getMail();

        $setReturnPath = Mage::getStoreConfig(self::XML_PATH_SENDING_SET_RETURN_PATH);
        switch ($setReturnPath) {
            case 1:
                $returnPathEmail = $this->getSenderEmail();
                break;
            case 2:
                $returnPathEmail = Mage::getStoreConfig(self::XML_PATH_SENDING_RETURN_PATH_EMAIL);
                break;
            default:
                $returnPathEmail = null;
                break;
        }

        if ($returnPathEmail !== null) {
            $mailTransport = new Zend_Mail_Transport_Sendmail("-f".$returnPathEmail);
            Zend_Mail::setDefaultTransport($mailTransport);
        }


        foreach ($emails as $key => $email) {
            $mail->addTo($email, '=?utf-8?B?' . base64_encode($names[$key]) . '?=');
        }

        $this->setUseAbsoluteLinks(true);
        $text = $this->getProcessedTemplate($variables, true);

        if($this->isPlain()) {
            $mail->setBodyText($text);
        } else {
            $mail->setBodyHTML($text);
        }

        $mail->setSubject('=?utf-8?B?' . base64_encode($this->getProcessedTemplateSubject($variables)) . '?=');
        $mail->setFrom($this->getSenderEmail(), $this->getSenderName());

        try {
            if (!Mage::getStoreConfig('russell_config/general/suppress_emails'))
            {
                $mail->send();
            }
            $this->_mail = null;
        }
        catch (Exception $e) {
            $this->_mail = null;
            Mage::logException($e);
            return false;
        }

        if (Mage::getStoreConfig('russell_config/general/log_emails') || is_null(Mage::getStoreConfig('russell_config/general/log_emails')))
        {
            $template_email_subject = $this->getData('template_subject');
            $template_email_body    =  $this->getData('template_text');
            $email_subject          = $this->getProcessedTemplateSubject($variables);

            // Capture the email
            // We are going to log each recipient
            foreach ($emails as $key => $_recipient_email) {
                // Log each recipient email
                $_recipient_name = $names[$key];
                $entry = Mage::getModel('russell_emaillog/entry');

                $values = array(
                    'sender_email'          => $this->getData('sender_email'),
                    'sender_name'           => $this->getData('sender_name'),
                    'recipient_email'       => $_recipient_email,
                    'recipient_name'        => $_recipient_name,
                    'template_email_subject' => $template_email_subject,
                    'template_email_body'   => $template_email_body,
                    'email_subject'         => $email_subject,
                    'email_body'            => $text,
                    'template_id'           => $this->getData('template_id'),
                    'store_id'              => $variables['store']->getData('store_id'),
                    'created_at'            =>date("Y-m-d H:i:s"),
                );
                $entry->setData($values);
                try{
                    $entry->save();
                }catch (Exception $e){
                    Mage::logException($e);
                }
            }
        }
        return true;
    }

    /**
     * Send transactional email to recipient
     *
     * @param   int $templateId
     * @param   string|array $sender sender information, can be declared as part of config path
     * @param   string $email recipient email
     * @param   string $name recipient name
     * @param   array $vars varianles which can be used in template
     * @param   int|null $storeId
     * @return  Mage_Core_Model_Email_Template
     */
    public function sendTransactional($templateId, $sender, $email, $name, $vars=array(), $storeId=null)
    {
        /*
         * I am pretty sure we don't need this here, its probably enough in send()
         *
         * if(Mage::getStoreConfig('russell_config/general/override_all_emails'))
        {
            $email = trim(Mage::getStoreConfig('russell_config/general/override_email_address'));
            if(strlen($email) == 0)
            {
                $email = Mage::getStoreConfig('trans_email/ident_general/email');
            }
        }
        else
        {
            $email = Mage::getStoreConfig('trans_email/ident_general/email');
        }

        if(Mage::getStoreConfig('russell_config/general/override_name'))
        {
            $name = Mage::getStoreConfig('russell_config/general/override_name');
            if(strlen($name) == 0)
            {
                $name = $this->_name;
            }
        }
        else
        {
            $name = $this->_name;
        }
        */

        $this->setSentSuccess(false);
        if (($storeId === null) && $this->getDesignConfig()->getStore()) {
            $storeId = $this->getDesignConfig()->getStore();
        }

        if (is_numeric($templateId)) {
            $this->load($templateId);
        } else {
            $localeCode = Mage::getStoreConfig('general/locale/code', $storeId);
            $this->loadDefault($templateId, $localeCode);
        }

        if (!$this->getId()) {
            throw Mage::exception('Mage_Core', Mage::helper('core')->__('Invalid transactional email code: ' . $templateId));
        }

        if (!is_array($sender)) {
            $this->setSenderName(Mage::getStoreConfig('trans_email/ident_' . $sender . '/name', $storeId));
            $this->setSenderEmail(Mage::getStoreConfig('trans_email/ident_' . $sender . '/email', $storeId));
        } else {
            $this->setSenderName($sender['name']);
            $this->setSenderEmail($sender['email']);
        }

        if (!isset($vars['store'])) {
            $vars['store'] = Mage::app()->getStore($storeId);
        }

        $this->setSentSuccess($this->send($email, $name, $vars));
        return $this;
    }

    /**
     * @return array
     */
    public function getEmailTemplates()
    {
        /**
        'sq_access_code_generation_complete/template'   => 'SQ Access Code Generation Complete',

         *
         *
         *
         *
         *
         *
         *
         * Templates we do NOT use so are not included here are listed below:
         *  'sales_email/order/guest_template'              => 'Guest Order',
         *
         *
         * Do not worry about the order, we are sorting it before we send it off
         */
        $templates = array(
            'customer/password/remind_email_template'       => 'Password New',
            'customer/password/forgot_email_template'       => 'Password Forgot',
            'customer/create_account/email_template'        => 'Account New',
            'sales_email/shipment/template'                 => 'Shipment New',
            'sales_email/shipment_comment/template'         => 'Shipment Update',
            'sales_email/creditmemo_comment/template'       => 'Creditmemo Update',
            'sales_email/creditmemo/template'               => 'Credit Memo New',

            'russell_invoice_new/template'                   => 'Russell Invoice New',

            'create_order_exception/template'               => 'Create Order Exception',

            'sales_email/order/template'                    => 'Order',

        );
        // try to sort things naturally ASC
        natsort($templates);
        // return our sorted list
        return $templates;
    } 
}

app/code/local/Russell/Emaillog/Model/Resource/Entry/Collection.php

/**
 * Class Russell_Emaillog_Model_Resource_Entry_Collection
 */
class Russell_Emaillog_Model_Resource_Entry_Collection extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
    /**
     *
     */
    protected function _construct()
    {
        $this->_init('russell_emaillog/entry');
    }
}

app/code/local/Russell/Emaillog/Model/Resource/Entry.php /** * Class Russell_Emaillog_Model_Resource_Entry */ class Russell_Emaillog_Model_Resource_Entry extends Mage_Core_Model_Resource_Db_Abstract { /** * */ protected function _construct() { $this->_init('russell_emaillog/entry', 'entity_id'); } }

app/code/local/Russell/Emaillog/Model/Entry.php

/**
 * Class Russell_Emaillog_Model_Entry
 */
class Russell_Emaillog_Model_Entry extends Mage_Core_Model_Abstract
{
    protected $_eventPrefix = 'russell_entry';
    protected $_eventObject = 'entry';

    /**
     *
     */
    protected function _construct()
    {
        $this->_init('russell_emaillog/entry');
    }   
}

app/code/local/Russell/Emaillog/sql/russell_emaillog_setup/install-0.0.1.php /* @var $installer Mage_Core_Model_Resource_Setup */ $installer = $this;

$installer->startSetup();

$tableName = $installer->getTable('russell_emaillog/entry');
$table = $installer->getConnection()->newTable($tableName)
    ->addColumn('entity_id', Varien_Db_Ddl_Table::TYPE_INTEGER, null, array(
        'identity'  => true,
        'nullable'  => false,
        'primary'   => true,
    ), 'Entity Id')
    ->addColumn('sender_email', Varien_Db_Ddl_Table::TYPE_TEXT, 255, array(
        'nullable'  => true,
        'default'   => '',
    ), 'Sender Email')
    ->addColumn('sender_name', Varien_Db_Ddl_Table::TYPE_TEXT, 255, array(
        'nullable'  => true,
        'default'   => '',
    ), 'Sender Name')
    ->addColumn('recipient_email', Varien_Db_Ddl_Table::TYPE_TEXT, 255, array(
        'nullable'  => true,
        'default'   => '',
    ), 'Recipient Email')
    ->addColumn('recipient_name', Varien_Db_Ddl_Table::TYPE_TEXT, 255, array(
        'nullable'  => true,
        'default'   => '',
    ), 'Recipient Name')
    ->addColumn('template_email_subject', Varien_Db_Ddl_Table::TYPE_TEXT, 255, array(
        'nullable'  => true,
        'default'   => '',
    ), 'Email Template Subject')
    ->addColumn('template_email_body', Varien_Db_Ddl_Table::TYPE_TEXT, '1k', array(
        'nullable'  => false,
    ), 'Email Template Body')
    ->addColumn('email_subject', Varien_Db_Ddl_Table::TYPE_TEXT, 255, array(
        'nullable'  => true,
        'default'   => '',
    ), 'Actual Email Subject')
    ->addColumn('email_body', Varien_Db_Ddl_Table::TYPE_TEXT, '1k', array(
        'nullable'  => false,
    ), 'Actual Email Body')
    ->addColumn('store_id', Varien_Db_Ddl_Table::TYPE_SMALLINT, null, array(
        'unsigned'  => true,
        'nullable'  => false,
        'default'   => '0',
    ), 'Store Id')
    ->addColumn('template_id', Varien_Db_Ddl_Table::TYPE_TEXT, 255, array(
        'nullable'  => true,
        'default'   => '',
    ), 'Template Id')
    ->addColumn('created_at', Varien_Db_Ddl_Table::TYPE_TIMESTAMP, null, array(
        'nullable'  => false,
        'default'   => Varien_Db_Ddl_Table::TIMESTAMP_INIT,
        'comment'   => 'Created At',
    ), 'Created At')
    ->addIndex($this->getIdxName($tableName, array('sender_email', 'store_id')),
        array('sender_email', 'store_id'))
    ->addForeignKey($this->getFkName($tableName, 'store_id', 'core/store', 'store_id'),
        'store_id', $this->getTable('core/store'), 'store_id',
        Varien_Db_Ddl_Table::ACTION_CASCADE, Varien_Db_Ddl_Table::ACTION_CASCADE)
    ->setComment('Email Log Table');

$installer->getConnection()->createTable($table); 
$installer->endSetup();

End of part 5

0

I had the exact same problem. My module was apparently based on this article as well: http://markshust.com/2012/07/05/creating-magento-adminhtml-grids-simplified

In the Controller, look at the end of the function editAction()

$this->_initAction()
    ->_addBreadcrumb(...)
    ->_addContent(...)
    ->renderLayout();

I changed it into that to make it work:

//$this->_initAction()
$this->_addBreadcrumb(...)
    ->_addContent(...)
    ->renderLayout();

I can't explain why. I didn't find any side effect so far.

0

Problem is in editAction, there should be three function called as given below order:

public function editAction() {
    $this->loadLayout();
    $this->getLayout();
    $this->renderLayout();
}

If getLayout() is not called then addError messages are not collected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.