Magento2:向产品编辑表单添加自定义下拉列表

时间:2016-12-21 10:29:01

标签: php magento2

我想在magento2中的产品编辑表单中添加一个新的下拉列表。数据应来自我在自定义模块中创建的自定义表。我该怎么做,那里有一个很好的例子或教程吗?

我试图像这样创建一个观察者:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
  <event name="adminhtml_catalog_product_attribute_edit_prepare_form">
    <observer name="custom_product_fields" instance="Vendorname\Custom\Observer\CatalogProductEditPrepareForm"/>
    <!-- CatalogProductEditPrepareForm is name of class in which we'll add custom fields in form-->
  </event>
</config>

观察者看起来像这样:

class CatalogProductEditPrepareForm implements ObserverInterface
{
  protected $_coreRegistry;

  public function __construct(\Magento\Framework\Registry  $coreRegistry) {
    $this->_coreRegistry = $coreRegistry;
  }

  public function execute(\Magento\Framework\Event\Observer $observer){
    echo "why is this not called?!";
  }
  ...
}

谢谢!

1 个答案:

答案 0 :(得分:0)

您在自定义扩展程序中使用InstallData.php文件创建属性, 代码在这里。

<?php
namespace Vendor\Extension\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;
use Magento\Framework\Module\Setup\Migration;

class InstallData implements InstallDataInterface
{
    private $eavSetupFactory;


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

    public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
    {
        $setup->startSetup();
        $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

        // Product Attribute
        $eavSetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'attribute_id',
            [
                'type' => 'varchar',
                'label' => 'Attribute Label',
                'backend' => 'Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend',
                'input' => 'select',
                'source' => 'Vendor\Extension\Model\Source\Mysource',
                'required' => false,
                'sort_order' => 6,
                'global' => \Magento\Catalog\Model\ResourceModel\Eav\Attribute::SCOPE_STORE,
                'searchable'        => false,
                'filterable'        => false
            ]
        );
        $setup->endSetup();
    }
}

以上代码创建产品属性,您需要在此处创建自定义源文件

Vendor\Extension\Model\Source\Mysource.php

<?php
namespace Vendor\Extension\Model\Source;

use Magento\Eav\Model\Entity\Attribute\Source\AbstractSource;

class Mysource extends AbstractSource
{
     public function getOptionArray()
    {
        return [
            ['value' => 1, 'label'=>__('Label-1')],
            ['value' => 2, 'label'=>__('Label-2')],
        ];
    }
}