Domanda

I have a field in admin from which only be change at the time of new record. On the form edit, I want to show that field as editable but don't want to save the changes. For that, I have created the beforeSave method in resource model.

protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
{
    if ($object->getId()) {
        // how will I prevent specific field to update here
        // or reset a field to it's old value
    }
    return parent::_beforeSave($object);
}

Let suppose the field is email. Then code should be something like

protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
{
    if ($object->getId()) {
        $object->setData("email", "OLD_EMAIL");
        $object->("Reset Email Changes");
    }
    return parent::_beforeSave($object);
}

I know that I can use registry and get current model which was set from Edit controller and modify data in Save controller but I want know "is there any way to achive it in beforSave

È stato utile?

Soluzione

You can reach this by getting old value from OrigData.

Example in beforeSave public method which every model has (\Magento\Framework\Model\AbstractModel::beforeSave). Example with email field:

/**
 * @inheridoc
 */
public function beforeSave()
{
    $this->setData('email', $this->getOrigData('email'));
}

But if you need to do this in _beforeSave, you can do following:

$object->setData('email', $object->getOrigData('email'));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a magento.stackexchange
scroll top