Custom observer not being triggered - magento

I am trying to write an observer for magento that will be triggered when an order has been marked as shipped and has been given a tracking number.
When I go in through the admin and place an order, invoice and then go to ship the function I need to call is never actually called, and I do not understand why.
I have go through a couple of of pages on the magento website to see what I might be doing wrong, but I just cant figure it out (http://www.magentocommerce.com/wiki/5_-_modules_and_development/0_-_module_development_in_magento/customizing_magento_using_event-observer_method & http://www.magentocommerce.com/knowledge-base/entry/magento-for-dev-part-2-the-magento-config).
Please note that I do see the module within the admin Advanced area and it is enabled.
If anyone could look over the code I have attached and let me know where my issue is, it would be much appreciated.
Here is my Observer class which is located in app/code/local/WR/TrackingEmail/Model/Observer.php
class WR_TrackingEmail_Model_Observer
{
public function sendTrackEmail($observer)
{
$track = $observer->getEvent()->getTrack();
$shipment = $track->getShipment(true);
$shipment->sendEmail();
}
}
Here is my config.xml for the module
<config>
<global>
<modules>
<wr_trackingemail>
<version>0.1.1</version>
</wr_trackingemail>
</modules>
<events>
<sales_order_shipment_track_save_after>
<observers>
<Wr_trackingemail_model_observer>
<type>singleton</type>
<class>WR_TrackingEmail_Model_Observer</class>
<method>sendTrackEmail</method>
</Wr_trackingemail_model_observer>
</observers>
</sales_order_shipment_track_save_after>
</events>
</global>
</config>
Here is my app/etc/modules/WR_TrackingEmail.xml
<config>
<modules>
<WR_TrackingEmail>
<active>true</active>
<codePool>local</codePool>
</WR_TrackingEmail>
</modules>
</config>

Your statement "Custom observer not being triggered" leaves a lot of room for interpretation. Here's what you'll want to check.
Your observer appears to be setup correctly (although the modules tag belongs outside the global tag, but that doesn't appear to matter for this case). You can test your setup by running the following code yourself from a blank controller action (or other bootstrapped, event loaded, Magento script)
Mage::dispatchEvent('sales_order_shipment_track_save_after');
and then replacing your sendTrackEmail with this
public function sendTrackEmail($observer)
{
exit(__METHOD__);
}
If execution halts with the text
WR_TrackingEmail_Model_Observer::sendTrackEmail
you'll know your event is configured correctly.
If your event IS configured correctly, the next step is to ensure that the event is actually being fired when you perform the steps above. You can log these events in app/Mage.php by adding this temporary logging code
public static function dispatchEvent($name, array $data = array())
{
//brain dead logging
file_put_contents('/tmp/events.log',"$name\n",FILE_APPEND);
Varien_Profiler::start('DISPATCH EVENT:'.$name);
$result = self::app()->dispatchEvent($name, $data);
#$result = self::registry('events')->dispatch($name, $data);
Varien_Profiler::stop('DISPATCH EVENT:'.$name);
return $result;
}
Also, there's a good chance that leaving your exit in above will still result in execution halting if your event is being fired.
If you've determined your observer is configured correctly, AND your event is being fired, then the problem isn't an event being triggered, but your observer code not doing what you think its doing. Re-add your code but keep your exit in place
class WR_TrackingEmail_Model_Observer
{
public function sendTrackEmail($observer)
{
$track = $observer->getEvent()->getTrack();
$shipment = $track->getShipment(true);
$shipment->sendEmail();
exit(__METHOD__);
}
}
This will allow you to reload the browser over and over again to test your observer code. Good luck!

Have you registered your module under app/etc/modules/ in a .xml file?
<?xml version="1.0"?>
<config>
<modules>
<Wr_Trackingemail>
<active>true</active>
<codePool>local</codePool>
</Wr_Trackingemail>
</modules>
</config>

Related

Change the customer group according to the custom field created in the magento checkout page

I have created a custom field in magento onepage checkout page. When a user is filling this field his customer group should set to group 1 and if the field is left blank his customer group should be group 2.
My main problems
1) How to set the customer group value programatically when user is registering thru checkout page
2) How to relate my custom field value and customer group value in checkout process.
Thanks in advance.
To achieve solution for above question, You need to use event observer pattern of magento, their is event called customer_save_before, That will help you to get required answer.
Now, we have to add in our custom module. I am calling my module Customer and it is part of the Npm group. So, the file should be named app/etc/modules/Npm_Customer.xml. Add the following code into this file:
<config>
<modules>
<Npm_Customer>
<active>true</active>
<codePool>local</codePool>
</Npm_Customer>
</modules>
</config>
Next, we need to create the code for the module. The idea behind our code is that we are going to create an observer on the customer_save_before event. Magento has a number of events that we can observe but most are beyond the scope of this article. What is useful is that the customer_save_before event is called both when a customer is created and when a customer makes changes to their account. This means that the one observer will be able to do the work for both events.
All of the code we are writing for our module will be located inside the app/code/local/Npm/Customer/ directory. The first file is etc/config.xml:
<?xml version="1.0"?>
<config>
<modules>
<Npm_Customer>
<version>1.0</version>
</Npm_Customer>
</modules>
<global>
<events>
<customer_save_before>
<observers>
<npm_customer_save_observer>
<type>singleton</type>
<class>Npm_Customer_Model_Customer_Observer</class>
<method>customerSaveBefore</method>
</npm_customer_save_observer>
</observers>
</customer_save_before>
</events>
</global>
</config>
The next step is to create the class that we have just told Magento we are going to use, and should be defined in the file Model/Customer/Observer.php:
<?php
class Npm_Customer_Model_Customer_Observer extends Mage_Core_Model_Abstract
{
/*
* observer for the customer saved event
*/
public function customerSaveBefore($observer)
{
try {
$customer = $observer->getCustomer();
if (null != $customer->getPermissionCode()) {
$customer->setData('group_id', 4); // Set the new customer group
} else {
$customer->setData('group_id', 1); // Set to the default customer group
}
} catch ( Exception $e ) {
Mage::log("customer_save_before observer failed: " . $e->getMessage());
}
}
}
Customers are now automatically assigned to your new group if they supply Permission code from the registration form.
Thanks

