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

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.

Related

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

Why does magento catch wrong event from admin section?

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

Magento - Displaying custom attribute in accounts area (front-end)

I have used this module creator to get an custom attribute (which takes the type 'file').
http://www.silksoftware.com/magento-module-creator/
This works and can be seen in the admin area. I also have other custom attributes for customers which I have used this tutorial to create:
http://www.fontis.com.au/blog/magento/know-more-about-your-customers-adding-custom-signup-attributes
This also works. The reason I used the module creator was because I was unsure of how to make the input type as 'file'.
The attributes created through the fontis tutorial can be displayed as needed on the front end (which was only needed in the registration form).
The problem I'm having is in the custom area in the logged in accounts area on the front end. What I need is to retrieve the value of the 'file' attributes which was created in the module creator. Could anyone point me in the right direction of how to display these please? I have tried getAttributeName but this is not working.
Thank you.
If you post the code from your custom module we could help you more.
Meanwhile, here is some info that could help you:
Whenever you store something in the DB using a module, there is a Model class (that allows you to access the necessary data)
You can find the class name by looking in your modules etc/config.xml file
In the file look for section named <models>
The sub nodes of <models> is the name of the namespace (see below)
The sub node of your 'namespace' called <class> contains the rest of the info you will need
Next you need to call the Model with Mage::getModel('namespace/class_name')->load($id); to get a collection of all the custom attribute records that are in the system
To break this down in to manageable pieces:
Let's assume this is what your config.xml contains:
<models>
<customattribute> // this is your namespace
<class>Mycompany_Customattribute_Model</class> //this tells you wher to find your model files
<resourceModel>customattribute_resource</resourceModel>
</customattribute>
...
</models>
This means that your 'namespace' is 'customattribute'.
Next you need to find the file that contains your Model.
In this case we look at the <class> node to give us the file location (in this case app/code/local/Mycompany/Customattrbute/Model), now we need to go there and see the file that is there (let's say it's called 'File.php')
To get all the data we call the follwoing function:
Mage::getModel('customattribute/file')->load();
This will give us all the data.
If we want to narrow it down we can use the following function:
Mage::getResourceModel('customattribute/file')->addFieldToFilter('name_of_filed_in_db', 'value_we_want');

Is there a comprehensive list of observer events?

Is there a comprehensive list of all events that can be listened for?
If this list doesn't exist, what's the best method to debug to obtain all events?
You'll never find a complete list. But if you go to app/Mage.php you can put in some debug code inside of the function "dispatchEvent()" and log all of the events as you go.
$params = array();
foreach (array_keys($data) as $key) {
if (is_object($data[$key])) {
$params[] = $key.' ('.get_class($data[$key]).')';
} else {
$params[] = $key.' ('.gettype($data[$key]).')';
}
}
Mage::log('event_name:'.$name.',event_passed_keys:'.implode('|',$params),null,'events.log',true);
Then using some excel wizardry you can parse those out into a list of all of the event names and parameters being passed to it.
The problem with many of the compiled lists or even doing the grep as shown above is that many of the events are dynamically created. Which lets you discern what events there are that aren't listed.
Make sure to comment out that debug code or the events.log file will become huge after just a short time.
Take a look at a list of events #
http://www.nicksays.co.uk/magento_events_cheat_sheet/
Customize Magento using Event/Observer
or
To log all the event for a specific page in your dev environment you could add Mage::log($eventName);
in /app/code/core/Mage/Core/Model/App.php
public function dispatchEvent($eventName, $args){
Mage::log($eventName);
....
or
grep -r Mage::dispatchEvent /path/to/your/Magento/* > events.txt
Read more #
Magento which event is called? Need to build an observer
https://magento.stackexchange.com/questions/153/where-can-i-find-a-complete-list-of-magento-events
As an exercise I wrote a Bash script to generate rough list of events (it actually acts as a wrapper to grep with a few switches to provide context and available params).
I've used this script to generate events lists for default Magento installations for versions 1.3.3.0 to 1.8.0.0 version and the code is available at GitHub:
https://github.com/Marko-M/magento-events-list/
Lists of events are available here:
https://github.com/Marko-M/magento-events-list/tree/master/magento-outofthebox
and a follow up article on my blog here:
http://www.techytalk.info/bash-script-to-generate-list-of-events-for-magento-installation/
Be aware that these lists can never be complete due to many event names being generated dynamically.
As you probably have extensions on your project and they dispatch their own events, it's even better to generate this list manually trough grep or using my script.
Cheers!
a general mean is to set an observer for any specific event you are interesting in
see https://magento.stackexchange.com/questions/314/how-to-know-the-magento-event-that-we-want-to-hook
in the module Logevent, the config.xml
0.1
Maticode_Logevent_Model
<controller_action_predispatch>
<observers>
<Logevent>
<type>singleton</type>
<class>Logevent/observer</class>
<method>controller_action_predispatch</method>
</Logevent>
</observers>
</controller_action_predispatch>
and the Model/observer.php
<?php
class Maticode_Logevent_Model_Observer {
public function controller_action_predispatch($observer) {
Mage::log ( $observer->getEvent ()->getControllerAction ()->getFullActionName (),null, 'eventlog.log' );
}
}
This way , in the
var/log/eventlog.log file
u can visualize a possible hook on any tested actions (click on a button and check your log )

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
}
}

Resources