0

Where is the correct place to validate field in model?

For example, I have a database, with a table Product, but the database designer didn't force NOT NULL in some required fields (for instance, column SKU). So now I have to check whether these fields are NULL or not by code

I thought it will be added in setData() method. But I think setData() should only care about the "set data" job. Is there any better place for this validation job?

1

As far as I know, our model usually derives from \Magento\Framework\Model\AbstractModel class. So, we can validate the data before saving it by using Observer or overload beforeSave method in our Model.

1

After a couple of hours googling, I found this article https://www.ashsmith.io/magento2/module-from-scratch-module-part-2-models/

Model is used to interact with data Resource model is used to interact with database (CRUD for example)

So I think the best place to check data validation is in Resource model.

In Resource model, there is a method called _beforeSave

    /**
     * Process post data before saving
     *
     * @param \Magento\Framework\Model\AbstractModel $object
     * @return $this
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
    {
    }

Override this function to validate data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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