Why does magento catch wrong event from admin section? - magento

I have set up a default 'no modifications' copy of magento on a local machine to replicate the results on our production machine.
When I try to catch the event 'adminhtml_customer_save_after' in a module, it always returns / stops on customer_save_before. This is also true for any of the customer_save_after type events.
Adding
file_put_contents('/tmp/events.log','Dispatching '. $name. "\n",FILE_APPEND);
to the dispatchEvent function in /var/www/app/Mage.php verifies that it indeed does return on customer_save_before, even though that is not the event i'm asking for.
Please validate this and let me know if this is intended functionality. I must have access to the entity_id in magento admin section when our call center / order team creates new customers in the admin side of the site (for placing phone-in orders) for synchronization with our company's database.
PHP from module
<?php
class NKI_CustomerSync_Model_Observer
{
public function AddCustomerToQueue($observer)
{
$event = $observer->getEvent();
$customer = $event->getCustomer();
$model=$event->getModel();
echo "<PRE>";
var_dump($event->getName());
var_dump($event->getData());
var_dump($event);
var_dump(get_class_methods($event));
die();
}.....
XML
<config>
<modules>
<NKI_CustomerSync>
<version>0.1.0</version>
</NKI_CustomerSync>
</modules>
<global>
<events>
<adminhtml_customer_save_after>
<observers>
<NKI_customersync_model_observer>
<type>singleton</type>
<class>NKI_CustomerSync_Model_Observer</class>
<method>AddCustomerToQueue</method>
</NKI_customersync_model_observer>
</observers>
</adminhtml_customer_save_after>

First, since your post betrays a few misunderstandings about how Magento's event system works, which in turn is leading you to diagnose the problem incorrectly, here's a quick review of the event system.
The dispatchEvent method in Mage.php is the wrong place to check if Magento "catches" your event. This method receives all events. It's not until deeper in the calling chain, in Mage_Core_Model_App's identically named dispatchEvent method
#File: app/code/core/Mage/Core/Model/App.php
public function dispatchEvent($eventName, $args)
{
foreach ($events[$eventName]['observers'] as $obsName=>$obs) {
//...
}
}
where Magento will look for any event observers (or in your parlance, event catchers)
Magento issues all sorts of events on every request. The customer_save_before event is issued whenever a customer model object is saved. This includes saving both on the frontend and the backend. However, the adminhtml_customer_save_after event is fired here
#File: app/code/core/Mage/Adminhtml/controllers/CustomerController.php
public function saveAction()
{
//...
$customer->save();
//...
Mage::dispatchEvent('adminhtml_customer_prepare_save', array(
'customer' => $customer,
'request' => $this->getRequest()
));
//..
}
In other words, this event fires in the saveAction of the admin customer controller. In other other words, this event fires after a user clicks "save" in the Magento admin console when looking at an individual customer.
So, both the customer_save_before and the adminhtml_customer_save_after event will fire when a customer gets saved in the Magento admin. The customer_save_before event fires first, and then the adminhtml_customer_save_after event fires.
As for your specific code, what you've shown looks correct. That assuming you have the closing } on the observer class, and that it's in the correct location.
app/code/community/NKI/CustomerSync/Model/Observer.php
//or, if your module is configured in the local code pool
app/code/local/NKI/CustomerSync/Model/Observer.php
and that your module's config.xml has a closing </config>, is valid XML, and is in your module's etc/config.xml file. This also assumes Magento can see your module.
I used your code to throw together a skeleton module and your event fired when I saved a customer on the backend of Magento. That skeleton module is here. Compare it to what you have to see where your module may be subtly incorrect.

The Event Should be put in adminhtml and is called customer_save_after

Related

Perform Some Action after Customer successful Login : Magento

I am creating a module in which I want to check some condition after customer successfully login, if condition is true then customer login otherwise not.
I know two ways of doing this :
Overriding AccountController
With Magento event.
My query are:
which is the best way?
Is there any event with which I can full fill my requirement?
Or if there is other best way of doing this, please recommend.
You need to use customer_login
On the Mage_Customer_Model_Session model's method setCustomerAsLoggedIn() the event customer_login is dispatched.
config.xml
<customer_login>
<observers>
<yourobservername>
<type>model</type>
<class>yourmodule/path_to_class</class>
<method>customerLogin</method>
</yourobservername>
</observers>
</customer_login>
and your Observer
class YourCompany_YourModule_Model_Observer
{
public function customerLogin($observer)
{
$customer = $observer->getCustomer();
}
}
Whenever a user is sucessfully logged in, the event customer_login will be fired and you have observed the method customerLogin() on that event, so your method from the observer will execute whenever a customer is successfully logged in.
Here you can check your conditions as per requirements.
I think the best way to use magento event if possible. But in your case you have to check the condition before customer logins am i right? If so i don't think there is any events for that.So the best way is to override the controller.

Event After Every Model Save

I would assume that there is an event after every model save.
How is this formatted, and is there a way to log all of these events?
This is useful if there is not a standard event declared within the moudle you are looking to extend.
Here is what I think the best answer would be based on all of the information that you've been provided.
A model does not necessarily need to fire an event at save/edit/delete however if it extends the Mage_Core_Model_Abstract class without overriding the default methods associated with save/edit/delete the events will be fired.
In order for an event to be unique to that model $this->_eventPrefix must be unique to that model
Logging these events often does not work
To find the particular event you are looking for
If you are using an IDE this should be much easier but you can also use utilities like grep.
Make a search within the module that you are working with for "$_eventPrefix ="
Use the list below to find the appropriate event suffix
Concatenate the two together and you should have your event
_load_before
_load_after
_save_before
_save_after
_save_commit_after
_delete_before
_delete_after
_delete_commit_after
_clear
To Log all events go to app/Mage.php line 446 and add:
Mage::setIsDeveloperMode(true);
Mage::log($name);
Take a look at Mage_Core_Model_Abstract::afterCommitCallback - it has a generic event and an event dispatched by the prefix of the specific model being saved.
/**
* Callback function which called after transaction commit in resource model
*
* #return Mage_Core_Model_Abstract
*/
public function afterCommitCallback()
{
Mage::dispatchEvent('model_save_commit_after', array('object'=>$this));
Mage::dispatchEvent($this->_eventPrefix.'_save_commit_after', $this->_getEventData());
return $this;
}
Whether you want this or
/**
* Processing object after save data
*
* #return Mage_Core_Model_Abstract
*/
protected function _afterSave()
{
$this->cleanModelCache();
Mage::dispatchEvent('model_save_after', array('object'=>$this));
Mage::dispatchEvent($this->_eventPrefix.'_save_after', $this->_getEventData());
return $this;
}
depends on whether you care if the data has actually been written to the database or not when you run your event handler.
When Magento sees a call to Mage::dispatchEvent it will call any public model class registered for that specific event name. So the real place to look for events is in the config.xml for the module/models you're interested in. The xml is not likely to be programmatically generated, so you don't have to fuss around with guessing _eventPrefix values. You know the event suffix you want, so just look in configuration for events with names ending with that suffix.
If you have an installed store, you can use n98-magerun to search the config.xml. (It has a config:get command that you can use to search, but I prefer config:dump to a file, followed by using an xml parser and xpath to search through the result.)
I always put a log into app/Mage.php into dispatchEvent() method
...
Mage::log($name, array_keys($event_data));
...
Then I refresh the page in the browser where I need to apply a custom event action and then look into system.log to see what events happen on my page.
Just need to put something like below in config.xml:
<global>
<events>
<catalog_entity_attribute_save_commit_after>
<observers>
<yourextension_save_commit_after_observer>
<type>singleton</type>
<class>yourextension/save_commit_after_observer</class>
<method>yourMethod</method>
</yourextension_save_commit_after_observer>
</observers>
</catalog_entity_attribute_save_commit_after>
</events>
</global>
That's correct. There is a _save_before and _save_after events after every model save, such as catalog_product_before_save, catalog_product_after_save, customer_address_before_save, customer_address_after_save, etc.
You can refer to this link below for more complete information about how to use it and the complete list of all events in Magento.
Source: http://www.vjtemplates.com/blog/magento/events-and-observers

Magento Observer Destination

I have wrote 2 Magento observers and they both do exactly what I want with the exception that they end on the wrong page. In other words, they write the log files, modify the databases, and talk with other servers, but they modify the page to page routing. For example, I have an observer that I used at login that modifies a database, writes a cookie, and writes to a log, but it changes the post log-in page to
http://www.my-web-site.com/index.php/customer/login/post/
and then gives me a 404 error. If I hit "Ctrl" + 'r' then I am logged in at
http://www.my-web-site.com/index.php/customer/account/index/
which is correct. If I change, app/code/local/my_module/my_model/etc/config.xml to
app/code/local/my_module/my_model/etc/config.xml.1 (in other words take out the observer), then Magento routes to the correct page,
I'm thinking that I need router information in config.xml. My current config.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<!-- The root node for Magento module configuration -->
<config>
<!-- The module's node contains basic information about each Magento module -->
<modules>
<!-- This must exactly match the namespace and module's folder
names, with directory separators replaced by underscores -->
<MyCompany_LogIn>
<!-- The version of our module, starting at 0.0.0 -->
<version>0.0.0</version>
</MyCompany_LogIn>
</modules>
<!-- Configure our module's behavior in the global scope -->
<global>
<!-- Defining models -->
<models>
<!-- Unique identifier in the model's node.
By convention, we put the module's name in lowercase. -->
<mycompany_login>
<!-- The path to our models directory,
with directory separators replaced by underscores -->
<class>MyCompany_LogIn_Model</class>
</mycompany_login>
</models>
</global>
<frontend>
<!-- Defining an event observer -->
<events>
<!-- The code of the event we want to observe -->
<customer_login>
<!-- Defining an observer for this event -->
<observers>
<!-- Unique identifier within the catalog_product_save_after node.
By convention, we write the module's name in lowercase. -->
<mycompany_login>
<!-- The model to be instantiated -->
<class>mycompany_login/observer</class>
<!-- The method of the class to be called -->
<method>wrtLogInCookie</method>
<!-- The type of class to instantiate -->
<type>singleton</type>
</mycompany_login>
</observers>
</customer_login>
</events>
</frontend>
</config>
I'm guessing that the login inside Magento uses an observer, and I'm interfering with it.
Besides the , I'm guessing that I could also accomplish a similar thing in the PHP Observer code. My observer is:
<?php
/**
* Our class name should follow the directory structure of
* our Observer.php model, starting from the namespace,
* replacing directory separators with underscores.
* i.e. /www/app/code/local/MyCompany/LogIn/Model/Observer.php
*/
class MyCompany_LogIn_Model_Observer extends Varien_Event_Observer
{
/**
* Magento passes a Varien_Event_Observer object as
* the first parameter of dispatched events.
*/
public function wrtLogInCookie(Varien_Event_Observer $observer)
{
// Retrieve the product being updated from the event observer
$customer = $observer->getEvent()->getCustomer();
$email = $customer->getEmail();
Mage::log('The E-mail is: ' . $email);
$ran_nmbr = rand();
Mage::log('The random number is: ' . $ran_nmbr);
$crnt_dat = date("m-d-Y::H:i:s");
Mage::log('The date is: ' . $crnt_dat);
return $this;
}
}
?>
I have read about routers, but the articles discussed it in terms of landing on some page before the extension is executed. As you can see, I need to land on the right page after the extension is executed.
Inside the PHP observer, I also tried redirects. For example,
Mage::app()->getResponse()->setRedirect(Mage::getUrl('customer/account/login'));
Maybe I need a full URL address or something. I'm sure this is easy to fix, but my ignorance seems to be following me around. Please help if you know something about this.
Unfortunately, it's not quite as simple as an easy fix. You see, if we look at app/code/core/Mage/Customer/controllers/AccountController.php, in the loginPostAction(), we see that the customer/session singleton triggers the customer_login call. However, what is causing the trip-up here is that after that is called, back in the controller, the controller calls $this->_loginPostRedirect(), so all of your rerouting work that you did is overwritten.
How to fix:
After saying it isn't all that simple, I did happen to see a cheat that we can take advantage of:
$session = Mage::getSingleton('customer/session');
$session->setBeforeAuthUrl($forwardToUrl);
You're partially right. The problem you're running into is Magento's redirect mechanism works with a "last one to say something" wins philosophy. If you look at the standard login code in
app/code/core/Mage/Customer/controllers/AccountController.php
You'll see the loginPostAction method ends with a call to
$this->_loginPostRedirect();
which (ultimately) ends up calling some code that looks like this
$this->getResponse()->setRedirect($url);
This may be the code that's causing you a problem, or it may be something else. The general problem is the final call to the response object's setRedirect method will win.
My usual solution to this is setting some sort of global flag (static variable on a class, a flag set with Mage::register) when I want to perform a redirect, and then creating an additional observer for controller_action_postdispatch. In this observer I look for the global flag I set, and if I find it, set the redirect there.
This handled 99% of redirect situations, and should handle yours. The times this won't work are with some admin login cases, as well as URL rewrites.
The admin login contains some redirect code that doesn't use Magento response object
#File: app/code/core/Mage/Admin/Model/Session.php
...
header('Location: ' . $requestUri);
exit;
...
If this redirect is causing you a problem, create a listener for admin_session_user_login_success that uses PHP header redirects before Magento's does.
Similarly, if Magento's using a rewrite object, the following code might run
#File: app/code/core/Mage/Core/Model/Url/Rewrite.php
if ($isPermanent) {
header('HTTP/1.1 301 Moved Permanently');
}
header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
header('Pragma: no-cache');
header('Location: ' . $url);
exit;
(that said, the rewrite code will rarely be your problem, as in standard Magento operation is runs before controller dispatch)

Magento - module with system config, how do I do something on save?

I have a simple module created with the Magento Module Creator with a couple of settings in admin->system->config.
When I go to these settings and choose the enable/disable option, the settings get saved - which is great - however, I want to run my own code after that, i.e. on the save action, once the data has been saved.
In your etc/system.xml add a backend model descended from Mage_Core_Model_Config_Data and use it's _afterSave() method to run your code.
although it isnt a good idea but you can achieve it by observers:
<controller_action_postdispatch_adminhtml_mymodule_mycontroller_myaction>
replace the my-s with module_controller_action, and most likely you want to put it in this event:
<controller_action_postdispatch_adminhtml_system_config_save>
in your config xml as follows:
<controller_action_postdispatch_adminhtml_system_config_save>
<observers><myobserver>
<type>singleton</type>
<class>mymodule/observer</class>
<method>mymethod</method>
</myobserver></observers>
</controller_action_postdispatch_adminhtml_system_config_save>
and in mymodule, as in your module have a class observer in mymodule/Model/Observer.php
and declare the observer as
class modules_mymodule_observer {
public function myfunction(Varien_Event_Observer $observer){
//do your stuffs
}
}

Magento backend_model - do I need to specify for each config field?

If I want to do something extra when a particular configuration field for my custom module is saved (over and above saving to the Magento core config table), I can just specify a backend_model for that field in my system.xml, and have that backend model class extend Mage_Core_Model_Config_Data, override _afterSave, and put my extra stuff in that method.
But what if I have several fields I want to do this for. I don't want the behaviour to be to save field1 and call my afterSave for that field, save field2 and call my afterSave for that field, etc. I'd rather that all the fields were saved to the Magento core config table, and then I do my extra stuff.
Is that possible? I thought I might be able to achieve that using event/observer. So in my config.xml, <adminhtml> section, I added an observer as follows:
<events>
<admin_system_config_changed_mysection>
<observers>
<mypfx_admin_system_config_changed_mysection>
<class>mymodule/adminhtml_system_config_backend_configSaveObserver</class>
<method>myConfigSaved</method
</mypfx_admin_system_config_changed_mysection>
</observers>
</admin_system_config_changed_mysection>
</events>
but my observer method is not called when the config is saved. Maybe I have the wrong event name? The "mysection" bit on the end of the event name I was guessing had to match the section from system.xml:
<sections>
<mysection translate="label" module="mymodule">
...
<groups>
...
</groups>
</mysection>
</sections>
Thanks.
The event you're trying to listen for doesn't exist. Here's what you want to do, and some tips for picking the right event in the future.
First, every event is fired in Magento by the Mage::dispatchEvent method. Search the core code for these calls and you'll always know the name of the event you want to listen for.
$ ack 'admin_system_config_changed_'
Adminhtml/controllers/System/ConfigController.php
136: Mage::dispatchEvent("admin_system_config_changed_section_{$section}",
From the above, you can see the name of the event vs. what you thought it was
admin_system_config_changed_section_{$section}
admin_system_config_changed_mysection
So, it looks like you're missing the section before your own section name.
Second, while working on a development box, the best way to find the event you're looking for is to log things at the source. Temporarily add some debugging code to the dispatchEvent function.
#File: app/Mage.php
public static function dispatchEvent($name, array $data = array())
{
//either one of the lines below should do it. One uses Magento's
//built in logging, the other uses something more crude
#Mage::Log($name);
#file_put_contents('/tmp/test.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;
}
This will dump a huge list of event names out to your log. I typically use OS X's Console.app to view the log file during the request, copy the lines out, sort and remove duplicates, and then end up with a list like this
admin_system_config_changed_section_commercebug
admin_user_load_after
admin_user_load_before
adminhtml_block_html_before
adminhtml_controller_action_predispatch_start
application_clean_cache
controller_action_layout_generate_blocks_after
controller_action_layout_generate_blocks_before
controller_action_layout_generate_xml_before
controller_action_layout_load_before
controller_action_layout_render_before
controller_action_layout_render_before_adminhtml_system_config_edit
controller_action_postdispatch
controller_action_postdispatch_adminhtml
controller_action_postdispatch_adminhtml_system_config_edit
controller_action_postdispatch_adminhtml_system_config_save
controller_action_predispatch
controller_action_predispatch_adminhtml
controller_action_predispatch_adminhtml_system_config_edit
controller_action_predispatch_adminhtml_system_config_save
controller_front_init_before
controller_front_init_routers
controller_front_send_response_after
controller_front_send_response_before
core_abstract_load_after
core_abstract_load_before
core_block_abstract_prepare_layout_after
core_block_abstract_prepare_layout_before
core_block_abstract_to_html_after
core_block_abstract_to_html_before
core_collection_abstract_load_after
core_collection_abstract_load_before
core_config_data_load_after
core_config_data_save_after
core_config_data_save_before
core_config_data_save_commit_after
core_layout_block_create_after
core_locale_set_locale
core_session_abstract_add_message
core_session_abstract_clear_messages
http_response_send_before
model_load_after
model_load_before
model_save_after
model_save_before
model_save_commit_after
resource_get_tablename
store_load_after
store_load_before
You still need to use some intelligence guessing to figure out which event you want, but they're named intuitively enough that you can usually find what you're looking for.
You need to tie your observer method to a specific Magento event (you can add your own, but need to find when you want it to be fired and add your own dispatchEvent call). If Magento has an event built in, use that event name in the config.
There's a pdf of the built in event lists on the web - google for it & you'll find it.

Resources