1

The scenario is I have multiple if-conditions to create product programmatically or load at controller action. I need a single variable who's value should be updating through different functions.

I have tried custom php ways but are not working. How can I achieve this?

Edit

Here is my class, I want to create product one(first) time and after that each time same product should gets load so that it could be added to cart programmatically. I am loading product using SKU. To read code please focus on $sku variable which I want to make global or static.

class Index extends \Magento\Framework\App\Action\Action
{
protected $resultPageFactory;
protected $session;
protected $sku;
private $productRepository;
public function __construct(
    FormKey $formKey,
    Cart $cart,
    Product $product,
    \Magento\Framework\App\Action\Context $context,
    \Magento\Customer\Model\Session $customerSession,
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
    PageFactory $resultPageFactory
)
{
    $this->session = $customerSession;
    $this->formKey = $formKey;
    $this->sku = $sku;
    $this->cart = $cart;
    $this->productRepository = $productRepository;
    $this->product = $product; 
    parent::__construct($context);
    $this->resultPageFactory = $resultPageFactory;
}
public function execute()
{
    if (!$this->session->isLoggedIn())
    {
        $resultRedirect = $this->resultRedirectFactory->create();
        $resultRedirect->setPath('customer/account/login');
        return $resultRedirect;
    }
    else
    {
        $resultPage = $this->resultPageFactory->create();
        $resultPage->getConfig()->getTitle()->set(__('My Wallet'));


        $vat_exempt_name = $this->getRequest()->getPost('vat_exempt_name');
         //...........Load Product...............//
        $product= $this->loadMyProduct();
        $ID = $product->getId();

    //.............. For Add to Cart .........//
    $productId =$ID;
    $params = array(
                'form_key' => $this->formKey->getFormKey(),
                'product' => $productId, 
                'qty'   =>1
            );
        $product = $this->product->load($productId);       
        $this->cart->addProduct($product, $params);
        $this->cart->save();
        return $resultPage;
    }
} 
    public function loadMyProduct()
    {   
        if (empty($this->sku)){
        $this->createProduct();
        }
        else{
        return $this->productRepository->get($this->sku);
        }
    }
    public function createProduct(){
        $posted = $this->getRequest()->getParam('vat_exempt_name');
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // instance of object manager
        $product = $objectManager->create('\Magento\Catalog\Model\Product');
        $product->setSku('my-sku44'); // I need this SKU to be set for global variable $sku
        $product->setName('Wallet Amount'); // Name of Product
        $product->setAttributeSetId(4); // Attribute set id
        $product->setStatus(1); // Status on product enabled/ disabled 1/0
        $product->setWebsiteIds(array(1));
        $product->setWeight(10); // weight of product
        $product->setVisibility(4); // visibilty of product (catalog / search / catalog, search / Not visible individually)
        $product->setTaxClassId(0); // Tax class id
        $product->setTypeId('simple'); // type of product (simple/virtual/downloadable/configurable)
        $product->setPrice(199); // price of product
        $product->setStockData(
                 array(
                      'use_config_manage_stock' => 0,
                      'manage_stock' => 1,
                      'is_in_stock' => 1,
                      'qty' => 99999
                      )
                     );
        $product = $product->save();
        $ID = $product->getId();
        //global $sku;
        $this->sku = $product->getSku(); // here global variable $sku should update
    }

}

Thanks.

2
  • add the code you tried much better
    – fmsthird
    May 29, 2019 at 11:09
  • @magefms I have updated question.
    – Ajwad Syed
    May 29, 2019 at 11:37

2 Answers 2

0

I think I'm more going to answer a "php question" than a "magento question" here.

I would have use

$this->sku

and declare it with the others (protected $resultPageFactory;protected $session;private $productRepository;)

Its value will be updated in the object rather than in the method.

I Hope I'm clear enough ;)

If not, there is the documentation. https://www.php.net/manual/fr/language.oop5.properties.php

4
  • Hi, I have updated code as you suggested see code in question, this is how updated..but it is throwing exception: Exception #0 (Exception): Notice: Undefined variable: sku
    – Ajwad Syed
    May 30, 2019 at 6:58
  • You might need to declare it in your construcor or the first time you call it. Show me your new version of the code ?
    – Mric
    May 30, 2019 at 12:26
  • how can we declare it in constructor ?
    – Ajwad Syed
    May 30, 2019 at 12:41
  • $this->sku = ''; (in the constructor). I'm not sure it's the best way, but at least it works
    – Mric
    May 30, 2019 at 14:08
0

I solved problem using core session to store value and access globally, here is example to understand concept:

use Magento\Framework\Session\SessionManagerInterface as CoreSession;

class MyClass
{

protected $_coreSession;

public function __construct(
    ...
    CoreSession $coreSession
    ...
) {
    $this->_coreSession = $coreSession;
}

public function setValue(){
    $this->_coreSession->start();
    $this->_coreSession->setMyVariable('My variable value');
}
}

Get your variable value anywhere by core session as:

public function getValue(){
    $this->_coreSession->start();
    return $this->_coreSession->getMyVariable();
}

We can also unset session variable by

public function unsetValue(){
    $this->_coreSession->start();
    return $this->_coreSession->unsMyVariable();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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