How to update existing cms page through install sc

2019-08-03 10:04发布

问题:

I have this script

$cmsPage = Array ( 
    'title' => 'Test Page 1',
    'root_template' => 'one_column', 
    'identifier' => 'testpage1', 
    'content' => "<p>Testowa sprawa czy działa update ? oooooooooooo</p>", 
    'is_active' => 1,
    'stores' => array(1), 
    'sort_order' => 0 
);
$collection = Mage::getModel('cms/page')->getCollection()->addFieldToFilter('identifier', 'testpage1');
$page = Mage::getModel('cms/page')->load($collection->getFirstItem()->getId());
$page->setData($cmsPage)->save();

If cms page with identifier "testpage1" exist , the script create another with the same identifier. Is there a way to check if cmspage exist - and if that is true - do update ?

回答1:

When you call $page->setData($cmsPage) you remove all data from the Mage_Cms_Model_Page object and replace it with the data from the $cmsPage array. Part of the data you are removing is the page_id from the object's internal $_data array. The page_id is what maps the object to a column in the cms_page database table. By removing that ID you make Magento run an INSERT query rather than an UPDATE.

Something like this should work:

$pageId = $collection = Mage::getModel('cms/page')->getCollection()->addFieldToFilter('identifier', 'testpage1')->getFirstItem()->getId();
$page = Mage::getModel('cms/page')->load($pageId);

$cmsPage = Array ( 
    'page_id' => $pageId,
    'title' => 'Test Page 1',
    'root_template' => 'one_column', 
    'identifier' => 'testpage1', 
    'content' => "<p>Testowa sprawa czy działa update ? oooooooooooo</p>", 
    'is_active' => 1,
    'stores' => array(1), 
    'sort_order' => 0 
);

$page->setData($cmsPage)->save();


标签: php magento