I am adding a custom field to product attributes with a plugin providing the adminhtml display.
I have it visible in Store -> Attributes -> Product -> Edit attribute and it works okay to save, but when editing a product attribute the stored value is not loaded. The value is initially correctly stored in the database, subsequent visits to edit do not load the saved value from the database.
How can I have this yesno successfully pull the stored value when an admin is editing the attribute? I'm not sure why the value isn't being pulled with the current one being selected. This is Magento 2.2.7
CompanyName\ModuleName\Setup\UpgradeSchema.php
<?php
namespace CompanyName\ModuleName\Setup;
use Magento\Framework\Setup\UpgradeSchemaInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\SchemaSetupInterface;
class UpgradeSchema implements UpgradeSchemaInterface{
public function upgrade(SchemaSetupInterface $setup, ModuleContextInterface $context){
if (version_compare($context->getVersion(), '1.0.1') < 0) {
$setup->startSetup();
$setup->getConnection()->addColumn(
$setup->getTable('catalog_eav_attribute'),
'my_custom_field',
['type' => \Magento\Framework\DB\Ddl\Table::TYPE_SMALLINT,
'length' => '1',
'nullable' => false,
'unsigned' => true,
'default' => '0',
'comment' => 'This is a custom field']);
$setup->endSetup();
} } }
CompanyName\ModuleName\Plugin\Block\Adminhtml\Product\Attribute\Edit\Tab\Front.php
<?php
namespace CompanyName\ModuleName\Plugin\Block\Adminhtml\Product\Attribute\Edit\Tab;
class Front
{
/**
* @var Yesno
*/
protected $_yesNo;
/**
* @param Magento\Config\Model\Config\Source\Yesno $yesNo
*/
public function __construct(
\Magento\Config\Model\Config\Source\Yesno $yesNo
) {
$this->_yesNo = $yesNo;
}
/**
* Get form HTML
*
* @return string
*/
public function aroundGetFormHtml(
\Magento\Catalog\Block\Adminhtml\Product\Attribute\Edit\Tab\Front $subject,
\Closure $proceed
)
{
$yesnoSource = $this->_yesNo->toOptionArray();
$form = $subject->getForm();
$fieldset = $form->getElement('front_fieldset');
$fieldset->addField(
'my_custom_field',
'select',
[
'name' => 'my_custom_field',
'label' => __('Label for my custom field'),
'title' => __('Title for my custom field'),
'note' => __('Note for my custom field.'),
'values' => $yesnoSource,
]
);
return $proceed();
}
}
CompanyName/ModuleName/etc/adminhtml/di.xml
<?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="companyname_attribute_edit_form" type="CompanyName\ModuleName\Plugin\Block\Adminhtml\Product\Attribute\Edit\Tab\Front" sortOrder="1"/>
</type>
</config>
