Magento 1.9 Backend Model _afterSave and _afterLoad Methods

configurationmagento-1.9

I am making a simple plugin that would save some data to DB when you click "Save Config" button in system configurations. I have added this to my system.xml

<frontend_type>select</frontend_type>
<source_model>adminhtml/system_config_source_yesno</source_model>
<backend_model>storesave/config_save</backend_model>

And in Save.php I am using _afterSave() method. I select the 'yes', but it does not run the code the first time "Save config" button is clicked. It only runs the code after I click the button second time. But when I select 'No' option and press "Save config" it reruns the code before save happens.

So I tried the _afterLoad() method, but if it was saved with 'yes' option selected, it runs the code the moment I go to my config page before I even press "Save config".

Finally I tried Using both methods to make a workaround.

public function _afterSave(){
    $this->saveState = true;
}

public function _afterLoad()
{   
    if($this->saveState == true){
        //execute code here
    }
}

But the _afterLoad() method does not trigger this way because $saveState always remains false.

So I would like to know why is this happening, and how could I make it work?

EDIT:

I use this as a check for yes No options:

   const XML_PATH_ENABLED = 'storesave/global/status';
    public function isEnabled(){
        return Mage::getStoreConfig(self::XML_PATH_ENABLED);
    }
    public function _afterSave()
    {
        if ($this->isEnabled() == true){
            //run the code
        }
    }

Even with this if selected state is Yes and I set it to No and Press "Save config", the _afterSave method still runs the code inside my if statement. So my thought is that how to make it not do that.

Best Answer

I'm assuming the default value for your option is Yes. Magento has a short-circuit mechanism to prevent most of the code in save from triggering if the data on a model is the same as the data on the model at the point it was loaded (see Mage_Core_Model_Abstract::save(). The code you place in _afterSave will therefore only get triggered if the option actually changes (which in most cases is all you really want, but your requirements may be different). As you have found the _afterLoad method will get triggered when you load the page, not just when you click save.

If your requirement is to always trigger your custom code, only when save is called, the best bet will be to simply override the save method itself.

public function save()
{
    // do your custom work here
    parent::save();
}
Related Topic