Magento – Magento:2 How to save unique values for the custom admin module

adminhtmldatabaseform-validationmagento2

I am making a custom admin module which store custom data. I want to save unique values in table field.

How I can check unique column value before save data, show error message if values already exist.

Which is the best way as per Magento standard?

Thank

Best Answer

I think you should follow the same path which Magento follow in module CMS for unique cms block identifier and unique cms page url, you can add _beforeSave method in your ResourceModel class and check your unique value.

In CMS block you can find this,

 protected function _beforeSave(AbstractModel $object)
    {
        if (!$this->getIsUniqueBlockToStores($object)) {
            throw new LocalizedException(
                __('A block identifier with the same properties already exists in the selected store.')
            );
        }
        return $this;
    }

File path vendor\magento\module-cms\Model\ResourceModel\Block.php

From here you can get your starting point

Related Topic