removeAttribute magento 2

时间:2016-07-06 13:27:56

标签: controller custom-attributes magento2

如何在Magento 2.1中删除后台和控制器中的产品属性?

在Magento 1. *它是:

$setup = Mage::getResourceModel('catalog/setup','catalog_setup');
$setup->removeAttribute('catalog_product','my_attribute');

修改 不要给我使用安装/卸载方法。阅读注意问题:"删除后台和控制器中的属性"

编辑2: 我找到答案

namespace Company\Module\Controller\Adminhtml\Shoptheme; //optional

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class Removeattribute extends \Magento\Backend\App\Action {
    private $dataSetup;
    private $eavSetupFactory;

    public function __construct(
        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\Setup\ModuleDataSetupInterface $dataSetup,
        \Magento\Eav\Setup\EavSetupFactory $eavSetupFactory
    ) {
        $this->dataSetup = $dataSetup;
        $this->eavSetupFactory = $eavSetupFactory;
        parent::__construct($context);
    }

    public function execute() {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $this->dataSetup]);
        $eavSetup->removeAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'prod_special_descr');

        $this->messageManager->addSuccess('attribute removed');
        $this->_redirect('admin/dashboard/');
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用以下设置脚本删除属性:

<?php

namespace Namespace\Company\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{
    private $eavSetupFactory;

    public function __construct(EavSetupFactory $eavSetupFactory)
    {
        $this->eavSetupFactory = $eavSetupFactory;
    }

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);
        $eavSetup->removeAttribute(
          \Magento\Catalog\Model\Product::ENTITY,
            'my_attribute');
    }
}