1

I want to get a plain value from custom variable (defined on admin) in php with objectManager.

storeID is in $order->getStore()->getId()

Custom Variable Code is 'mycustomvar'

why does following code not work?

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $variables = $objectManager->create('Magento\Variable\Model\Variable');
    if ($var = $variables->getResource()->getVariableByCode('mycustomvar', true, $order->getStore()->getId())) {
        $value = 'defined';
//      $value = $variables->getData('plain_value');
    } else {
        $value = 'undefined';
    }

It looks like $var contains the array with the values of mycustomvar, but I'm not sure.

How can I pass $var to getData('plain_value')? Or is there a better way to get 'plain_value'?

Classes I was looking into are

Magento\Variable\Model\Variable

Magento\Variable\Model\ResourceModel\Variable

PS I understood objectManager is not the preferred way, but I need to get this working here

PPS Magento 2.1

  • 1
    You can use $model = $objectManager->get('Magento\Variable\Model\Variable')->loadByCode('myVariable'); $plain_value = $model->getPlainValue(); $html_value = $model->getHtmlValue(); But this method is not recommend by Magento to create instance. – Vikas Verma Jul 20 '17 at 10:52
  • 1
    @Vikas Sorry, I don't understand - how would I set the storeID then? – rico Jul 20 '17 at 11:18
  • This will automatically provide you the current store value. Did you use it ? – Vikas Verma Jul 20 '17 at 11:31
  • No - I need to get different values of this custom variable depending on which store the document was created.This is part of a modificaton of function insertOrder in Magento\Sales\Model\Order\Pdf\Abstractpdf.php and I checked the storeId is in $order->getStore()->getId(), for example storeId = 3. – rico Jul 20 '17 at 11:59
0

Class Magento\Variable\Model\Variable offers everything - such as setStoreId(StoreId), which needs to be set case by case for my application. There is no need to dig into Magento\Variable\Model\ResourceModel\Variable.

The following code is working now. Replace myStoreID and mycustomvar with your needs. Remove code line with setStoreId(StoreId), if you need access to mycustomvar in the current store.

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $variables = $objectManager->create('Magento\Variable\Model\Variable');
    $variables->setStoreId(myStoreID);

    $value = $variables->loadByCode('mycustomvar')->getPlainValue();

Thanks to Vikas comments, it helped me find the solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.