Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

magento2 create custom variables programmatically

Tags:

php

magento2

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.

like image 386
jj-aa Avatar asked May 16 '26 22:05

jj-aa


1 Answers

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();          
    }
}
like image 87
jj-aa Avatar answered May 18 '26 11:05

jj-aa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!