系统学习magento二次开发,推荐小册:《Magento中文全栈二次开发 》
本小册面向Magento2以上版本,书代码及示例兼容magento2.0-2.4版本。涵盖了magento前端开发,后端开发,magento2主题,magento2重写,magento2 layout,magento2控制器,magento2 block等相关内容,带领您成为magento开发技术专家。
在Magento 2中添加自定义字段并在产品属性中添加表单中添加值的步骤:
第1步: 首先我们需要在 etc文件夹中创建一个“di.xml”文件
app\code\Vendor\Extension\etc\adminhtml
现在,添加代码,如下所示
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\Catalog\Block\Adminhtml\Product\Attribute\Edit\Tab\Front"> <plugin name="extension_attribute_edit_form" type="Vendor\Extension\Plugin\Block\Adminhtml\Product\Attribute\Edit\Tab\Front" sortOrder="1"/> </type> </config>
步骤2: 在下一步中,我们将在 插件文件夹中创建“Front.php”文件
app\code\Vendor\Extension\Plugin\Block\Adminhtml\Product\Attribute\Edit\Tab
然后附加下面提到的代码片段
<?php
namespace Vendor\Extension\Plugin\Block\Adminhtml\Product\Attribute\Edit\Tab;
class Front
{
protected $custom;
public function __construct(
\Magento\Config\Model\Config\Source\Yesno $custom
) {
$this->custom = $custom;
}
public function aroundGetFormHtml(
\Magento\Catalog\Block\Adminhtml\Product\Attribute\Edit\Tab\Front $subject,
\Closure $proceed
)
{
$customSource = $this->custom->toOptionArray();
$form = $subject->getForm();
$fieldset = $form->getElement('front_fieldset');
$fieldset->addField(
'used_in_custom',
'select',
[
'name' => 'used_in_custom',
'label' => __('Used in Custom'),
'title' => __('Used in Custom'),
'values' => $customSource,
]
);
return $proceed();
}
}步骤3:然后我们将 在etc文件夹中创建“db_schema.xml”文件
app\code\Vendor\Extension\etc
最后,添加以下代码
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd"> <table name="catalog_eav_attribute" resource="default" engine="innodb" comment="Catalog EAV Attribute Table"> <column xsi:type="smallint" name="used_in_custom" unsigned="true" nullable="false" identity="false" default="0" comment="Custom forms"/> </table> </schema>
输出:

自定义产品字段
结论:
这样,您可以在Magento 2中添加自定义字段并在产品属性中添加表单中保存值。