Các bài trước chúng ta đã cùng nhau tìm hiểu về source mode, frontend model rồi và hôm nay. Chúng ta sẽ tìm hiểu về backend model trong Magento 2. Các bạn có thể xem lại các bài này để hiểu rõ hơn về những gì chúng ta sẽ học trong bài viết này.
Khi mà các giá trị trong Stores > Configuration được lưu. Nhờ vào backend model mà chúng ta có thể kiểm soát được các hành động của chúng trước khi save( nhờ vào hàm beforeSave()) và sau khi save với hàm afterSave().
Để lấy một ví dụ đơn giản thì tôi sẽ làm một validate form chỉ cho phép nhập số dương tức là lớn hơn 0. Tất nhiên system.xml có hỗ trợ validate rồi, nhưng ở đây tôi muốn sử dụng backend model để các bạn có thể hiểu được cách mà nó hoạt động.
Tạo system.xml
ViMagento/HelloWorld/etc/adminhtml/system.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
... <group id="test_backend" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1"> <label>Backend model example</label> <field id="custom_backend_model" translate="label" type="text" sortOrder="1" showInDefault="1" showInWebsite="1" showInStore="1"> <label>Backend model example</label> <backend_model>ViMagento\HelloWorld\Model\Config\Backend\Validate</backend_model> </field> </group> .. |
Ở trên tôi đã sử dụng hàm beforeSave để validate input của tôi. và đây là kết quả:

Bây giờ hãy lấy một ví dụ về afterSave(). Tôi muốn khi save không cần biết người dùng nhập cái gì, tôi đều lưu giá trị ViMagento_HelloWorld vào cơ sở dữ liệu. Vẫn sử dụng class Validate ở trên và tôi sẽ thêm vào hàm afterSave như bên dưới:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
<?php namespace ViMagento\HelloWorld\Model\Config\Backend; class Validate extends \Magento\Framework\App\Config\Value { const CUSTOM_OPTION_STRING_PATH = 'setting/post/age'; protected $_configValueFactory; /** * @param \Magento\Framework\Model\Context $context * @param \Magento\Framework\Registry $registry * @param \Magento\Framework\App\Config\ScopeConfigInterface $config * @param \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList * @param \Magento\Framework\App\Config\ValueFactory $configValueFactory * @param \Magento\Framework\Model\ResourceModel\AbstractResource $resource * @param \Magento\Framework\Data\Collection\AbstractDb $resourceCollection * @param string $runModelPath * @param array $data */ public function __construct( \Magento\Framework\Model\Context $context, \Magento\Framework\Registry $registry, \Magento\Framework\App\Config\ScopeConfigInterface $config, \Magento\Framework\App\Cache\TypeListInterface $cacheTypeList, \Magento\Framework\App\Config\ValueFactory $configValueFactory, \Magento\Framework\Model\ResourceModel\AbstractResource $resource = null, \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null, array $data = [] ) { $this->_configValueFactory = $configValueFactory; parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data); } public function beforeSave() { $label = $this->getData('field_config/label'); if ($this->getValue() == '') { throw new \Magento\Framework\Exception\ValidatorException(__($label . ' is required.')); } else if (!is_numeric($this->getValue())) { throw new \Magento\Framework\Exception\ValidatorException(__($label . ' is not a number.')); } else if ($this->getValue() < 0) { throw new \Magento\Framework\Exception\ValidatorException(__($label . ' is less than 0.')); } $this->setValue(intval($this->getValue())); parent::beforeSave(); } public function afterSave() { $value = 'ViMagento HelloWorld'; try { $this->_configValueFactory->create()->load( self::CUSTOM_OPTION_STRING_PATH, 'path' )->setValue( $value )->setPath( self::CUSTOM_OPTION_STRING_PATH )->save(); } catch (\Exception $e) { throw new \Exception(__('We can\'t save new option.')); } return parent::afterSave(); } } |
Đây chỉ là ví dụ đơn giản để các bạn hiểu được backend model, chúng ta có thể thực hiện một số hành động trước và sau khi lưu với backend model. Và để kiểm tra ví dụ trên tôi sẽ nhập số 1 vào ô input và đây là kết quả.

Kết luận
Vậy là tôi đã hướng dẫn cho các bạn về backend model trong Magento 2. Hy vọng bài viết có thể giúp ích phần nào cho các bạn. Thanks.
Bài viết thiếu file system.xml. Kham khảo tại:
https://magently.com/blog/magento-2-backend-configuration-backend-model-part-23/