Magento 2 also comes with Custom Variables like in Magento 1. Previously to set a custom variable in Magento 1 programmatically was doing something similar to the following:
$variable = Mage::getModel('core/variable')
->setCode('variable-code')
->setName('Variable Name')
->setPlainValue(0)
->save();
For Magento 2, in my current scenario I would like to create custom variables programmatically in the InstallData.php script instead of website backend. I only find via website backend, but I always prefer programmatically due to versioning advantages.
Solved. Something like the following works as expected
...
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With