12

I am having an issue getting a custom model's value to update to NULL.

$model = Mage::getModel('custom/model')->load($id);
$model->setCustomValue(NULL);
$model->save();

This code does not update the field custom_value in the database, and the database value accepts NULL values (Manually setting NULL in the database works fine).

EDIT: As Tim mentions below using Zend_Db_Expr("NULL") does set the value to null, could anyone explain why this is required in Magento and not just simply a php NULL ?

5
  • just try $model->setCustomValue("");
    – Mufaddal
    Commented Jul 2, 2014 at 11:10
  • The type of the table field is double and I have tried other numeric types like decimal and doing $model->setCustomValue(""); sets the value to 0 Commented Jul 2, 2014 at 11:36
  • 8
    How about $null = new Zend_Db_Expr("NULL"); ? Commented Jul 2, 2014 at 11:42
  • 2
    @Invoke, to reply to your answer, if you only set it to "NULL" Magento will only think you don't want to update the value. As Tim suggested, you need to specify that it's the database "NULL" that you want to set. Commented Jul 2, 2014 at 14:49
  • Thanks @mayers-dev, interesting behaviour. I guess it was designed as a get-out-clause should you need to cancel the intended update while generating the value itself. Commented Jul 2, 2014 at 15:24

1 Answer 1

2

This is, as so often a isset() vs array_key_exists() problem, when I see this correctly.

I didn't try it, but from code reading I would say, the value is checked here:

\Mage_Eav_Model_Entity_Abstract::_saveAttribute
if (!isset($this->_attributeValuesToSave[$table])) {
    $this->_attributeValuesToSave[$table] = array();
}

and because isset return false on a set array key which is NULL, your value is overwritten.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.