In Magento 1, we used the lockAttribute($attributeCode)
method from a catalog_product_edit_action
observer, and it prevented the admin user from editing that particular attribute. See Read-Only Product Backend attribute.
Magento 2 has the same lockAttribute
method in Magento\Catalog\Model\AbstractModel
. However, the UI for the attribute is no different after calling this method.
I also tried it on catalog_product_save_before
, and it still allowed me to apply a new value to the attribute.
Vendor/Module/Observer/Lock.php
namespace Vendor\Module\Observer;
class Lock implements \Magento\Framework\Event\ObserverInterface
{
/**
* Observer to catalog_product_save_before to lock attributes.
*
* @param \Magento\Framework\Event\Observer $observer
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
$product = $observer->getEvent()->getProduct();
$product->lockAttribute('my_custom_attribute');
}
}
Vendor/Module/etc/adminhtml/events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<!-- <event name="catalog_product_save_before"> -->
<event name="catalog_product_edit_action">
<observer name="test_lock_attributes" instance="Vendor\Module\Observer\Lock"/>
</event>
</config>