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

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

Related

Magento Helper Directory Structure

I have a custom module and everything works fine. I'm adding and admin panel portion to the module and would like a separate admin helper. I know I can create and call my admin helper like this:
app/code/local/namespace/module/helper/Admin.php
class Namespace_Module_Helper_Admin extends Mage_Core_Helper_Abstract....
$helper = Mage::helper('namespace_module/admin');
And everything works great.
I was really wanting the structure for my admin helper to be something like this:
app/code/local/namespace/module/helper/admin/Data.php
But can't figure out the how to set that up in config.xml and then call the helper.
My initial thought was to setup the config like this:
...
<helper>
<namespace_module>
<class>Namespace_Module_Helper</class>
</namespace_module>
<namespace_module_admin>
<class>Namespace_Module_Admin_Helper</class>
</namespace_module_admin>
</helper>
...
Then call the helper like this:
$helper = Mage::helper('namespace_module_admin');
But this doesn't work.
Is it possible to have a second helper for my module in a helper directory child directory? If so could someone point me in the right direction.
Thanks for the help!
Yes, it is possible to do this but I think you have some typos. I was able to register a new helper using your approach with settings like this:
<helpers>
<namespace_module>
<class>Namespace_Module_Helper</class>
</namespace_module>
<namespace_module_admin>
<class>Namespace_Module_Helper_Admin</class>
</namespace_module_admin>
</helpers>
The helper file itself was at the path: app/code/local/Namespace/Module/Helper/Admin/Data.php
The helper class looks like this:
class Namespace_Module_Helper_Admin_Data extends Mage_Core_Helper_Abstract
{
public function test()
{
return 'test';
}
}
And I was able to invoke it with the syntax:
Mage::helper('namespace_module_admin')->test();
So it is possible that your issue is due to your file/class name not matching up with the location Magento’s autoloader was expecting. For example your <class>Namespace_Module_Admin_Helper</class> should map to the (improper) directory app/code/local/Namespace/Module/Admin/Helper rather than the expected app/code/local/Namespace/Module/Helper/Admin.
Your approach looks fine and absolutely right. You have only one mistake in config.xml. You should name node <helpers> instead of <helper>

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

Error extends AccountController.php in magento

I'm trying to extend the core AccountController.php -> app/code/core/Mage/Customer copied it to app/code/local/Mage/ and add a log to see which extends properly.
In the file AccountController.php (app/code/local/Mage/Customer/controllers)
...
...
public function createPostAction() {
Mage::log('In app/code/local/Mage/', null, 'test.log', true);
...
...
AND CORE (only test)
In the file AccountController.php (app/code/core/Mage/Customer/controllers)
...
...
public function createPostAction() {
Mage::log('In app/code/core/Mage/', null, 'test.log', true);
...
...
And does not go through code/local/ Mage but by CORE.
I need to configure something or it fails?
The logic through which controller class definitions are loaded builds the path to the file above the explicit include paths on which the autoloader relies. This means no local vs. core precedence.
You need to creat a controller rewrite by specifying a directory under the xpath frontend/routers/customer/args/modules/your_module
The latter node needs the before attribute set to Mage_Customer and you will need to create an AccountController.php with a createPostAction() method. Depending on your needs you may or may not need to extend from and require the core account controller class.
I guess you need to require the original controller:
require_once Mage::getModuleDir('controllers', 'Mage_Customer').DS.'AccountController.php';
Normally you need to do this with rewriting a controller the xml way...i havent checked in code, but maybe this is the problem.
I would recommend to do it the regular way via config.xml
http://www.magentocommerce.com/wiki/5_-_modules_and_development/0_-_module_development_in_magento/how_to_overload_a_controller

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