Magento – save new tab data in separate table when save cms >> page data

adminadminhtmlcmsforms

I am developing a module in magento. I added a new Tab in CMS >> Page core module through my custom module. I want to save new tab data in separate table which one created by custom module. My problem is that I don't know how can I save new tab data in my new table when core page's save/edit functionality works?

Thanks in advance.

Best Answer

EDIT: The entire answer updated, to accommodate new cms page creation.

Ok, you can solve this in multiple ways, rewrites are one (rewriting controller and models of the cms system (yuk)) or just using observers/events. I prefer observer events, as it makes for higher compatibility with other 3rd party modules.

As per my previous answer, the flaw was that I suggested using only the 'cms_page_prepare_save' event, but as you had found that does not work for new pages. Why? Because the page model has not saved yet, thus no page id.

However, this event is the only event available that also passes the request data, so it must be used.

The solution: Use two events. The first stays as 'cms_page_prepare_save', which allows you to get the request data, and the second will be an event on the model save after 'cms_page_save_after'.

Thus the process will be:

  1. Observe the 'cms_page_prepare_save' event
  2. Grab the request data and extract your tabs data.
  3. Set that against the page model that was also passed (this is temp storage so you can use it later)
  4. Listen to the cms page model save after event. 'cms_page_save_after'
  5. Grab your data out of the page model, as well as the page id and use it.

So here goes:

In the observer event 'cms_page_prepare_save' you will have code like this:

public function cms_page_prepare_save(Varien_Event_Observer $observer) {
        $requestParams = $observer->getRequest()->getParams(); 
        $page = $observer->getPage();
        $page->setData('request_params',$requestParams); // save the request data to the page model. This will not intevere with normal model functionality as it will be ignored by anything else.
        return $this;
    }

Next you have another observer on 'cms_page_prepare_save' event with this code:

public function cms_page_save_after(Varien_Event_Observer $observer) { 
        $page = $observer->getObject();
        $requestParams = $page->getRequestParams();
        // do what you need to do with your tab data, which is now in $requestParams
        return $this;
    }

Ideally in the cms_page_prepare_save observer code you'd only store your tabs information, not the entire request params, as that could be a lot of data. You could also use this event to filter/sanetise/check your data, before the models get saved.

Hope this adjusted answer helps.