Magento 2还附带了Magento 1中的自定义变量。之前以编程方式在Magento 1中设置自定义变量的做法类似于以下内容:
$variable = Mage::getModel('core/variable')
->setCode('variable-code')
->setName('Variable Name')
->setPlainValue(0)
->save();
对于Magento 2,在我目前的场景中,我想在InstallData.php脚本中以编程方式创建自定义变量,而不是网站后端。我只能通过网站后端找到,但由于版本控制优势,我总是更喜欢以编程方式。
答案 0 :(得分:2)
解决。像下面这样的东西按预期工作
...
use Magento\Variable\Model\VariableFactory;
class InstallData implements InstallDataInterface
{
protected $varFActory;
public function __construct(VariableFactory $varFactory)
{
$this->varFActory = $varFactory;
}
/**
* {@inheritdoc}
*/
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
) {
$variable = $this->varFActory->create();
$data = [
'code' => '',
'name' => '',
'html_value' => '',
'plain_value' => '',
];
$variable->setData($data);
$variable->save();
}
}
答案 1 :(得分:0)
要更新现有变量,您可以通过以下方式完成
:$var = $this->varFactory->create();
$var->loadByCode('YOUR_CUSTOM_VARIABLE_CODE');
$data = [
'variable_id' => $var->getId(),
'code' => 'YOUR_CUSTOM_VARIABLE_CODE',
'name' => 'YOUR_CUSTOM_VARIABLE_NAME',
'html_value' => 'YOUR_CUSTOM_VALUE_IN_HTML',
'plain_value' => 'YOUR_CUSTOM_VALUE_IN_PLAINTEXT'
];
$var->setData($data);
$var->save();
答案 2 :(得分:0)
至少在 2.3.4 中,您可以通过 XML 定义自定义的新变量
对于我的用例,我在系统配置中创建了一个自定义字段,并允许它是一个变量,如下所示:
etc/adminhtml/system.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
<system>
<section id="general">
<group id="store_information">
<field id="name_alt" translate="label" type="text" sortOrder="11" showInDefault="1" showInWebsite="1" showInStore="1">
<label>Store Name Alt</label>
</field>
</group>
</section>
</system>
</config>
etc/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\Variable\Model\Source\Variables">
<arguments>
<argument name="configPaths" xsi:type="array">
<item name="general/store_information" xsi:type="array">
<item name="general/store_information/name_alt" xsi:type="string">1</item>
</item>
</argument>
</arguments>
</type>
</config>