I am installing a custom attribute through the normal Magento module install script. It is a simple select box with Yes or No:
<?php
$installer = Mage::getResourceModel('catalog/setup','catalog_setup');
$installer->startSetup();
$installer->addAttribute(
'catalog_category',
'my_attribute',
array(
'label' => 'My attribute label',
'group' => 'My Group', //will be created if necessary
'type' => 'int',
'class' => 'validate-number',
'source' => 'eav/entity_attribute_source_boolean',
'required' => false,
'input' => 'select',
'global' => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_GLOBAL,
'visible' => true,
'visible_on_front' => true,
)
);
$installer->endSetup();
This is all good – it installs fine and if I change the value in the admin area the value gets saved correctly.
I also need a way to manually set that value via AJAX. This controller gets called correctly via a http://www.mywebsite.com/mymodule/setmyattribute/index/id/1
:
<?php
class Mynamespace_Mymodule_SetmyattributeController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
$categoryId = $this->getRequest()->getParam('id'); // Get id from params (1)
$category = Mage::getModel('catalog/category')->load($categoryId); // Load category (loads fine)
$category->setMyattribute(0); // <-- set Attribute
$category->save(); // <-- save the category
var_dump($category->getMyattribute()); // <-- Equals 0 here which is correct but doesn't equal 0 in the admin area
/** Re-index the products and category EAV **/
$process = Mage::getModel('index/process')->load(5); $process->reindexAll(); // Re-index category EAV
$process = Mage::getModel('index/process')->load(6); $process->reindexAll(); // Re-index Category Products
echo Mage::helper('core')->jsonEncode(array('status'=>'success'));
die();
}
}
Now the var_dump
above does as expected and reports 0
. However it doesn't seem to save it properly as in the admin area the value is still 1
. Why is this and how do I make it save correctly?
In my stand-alone Magento scripts when I am setting category attributes I have to put this line at the top:
<?php
Mage::app('admin'); // And not ('default')
To set custom category attributes, how do I achieve the same with the above controller?
Best Answer
Expanding on @TimVroom's answer please use store emulation in favor of changing the
currentStore
or setting theisSecureArea
. You can read more about emulation on the Inchoo blog.