Magento 1.9 redirect customer after registration

I would like to redirect all customers to a custom page after successful registration in Magento 1.9.
I have tried many things. Firstly, I am successfully overriding the core customer account controller.
I have attempted to customize the following actions:
createPostAction
_successProcessRegistration
_welcomeCustomer
By trying to set redirect url or by setting BeforeAuthUrl
//$successUrl = $this->_getUrl('*/*/index', array('_secure' => true));
$successUrl = $this->_getUrl('*/*/success');
$this->_getSession()->setBeforeAuthUrl('http://test.local/customer/account/success/');
if ($this->_getSession()->getBeforeAuthUrl()) {
$successUrl = $this->_getSession()->getBeforeAuthUrl(true);
}
return $successUrl;
Please note at this point, $successUrl is correct when it returns here. I see there are some post Dispatch methods that I am assuming are destorying this url and always returning to customer/account/index.
I have read several posts on this topic and cannot find a definitive answer that solves this question.
I have even set hidden form element 'success_url' in attempts to follow steps presented elsewhere as solutions to this.
What is the full, correct process that one needs to follow in order to be able to show a one time registration success page?
I know this is an old thread maybe this will help someone else out trying to accomplish the same thing. You can set the redirect URL in the register.phtml template directly without having to modify controllers or create a module. You can set success and error URLs with hidden inputs like this.
<input type="hidden" name="success_url" value="my-custom-success-url.html" />
<input type="hidden" name="error_url" value="my-custom-error-url.html" />
I used this to redirect the user back to where they entered the login/register process like this:
<?php $ref = $this->getRequest()->getParam('referer');?>
<input type="hidden" name="success_url" value="<?php echo !empty($ref)?Mage::helper('core')->urlDecode($ref):$this->getSuccessUrl(); ?>" />
if you want to do this for customer successfully then you can do this using event observer
after customer successfully magento trigger an event customer_register_success
This call an observer which will reequestion to custtom page
Mage::app()->getResponse()->setRedirct($Yourdreicurll);
Details:
Step1:
create config.xml is app/code/community/Amit/Custommodule/etc/ - See more at: http://www.amitbera.com/create-an-magento-extension-with-custom-database-table/#sthash.JSktrUD0.dpuf
and it code
<?xml version="1.0" ?>
<config>
<modules>
<Amit_Custommodule>
<version>1.0.0</version>
</Amit_Custommodule>
</modules>
<global>
<models>
<custommodule>
<class>Amit_Custommodule_Model</class>
</custommodule>
</models>
</global>
<frontend>
<events>
<customer_register_success>
<observers>
<notify_user>
<class>custommodule/observer</class>
<method>myredirection</method>
</notify_user>
</observers>
</customer_register_success>
</events>
</frontend>
</config>
Step2:
create module control file Module name as Amit_Custommodule.xml at app/etc/modules/
it code is
<?xml version="1.0"?>
<config>
<modules>
<Amit_Custommodule>
<codePool>community</codePool>
<active>true</active>
</Amit_Custommodule>
</modules>
</config>
Step3:
Create observer.php at Amit>Custommodule>Model
code is
<?php
class Amit_Custommodule_Model_Observer {
public function myredirection(Varien_Event_Observer $observer) {
$AccountController = $observer->getEvent()->getAccountController();
$Customer = $observer->getEvent()->getCustomer();
$response1 = Mage::app()->getResponse(); // observers have event args
$url = 'http://www.example.com/';
$response1->setRedirect($url);
Mage::app()->getFrontController()->sendResponse();
return;
}
}
You are doing this in right way, this is the best way to redirect customer to custom URL.
Go to customer accountcontroller find _welcomeCustomer method.
Search for $successUrl = $this->_getUrl('*/*/index', array('_secure' => true)); replace this code with your custom URL $successUrl = $this->_getUrl('costomURL', array('_secure' => true));
It works fine for me.

