Magento – How to use a backend_model for the field in system.xml in Magento 2

backendmagento-2.0magento2system.xml

I had setup this system.xml file

...
    <section id="account_info" translate="label" showInDefault="1" showInWebsite="1" showInStore="1">
                <label>Account configuration</label>
                <tab>account_info_tab</tab>
                <resource>myvendor_mymodule::config</resource>
                <group id="account_configuration" showInDefault="1" showInWebsite="1" showInStore="1">
                    <label>Account login</label>
                    <field id="title" translate="label comment" type="text" showInDefault="1" showInWebsite="1" showInStore="1">
                        <label>Token API</label>
                        <backend_model>Myvendor\Mymodule\Model\Config\TokenAPI</backend_model>
                        <validate>required-entry</validate>
                    </field>
                </group>
            </section>
...

I want to use a custom backend_model because i want to verify the data before saving it (have to use web services).

Then i have my TokenAPI backend_model

class TokenAPI extends \Magento\Framework\App\Config\Value{
    function __construct(\Magento\Framework\Exception\LocalizedException $e){
        $this->localizedException = $e;
    }

    public function beforeSave(){
        echo '<pre>';
            print_r($this->getValue());
        echo '</pre>';


        exit;
    }
} 

The problem that im having is that as soon i uncomment the backend_model in system.xml the field stops working throwing this error

[2016-05-03 13:28:23] main.CRITICAL: Missing required argument $text of Magento\Framework\Phrase. [] []

Best Answer

The problem is that your backend model constructor does not match the parent class constructor \Magento\Framework\App\Config\Value

You need to update your constructor like this:

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\Model\ResourceModel\AbstractResource $resource = null,
    \Magento\Framework\Data\Collection\AbstractDb $resourceCollection = null,
    \Magento\Framework\Exception\LocalizedException $e,
    array $data = []
) {
    $this->localizedException = $e;
    parent::__construct($context, $registry, $config, $cacheTypeList, $resource, $resourceCollection, $data);
}