1

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?

3 Answers 3

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.

1

Looking at the code of save method in Magento\Framework\Model\ResourceModel\Db, I can see that there is validateBeforeSave method which is being called on model object, so you can override _getValidationRulesBeforeSave method in your model where you can provide set of validation rules to validate your model.

Additionally, if validation fails then you can use _dataSaveAllowed flag to stop the saving operation.

Refer Magento\User\Model\User.php for reference.

I hope this helps someone looking for model data validation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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