How to Protect user,for visit product page in magento

I am working in a Magento site, Requirement is when user comes to the site user should be redirect to login page,
Without visit any product page.
After register he will be able to view the products,
I have already tried but not getting any solution yet.
Anyone can help me on this?
You can simply use free available extension on magento connect. I used this extension for my store http://www.magentocommerce.com/magento-connect/login-check.html
It is free and doing job nice.
You can try the following approach as described here. Since posting single link answers is not recommended, here is what you need to do.
You need to create an observer for the event controller_action_predispatch for frontend. You can do that in a custom module. Let's call that module Easylife_Restrict.
You will need the following files:
app/etc/modules/Easylife_Restrict.xml - the declaration file.
<?xml version="1.0"?>
<config>
<modules>
<Easylife_Restrict>
<codePool>local</codePool>
<active>true</active>
<depends>
<Mage_Customer />
</depends>
</Easylife_Restrict>
</modules>
</config>
app/code/local/Easylife/Restrict/etc/config.xml - the configuration file
<?xml version="1.0"?>
<config>
<modules>
<Easylife_Restrict>
<version>1.0.0</version>
</Easylife_Restrict>
</modules>
<global>
<models>
<easylife_restrict>
<class>Easylife_Restrict_Model</class>
</easylife_restrict>
</models>
</global>
<frontend>
<events>
<controller_action_predispatch>
<observers>
<easylife_restrict>
<class>easylife_restrict/observer</class>
<method>redirectNotLogged</method>
</easylife_restrict>
</observers>
</controller_action_predispatch>
</events>
</frontend>
</config>
app/code/local/Easylife/Restrict/Model/Observer.php - the module observer - this is where the magic happens:
<?php
class Easylife_Restrict_Model_Observer{
public function redirectNotLogged(Varien_Event_Observer $observer)
{
//get the current request action
$action = strtolower(Mage::app()->getRequest()->getActionName());
//get the current request controller
$controller = strtolower(Mage::app()->getRequest()->getControllerName());
//a list of allowed actions for the not logged in user
$openActions = array(
'create',
'createpost',
'login',
'loginpost',
'logoutsuccess',
'forgotpassword',
'forgotpasswordpost',
'resetpassword',
'resetpasswordpost',
'confirm',
'confirmation'
);
//if the controller is the customer account controller and the action is allowed for everyone just do nothing.
if ($controller == 'account' && in_array($action, $openActions)) {
return $this; //if in allowed actions do nothing.
}
//if the user is not logged in redirect to the login page
if(! Mage::helper('customer')->isLoggedIn()){
Mage::app()->getFrontController()->getResponse()->setRedirect(Mage::getUrl('customer/account/login'));
}
}
}
Clear the cache and give it a try.
Please use this
Step 1: Go to Admin => System => Configuration => Customer Configuration => Login Options => "Redirect Customer to Account Dashboard after Logging in" set it "No".
Step 2: If you're using a module page then you've the controller Action method like:
public function indexAction()
{
// use here to restrict the page //
if(!Mage::helper('customer')->isLoggedIn()){
Mage::getSingleton('customer/session')->setBeforeAuthUrl('Restricted Page Url');
$this->_redirect('customer/account/login');
}
// End your addition //
$this->loadLayout();
$this->renderLayout();
}
you can use one of this code to redirect:
Mage::getSingleton('customer/session')->setBeforeAuthUrl('Restricted Page Url');
$this->_redirect('customer/account/login');
OR
$this->_redirect('customer/account/login/referer/'.Mage::helper('core')->urlEncode('Restricted Page Url'));
Step 3: (optional) If you're using a cms page then follow this step:
In your admin CMS section include a phtml page and write the below code at the top of the page:
if(!Mage::helper('customer')->isLoggedIn()){
Mage::getSingleton('customer/session')->setBeforeAuthUrl('Restricted Page Url');
$this->_redirect('customer/account/login');
}
>> Now if you want to use the login url inside a page with referer url follow this:
<?php $referer = Mage::helper('core')->urlEncode(Mage::helper('core/url')->getCurrentUrl()); ?>
Login
I think it will solve your problem

