Magento – How to save serialized value into a table in magento

magento-1.7

In my custom model I want to store the data in serialized form. For achieving it by myself I have done the following thing but instead of all this 0 is getting stored against value

In my class Inchoo_Custombuilders_Model_Mysql4_Cableconnector extends Mage_Core_Model_MySql4_Abstract file

 $this->_serializableFields = array(
        'cable_id' => array(null, array())
    );

I also tried override the _beforeSave Action

 protected function _beforeSave()
 {
    if(is_array($this->getValue())){
        var_dump($this->getValue());die();
        $this->setValue(serialize($this->getValue()));
    }
 }

And I cannot change the database table design because some functionality that is build on the frontend is running from this table only.

What is the proper way to save serialize data into database in Magento.

Best Answer

Your methods seem a little bit off. If that _beforeSave() is inside of the Inchoo_Custombuilders_Model_Mysql4_Cableconnector class, then it should have an $object parameter passed in, and you should be checking $object->getValue(), not $this->getValue().

Now, assuming that the field name on the model is value (which by the way I would try to avoid that - I think you might run into mysql reserved keyword issues), and assuming that $object->getValue() contains an array, then what you seem to be doing should basically work fine:

protected function _beforeSave($object)
{
    if ($object->getValue()) {
        $serializedValue =  serialize($object->getValue());
        $this->setValue($serializedValue);
    }
}

If it isn't, then check to see what the value of $serializedValue is to make sure that it is what you expect it to be.