1

The scenario is I want to set my variable to a global variable from a phtml file and call in a module file or block file.

So what would be some code or tutorial link that I set my variable to global and call in a module or class file?

1

Create your custom variable using System -> Custom Variables .Using this you can add your global variable and use is anywhere in magento.

1

You can use the code as below for setting up the session below code explains how to set a session in the customer session.

protected $customerSession;
public function __construct(
    ...
    \Magento\Customer\Model\Session $customerSession, 
    ...
){
    ...
    $this->customerSession = $customerSession;
    ...
}

// later in your class you can use it as below

$this->customerSession->myName('anyname');

Few other sessions in Magento 2:

  • \Magento\Backend\Model\Session
  • \Magento\Catalog\Model\Session
  • \Magento\Checkout\Model\Session
  • \Magento\Customer\Model\Session
  • \Magento\Newsletter\Model\Session

Links to tutorials:

https://www.mageplaza.com/how-set-unset-session-magento-2.html http://blog.chapagain.com.np/magento-2-set-unset-get-session/

0

To set and get global variable in Magento 2 to follow below steps

1) create the variable in admin side go to System -> Other Settings -> Custom Variables

2) add Variable Code, Variable Name, Variable HTML Value(if you want any html value into phtml file) and Variable Plain Value(if you want any plain value into phtml file)

3) get created variable value into phtml file or anywhere in your code

protected $objectManager;

public function __construct(
        \Magento\Framework\ObjectManagerInterface $objectManager
){
        $this->_objectManager = $objectManager;
}

public function execute()
{
   $model = $this->_objectManager->get('Magento\Variable\Model\Variable')->loadByCode('test_var');//your Variable Code
   $plain_value = $model->getPlainValue();
   $html_value = $model->getHtmlValue();
   $name = $model->getName();
}

you can also set like a session variable and this one

  • how can i pass my own variable in it for example i save calue in variable and i want to pass that value on variable – jhon jhon doe Oct 5 '18 at 6:25
  • in your case, you should use session variable try this link as already mentioned in above answer – Hitesh Oct 5 '18 at 6:27
  • yeah i use this links pls can you helo me that how can i echo that value in get message ? – jhon jhon doe Oct 5 '18 at 6:29
  • check here this is nice answer magento.stackexchange.com/a/209343 just replace setMessage or getMessage with your variable like setCalue and getCalue – Hitesh Oct 5 '18 at 6:34

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.