how we use product duplicate observer event at custom module?

This is my config.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!--
Document : config.xml
Created on : July 26, 2012, 1:12 PM
Author : sanjeewani
Description:
Purpose of the document follows.
-->
<config>
<modules>
<Proporta_AmazonBarcode>
<version>0.1.0</version>
</Proporta_AmazonBarcode>
</modules>
<global>
<events>
<catalog_model_product_duplicate>
<observers>
<proporta_amazonbarcode_observer>
<class>Proporta_AmazonBarcode_Model_Observer</class>
<method>duplicate1</method>
</proporta_amazonbarcode_observer>
</observers>
</catalog_model_product_duplicate>
</events>
</global>
</config>
and this is my Observer class function.
public function duplicate1(Varien_Event_Observer $observer) {
$product=$observer->getEvent()->getProduct();
/*
my logic is here
*/
}
It's coming properly to duplicate1() function when I try to duplicate the product from admin.
My problem is, $product is null. I can't get product from event. Anyone have an issue like this?
It's because product is not a key of the event context. If you are unsure, what the context is, it's a good idea to look where the event is dispatched[1]. In this case in app/code/core/Mage/Catalog/Model/Product.php in the method Mage_Catalog_Model_Product::duplicate():
Mage::dispatchEvent(
'catalog_model_product_duplicate',
array('current_product' => $this, 'new_product' => $newProduct)
);
So, what you probably want to do is this:
$product = $observer->getEvent()->getCurrentProduct();
[1] or use a debugger, place a break point and inspect $observer
You have to put product ID , without ID , it wont work. When it comes to debugger , get HTTP Debugger , put BP , and observe response and everything that could look suspicious.

Getting Magento to send email when a payment is received

I don't believe Magento has an out of box method of sending an email to inform the owner when a payment has been received so is there any way that this can be programmed?
So far I have read this but it looks like it might be more focused on sending the email to the customer instead of the vendor; and this but apart from being completely lost ( as by the sound of it was the OP ) one person said accepted answer was a bit out of date and also I'm not sure it's what I need anyway.
Basically, what you need is (surprise) an observer module to do exactly that. Also, it is quite the same work in one of the links you provided.
To make a barebones observer module, you only need three files:
/app/etc/modules/Electricjesus_Notifyowner.xml
<?xml version="1.0"?>
<config>
<modules>
<Electricjesus_Notifyowner>
<active>true</active>
<codePool>local</codePool>
</Electricjesus_Notifyowner >
</modules>
</config>
/app/code/local/Electricjesus/Notifyowner/etc/config.xml
<?xml version="1.0"?>
<config>
<modules>
<Electricjesus_Notifyowner>
<version>0.1.0</version>
</Electricjesus_Notifyowner>
</modules>
<global>
<models>
<notifyowner>
<class>Electricjesus_Notifyowner_Model</class>
</notifyowner>
</models>
<events>
<sales_order_payment_pay>
<observers>
<notifyOwnerEvent>
<class>notifyowner/observer</class>
<method>notifyOwnerEvent</method>
</notifyOwnerEvent>
</observers>
</sales_order_payment_pay >
</events>
</global>
</config>
/app/code/local/Electricjesus/Notifyowner/Model/Observer.php
<?php
class Electricjesus_Notifyowner_Model_Observer
{
public function notifyOwnerEvent($observer)
{
// parameters you can get from the $observer parameter:
// array(’payment’ ? $this, ‘invoice’ ? $invoice)
$payment = $observer->getPayment();
$invoice = $observer->getInvoice();
// derivative data
$order = $invoice->getOrder(); // Mage_Sales_Model_Order
$ownerEmail = 'owner#shop.com';
/*
- build data
- build email structure
- send email via any php mailer method you want
*/
return $this; // always return $this.
}
}
You can also use other events in place of sales_order_payment_pay (see config.xml). See this list for a semi-complete list of events along with their parameters. And on this document to is some techniques to check/get an update of the current list of events with their parameters.
I recommend using Zend_Mail to do your mail stuff inside the observer. Nothing special, I'm just biased towards Zend stuff.
http://framework.zend.com/manual/en/zend.mail.html
--- EDIT
if you want a ready-made extension to do this (and more) and if you do not mind paying for it, you can take a look at:
http://www.magentocommerce.com/magento-connect/admin-email-notifications.html

Resources