2016-07-06 28 views
0

如何刪除Magento 2.1中後臺和控制器中的產品屬性?removeAttribute magento 2

在Magento的1 *是:

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

編輯: 不要給我使用安裝/卸載方法。閱讀注意的問題: 「刪除屬性在backand控制器」

編輯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/'); 
    } 
} 
+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'); 
    } 
}