首页 > 解决方案 > Magento 2:在 \Magento\Contact\Controller\Index\Post 类上使用它时出现 ScopeConfig 错误

问题描述

首先,我正在扩展模块以联系我们,我想检查后端是否启用或未使用ScopeConfig,但我遇到了这个问题。我已经尝试删除生成的文件并运行 setup upgrade 命令。

根据我的假设,我认为我的代码缺少一些东西

代码:

<?php
namespace SCI\Form\Controller\Index;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;

class Post extends \Magento\Contact\Controller\Index\Post
{
    protected $scopeConfig;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        ScopeConfigInterface $scopeConfig,
        array $data = []
    ){
        parent::__construct($context,$data);
        $this->_scopeConfig = $scopeConfig;
        $this->_storeManager = $storeManager;

    }

    public function ifEnabled(){
        return $this->_scopeConfig->getValue('extended_contact/config/extended_contact_enabled',ScopeInterface::SCOPE_STORE);
    }

    public function execute()
    {
        die($this->ifEnabled());

        return parent::execute();

    }
}

注意:当我将类表单 \Magento\Contact\Controller\Index\Post 更改为 \Magento\Framework\App\Action\Action 时,它的工作原理

错误:

致命错误:未捕获的 TypeError:参数 2 传递给 Magento\Contact\Controller\Index\Post::__construct() 必须实现接口 Magento\Contact\Model\ConfigInterface,给定数组,在 C:\xampp\htdocs\training\app 中调用\code\SCI\Form\Controller\Index\Post.php 在第 17 行并在 C:\xampp\htdocs\training\vendor\magento\module-contact\Controller\Index\Post.php:49 中定义堆栈跟踪:# 0 C:\xampp\htdocs\training\app\code\SCI\Form\Controller\Index\Post.php(17): Magento\Contact\Controller\Index\Post->__construct(Object(Magento\Framework\App\ Action\Context), Array) #1 C:\xampp\htdocs\training\generated\code\SCI\Form\Controller\Index\Post\Interceptor.php(14): SCI\Form\Controller\Index\Post-> __construct(对象(Magento\Framework\App\Action\Context),对象(Magento\Store\Model\StoreManager),对象(Magento\Framework\App\Config),数组)#2 C:\xampp\htdocs\training\vendor\magento\framework\ObjectManager\Factory\AbstractFactory.php(111): SCI\Form\Controller\Index\Post \Interceptor->__construct(Object(Magento\Framework\App\Action\Conte in C:\xampp\htdocs\training\vendor\magento\module-contact\Controller\Index\Post.php 第 49 行

标签: phpmagento2

解决方案


您可以尝试将您的功能更改为以下代码以修复错误。

public function ifEnabled(){
    $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;

    return $this->_scopeConfig->getValue(
        'extended_contact/config/extended_contact_enabled',
        $storeScope
    );
}

推荐阅读