Update single attribute value
-
08-10-2020 - |
Question
I'm a Magento newbee so please forgive me if there is ... a crap in the code ... Sending Ajax request with Brand ID and current state "status = 1 or 0" and would like to update state in table:
public function BrandsAction()
{
$brand_id = $this->getRequest()->getPost("brand_id");
$status = $this->getRequest()->getPost("status");
$_category = Mage::getResourceModel('catalog/category_collection')
->addFieldToFilter('name', 'Brands')
->getFirstItem();
$categoryId = $_category->getId();
$brands = Mage::getModel('catalog/category')->load($categoryId);
$brand = $brands->load($brand_id);
foreach($brand as $element){
echo $element;
if($element->getId() == $brand_id){
$element->getData();
$element->getAttribute('show_brand');
$element->setData('show_brand',$status);
$element->save();
}
}
I expected it will update value in column 'show_brand' but it actually does nothing just returning data back so I can see in console what values were sent. How to update value for specified "category -> Brand -> Somebrand" ?? Did I miss something ?
//just checking category id
$categoryId = $_category->getId();
//loading selected category
$brands = Mage::getModel('catalog/category')->load($categoryId);
//Loading Brand Data
$brand = $brands->load($brand_id);
isn't it ? Or I misunderstood something ?
Current code:
public function BrandsAction()
{
$brandNameId = $this->getRequest()->getPost("brand_id");
$status = $this->getRequest()->getPost("status");
$brandsNameCat = Mage::getModel('catalog/category')->load($brandNameId);
$brandsNameCat->setShowBrand($status);
$brandsNameCat->save();
}
not updating values in table ... what I should check to make sure it willl update values ?
Solution
In that case below code should work
<?php
function BrandsAction()
{
$brand_id = $this->getRequest()->getPost("brand_id");
// I assume $brand_id is your brand name category id which is subcategory or brands (Parent category)
$status = $this->getRequest()->getPost("status");
$brandsNameCat = Mage::getModel('catalog/category')->load($brand_id);
$brandsNameCat->setShowBrand($status);
$brandsNameCat->save();
}
OTHER TIPS
To avoid saving the entire model and improve the performance, you can replace the following code:
$brandsNameCat->save();
With:
$brandsNameCat->saveAttribute($brandsNameCat, 'show_brand');