Get product custom attribute in observer that listens to x specific eventcustomer_save_after and customer_register_success event in custom observer customer session is blank in mycustom fuction?Set custom price of product when adding to cart code not workingMagento 2: How to override newsletter Subscriber modelMagento 2: Add a product to the cart programmaticallyMagento 2: After custom cookie is created all pages default to home pageHow to solve Front controller reached 100 router match iterations in magento2I have created one field using product form field for my price i want save my field value at product creation time from backend magento2Magento 2.2.5: Add, Update and Delete existing products Custom Optionsmagento 2.2 trying to save multi select value in databaseHow to update product's attribute value in Magento 2?

The seven story archetypes. Are they truly all of them?

Character Arcs - What if the character doesn't overcome the big lie, flaws or wounds?

How can I indicate that what I'm saying is not sarcastic online?

How to run a substitute command on only a certain part of the line

What is the best word describing the nature of expiring in a short amount of time, connoting "losing public attention"?

What was the rationale behind 36 bit computer architectures?

Adding one more column to a table

Can't understand how static works exactly

Company requiring me to let them review research from before I was hired

Are there any English words pronounced with sounds/syllables that aren't part of the spelling?

Can I pay with HKD in Macau or Shenzhen?

What kind of anatomy does a centaur have?

Adding gears to my grandson's 12" bike

Other than a swing wing, what types of variable geometry have flown?

Was US film used in Luna 3?

If I have the Armor of Shadows Eldritch Invocation, do I know the Mage Armor spell?

Is it better to merge "often" or only after completion do a big merge of feature branches?

Bounded Torsion, without Mazur’s Theorem

Is it OK to accept a job opportunity while planning on not taking it?

How can I print a 1 cm overhang with minimal supports?

Are rockets faster than airplanes?

Why can't a country print its own money to spend it only abroad?

Does switching on an old games console without a cartridge damage it?

Correct use of smash with math and root signs



Get product custom attribute in observer that listens to x specific event


customer_save_after and customer_register_success event in custom observer customer session is blank in mycustom fuction?Set custom price of product when adding to cart code not workingMagento 2: How to override newsletter Subscriber modelMagento 2: Add a product to the cart programmaticallyMagento 2: After custom cookie is created all pages default to home pageHow to solve Front controller reached 100 router match iterations in magento2I have created one field using product form field for my price i want save my field value at product creation time from backend magento2Magento 2.2.5: Add, Update and Delete existing products Custom Optionsmagento 2.2 trying to save multi select value in databaseHow to update product's attribute value in Magento 2?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0















Anyone know how to get product custom attribute in observer? In my case event is controller_action_predispatch_checkout_cart_add.



My current code is giving me:




Uncaught Error: Call to a member function getProduct() on null in




 $product = $this->productRepository->getById($observer->getItem()->getProduct()->getId());
$attr = $product->getData('product_customattribute');


Also I tried this (same error):



 $product = $observer->getEvent()->getProduct();
$attr = $product->getProduct()->getAttributeText('product_customattribute');


UPDATE



My module redirect after click add to cart (with adding to the cart)



<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_predispatch_checkout_cart_add">
<observer name="myvendor_mymodule_observer_redirect" instance="MyVendorMyModuleObserverRedirect" />
</event>
</config>


and my Observer



<?php
namespace MyVendorMyModuleObserver;

use MagentoFrameworkEventObserver;
use MagentoFrameworkEventObserverInterface;
//use MagentoStoreModelStoreManager;
//use MagentoFrameworkAppObjectManager;

class Redirect implements MagentoFrameworkEventObserverInterface

/**
* @var MagentoFrameworkAppActionFlag
*/
protected $actionFlag;

/**
* @var MagentoFrameworkAppResponseRedirectInterface
*/
protected $redirect;
protected $resultRedirect;

public function __construct(
// MagentoFrameworkAppActionFlag $actionFlag,
MagentoFrameworkAppResponseRedirectInterface $redirect,
// StoreManager $storeManager,
MagentoFrameworkControllerResultFactory $result,
MagentoFrameworkAppActionFlag $actionFlag
)

$this->redirect = $redirect;
// $this->actionFlag = $actionFlag;
$this->resultRedirect = $result;
$this->_actionFlag = $actionFlag;
// $this->storeManager = $storeManager;

public function execute(MagentoFrameworkEventObserver $observer)
$controller = $observer->getControllerAction();
$this->_actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
$url = 'https://domain.com/url.html';
$controller->getResponse()->setRedirect($url);




I want change $url with custom attribute.

I was able to get product data using catalog_product_save_after but redirect wasn't working. Maybe I could connect somehow this two observers.



UPDATE 2



On this event I get custom attribute




checkout_cart_add_product_complete




 public function execute(MagentoFrameworkEventObserver $observer) 
$product = $observer->getProduct();
$customAttribute = $product->getCustomAttribute('custom_attribute');
$this->_logger->log(100,print_r( $customAttribute, true));



On this I get redirect after add to cart




controller_action_predispatch_checkout_cart_add




 public function execute(MagentoFrameworkEventObserver $observer) 
$controller = $observer->getControllerAction();
$this->_actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
$url = '/cart'; //should be custom_attribute

$controller->getResponse()->setRedirect($url);



But I can get this values in one observer. I tried to connect them but not sure what should I use? Cache? register? to pass data from one observer to another.










share|improve this question
























  • Which event you have tried to observe?

    – Sohel Rana
    Jul 14 at 15:33











  • I use controller_action_predispatch_checkout_cart_add

    – BartZalas
    Jul 14 at 21:05

















0















Anyone know how to get product custom attribute in observer? In my case event is controller_action_predispatch_checkout_cart_add.



My current code is giving me:




Uncaught Error: Call to a member function getProduct() on null in




 $product = $this->productRepository->getById($observer->getItem()->getProduct()->getId());
$attr = $product->getData('product_customattribute');


Also I tried this (same error):



 $product = $observer->getEvent()->getProduct();
$attr = $product->getProduct()->getAttributeText('product_customattribute');


UPDATE



My module redirect after click add to cart (with adding to the cart)



<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_predispatch_checkout_cart_add">
<observer name="myvendor_mymodule_observer_redirect" instance="MyVendorMyModuleObserverRedirect" />
</event>
</config>


and my Observer



<?php
namespace MyVendorMyModuleObserver;

use MagentoFrameworkEventObserver;
use MagentoFrameworkEventObserverInterface;
//use MagentoStoreModelStoreManager;
//use MagentoFrameworkAppObjectManager;

class Redirect implements MagentoFrameworkEventObserverInterface

/**
* @var MagentoFrameworkAppActionFlag
*/
protected $actionFlag;

/**
* @var MagentoFrameworkAppResponseRedirectInterface
*/
protected $redirect;
protected $resultRedirect;

public function __construct(
// MagentoFrameworkAppActionFlag $actionFlag,
MagentoFrameworkAppResponseRedirectInterface $redirect,
// StoreManager $storeManager,
MagentoFrameworkControllerResultFactory $result,
MagentoFrameworkAppActionFlag $actionFlag
)

$this->redirect = $redirect;
// $this->actionFlag = $actionFlag;
$this->resultRedirect = $result;
$this->_actionFlag = $actionFlag;
// $this->storeManager = $storeManager;

public function execute(MagentoFrameworkEventObserver $observer)
$controller = $observer->getControllerAction();
$this->_actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
$url = 'https://domain.com/url.html';
$controller->getResponse()->setRedirect($url);




I want change $url with custom attribute.

I was able to get product data using catalog_product_save_after but redirect wasn't working. Maybe I could connect somehow this two observers.



UPDATE 2



On this event I get custom attribute




checkout_cart_add_product_complete




 public function execute(MagentoFrameworkEventObserver $observer) 
$product = $observer->getProduct();
$customAttribute = $product->getCustomAttribute('custom_attribute');
$this->_logger->log(100,print_r( $customAttribute, true));



On this I get redirect after add to cart




controller_action_predispatch_checkout_cart_add




 public function execute(MagentoFrameworkEventObserver $observer) 
$controller = $observer->getControllerAction();
$this->_actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
$url = '/cart'; //should be custom_attribute

$controller->getResponse()->setRedirect($url);



But I can get this values in one observer. I tried to connect them but not sure what should I use? Cache? register? to pass data from one observer to another.










share|improve this question
























  • Which event you have tried to observe?

    – Sohel Rana
    Jul 14 at 15:33











  • I use controller_action_predispatch_checkout_cart_add

    – BartZalas
    Jul 14 at 21:05













0












0








0








Anyone know how to get product custom attribute in observer? In my case event is controller_action_predispatch_checkout_cart_add.



My current code is giving me:




Uncaught Error: Call to a member function getProduct() on null in




 $product = $this->productRepository->getById($observer->getItem()->getProduct()->getId());
$attr = $product->getData('product_customattribute');


Also I tried this (same error):



 $product = $observer->getEvent()->getProduct();
$attr = $product->getProduct()->getAttributeText('product_customattribute');


UPDATE



My module redirect after click add to cart (with adding to the cart)



<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_predispatch_checkout_cart_add">
<observer name="myvendor_mymodule_observer_redirect" instance="MyVendorMyModuleObserverRedirect" />
</event>
</config>


and my Observer



<?php
namespace MyVendorMyModuleObserver;

use MagentoFrameworkEventObserver;
use MagentoFrameworkEventObserverInterface;
//use MagentoStoreModelStoreManager;
//use MagentoFrameworkAppObjectManager;

class Redirect implements MagentoFrameworkEventObserverInterface

/**
* @var MagentoFrameworkAppActionFlag
*/
protected $actionFlag;

/**
* @var MagentoFrameworkAppResponseRedirectInterface
*/
protected $redirect;
protected $resultRedirect;

public function __construct(
// MagentoFrameworkAppActionFlag $actionFlag,
MagentoFrameworkAppResponseRedirectInterface $redirect,
// StoreManager $storeManager,
MagentoFrameworkControllerResultFactory $result,
MagentoFrameworkAppActionFlag $actionFlag
)

$this->redirect = $redirect;
// $this->actionFlag = $actionFlag;
$this->resultRedirect = $result;
$this->_actionFlag = $actionFlag;
// $this->storeManager = $storeManager;

public function execute(MagentoFrameworkEventObserver $observer)
$controller = $observer->getControllerAction();
$this->_actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
$url = 'https://domain.com/url.html';
$controller->getResponse()->setRedirect($url);




I want change $url with custom attribute.

I was able to get product data using catalog_product_save_after but redirect wasn't working. Maybe I could connect somehow this two observers.



UPDATE 2



On this event I get custom attribute




checkout_cart_add_product_complete




 public function execute(MagentoFrameworkEventObserver $observer) 
$product = $observer->getProduct();
$customAttribute = $product->getCustomAttribute('custom_attribute');
$this->_logger->log(100,print_r( $customAttribute, true));



On this I get redirect after add to cart




controller_action_predispatch_checkout_cart_add




 public function execute(MagentoFrameworkEventObserver $observer) 
$controller = $observer->getControllerAction();
$this->_actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
$url = '/cart'; //should be custom_attribute

$controller->getResponse()->setRedirect($url);



But I can get this values in one observer. I tried to connect them but not sure what should I use? Cache? register? to pass data from one observer to another.










share|improve this question
















Anyone know how to get product custom attribute in observer? In my case event is controller_action_predispatch_checkout_cart_add.



My current code is giving me:




Uncaught Error: Call to a member function getProduct() on null in




 $product = $this->productRepository->getById($observer->getItem()->getProduct()->getId());
$attr = $product->getData('product_customattribute');


Also I tried this (same error):



 $product = $observer->getEvent()->getProduct();
$attr = $product->getProduct()->getAttributeText('product_customattribute');


UPDATE



My module redirect after click add to cart (with adding to the cart)



<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="controller_action_predispatch_checkout_cart_add">
<observer name="myvendor_mymodule_observer_redirect" instance="MyVendorMyModuleObserverRedirect" />
</event>
</config>


and my Observer



<?php
namespace MyVendorMyModuleObserver;

use MagentoFrameworkEventObserver;
use MagentoFrameworkEventObserverInterface;
//use MagentoStoreModelStoreManager;
//use MagentoFrameworkAppObjectManager;

class Redirect implements MagentoFrameworkEventObserverInterface

/**
* @var MagentoFrameworkAppActionFlag
*/
protected $actionFlag;

/**
* @var MagentoFrameworkAppResponseRedirectInterface
*/
protected $redirect;
protected $resultRedirect;

public function __construct(
// MagentoFrameworkAppActionFlag $actionFlag,
MagentoFrameworkAppResponseRedirectInterface $redirect,
// StoreManager $storeManager,
MagentoFrameworkControllerResultFactory $result,
MagentoFrameworkAppActionFlag $actionFlag
)

$this->redirect = $redirect;
// $this->actionFlag = $actionFlag;
$this->resultRedirect = $result;
$this->_actionFlag = $actionFlag;
// $this->storeManager = $storeManager;

public function execute(MagentoFrameworkEventObserver $observer)
$controller = $observer->getControllerAction();
$this->_actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
$url = 'https://domain.com/url.html';
$controller->getResponse()->setRedirect($url);




I want change $url with custom attribute.

I was able to get product data using catalog_product_save_after but redirect wasn't working. Maybe I could connect somehow this two observers.



UPDATE 2



On this event I get custom attribute




checkout_cart_add_product_complete




 public function execute(MagentoFrameworkEventObserver $observer) 
$product = $observer->getProduct();
$customAttribute = $product->getCustomAttribute('custom_attribute');
$this->_logger->log(100,print_r( $customAttribute, true));



On this I get redirect after add to cart




controller_action_predispatch_checkout_cart_add




 public function execute(MagentoFrameworkEventObserver $observer) 
$controller = $observer->getControllerAction();
$this->_actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
$url = '/cart'; //should be custom_attribute

$controller->getResponse()->setRedirect($url);



But I can get this values in one observer. I tried to connect them but not sure what should I use? Cache? register? to pass data from one observer to another.







magento2 event-observer custom-attributes






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 2 days ago







BartZalas

















asked Jul 14 at 14:58









BartZalasBartZalas

9575 silver badges13 bronze badges




9575 silver badges13 bronze badges












  • Which event you have tried to observe?

    – Sohel Rana
    Jul 14 at 15:33











  • I use controller_action_predispatch_checkout_cart_add

    – BartZalas
    Jul 14 at 21:05

















  • Which event you have tried to observe?

    – Sohel Rana
    Jul 14 at 15:33











  • I use controller_action_predispatch_checkout_cart_add

    – BartZalas
    Jul 14 at 21:05
















Which event you have tried to observe?

– Sohel Rana
Jul 14 at 15:33





Which event you have tried to observe?

– Sohel Rana
Jul 14 at 15:33













I use controller_action_predispatch_checkout_cart_add

– BartZalas
Jul 14 at 21:05





I use controller_action_predispatch_checkout_cart_add

– BartZalas
Jul 14 at 21:05










2 Answers
2






active

oldest

votes


















1














If you are listening on checkout_cart_add_product_complete you have the following items on the $observer



 ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()]


Your code should look smth like this



$product = $observer->getProduct(); // or $observer->getData('product');
$customAttribute = $product->getCustomAttribute('custom_attribute_code');
// to avoid errors double check that this product
// has the custom attribute associated to it
$value = $customAttribute !== null ? $customAttribute->getValue() : null;


It's also a good practice to use the debugger to see what is what and what properties and values are available on a given object.



Hope this helps. Cheers.



EDIT as result of the comment



You do not have the product loaded at that point. You only have the controller instance and the request as it can be seen MagentoFrameworkAppActionAction::dispatch(). You must have smth on the request like a product_id or product_sku.



In a development environment if you don't have xdebug(you should really take care of that, it pays off) the fastest way to debug stuff is var_dump($object->getData()).



On this specific event what you can do is inject the product repository in the constructor, get the product id from the request and load the product.



smth like



$product = $this->productRepository->getById($observer->getRequest()->getProductId())


Once you have the product above should apply. You can add some extra checks like, is there a request on the observer data? is there a product id on the request and so on.






share|improve this answer

























  • Sorry I use controller_action_predispatch_checkout_cart_add my mistake. How You check what item do You have in $observer? Curentlly I use $this->_logger->log(100,print_r( $value, true)); WIth Xdebug have some problems for different Question.

    – BartZalas
    Jul 14 at 21:05












  • Oh ok I found this in file $this->_eventManager->dispatch( 'checkout_cart_add_product_complete', ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()] ); Problem that I cannot find mine event

    – BartZalas
    Jul 14 at 21:18












  • Check edited answer please.

    – vitoriodachef
    Jul 14 at 21:24






  • 1





    I would also edit the question to be smth like. Get product custom attribute in observer that listens to x specific event. You might get more hits. Cheers.

    – vitoriodachef
    Jul 14 at 21:28











  • Thanks for ideas. This I tried before getById. I see with var_dumb there is my attribute protected 'extensionAttributes' => null protected 'customAttributeFactory' => object(MagentoFrameworkApiAttributeValueFactory)[292] protected '_objectManager' => object(MagentoFrameworkAppObjectManager)[43] ... protected 'customAttributesCodes' => null ... protected '_origData' => array (size=75) 'my_attribute' => string ' value'

    – BartZalas
    Jul 14 at 21:53



















0














Finally I get this done with customer session storage



On this event I get custom attribute and save it on customer session




checkout_cart_add_product_complete




 public function execute(MagentoFrameworkEventObserver $observer) 
// get product custom attribute
$product = $observer->getProduct();
$customAttribute = $product->getCustomAttribute('custom_attribute');

// store attribute in customer session
$customer = $observer->getEvent()->getCustomer();
$myArray = $customAttribute->getValue();
$setValue = $this->customerSession->setMyValue($myArray);



On this I get redirect after add to cart and take attribute from customer session




controller_action_predispatch_checkout_cart_add




 public function execute(MagentoFrameworkEventObserver $observer) 
// get Value from customer session
$customer = $observer->getEvent()->getCustomer(); //Get customer object
$newurl = $this->customerSession->getMyValue();

//set redirect from attribute
$controller = $observer->getControllerAction();
$this->_actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
$controller->getResponse()->setRedirect($newurl);






share|improve this answer

























    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "479"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f282021%2fget-product-custom-attribute-in-observer-that-listens-to-x-specific-event%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    If you are listening on checkout_cart_add_product_complete you have the following items on the $observer



     ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()]


    Your code should look smth like this



    $product = $observer->getProduct(); // or $observer->getData('product');
    $customAttribute = $product->getCustomAttribute('custom_attribute_code');
    // to avoid errors double check that this product
    // has the custom attribute associated to it
    $value = $customAttribute !== null ? $customAttribute->getValue() : null;


    It's also a good practice to use the debugger to see what is what and what properties and values are available on a given object.



    Hope this helps. Cheers.



    EDIT as result of the comment



    You do not have the product loaded at that point. You only have the controller instance and the request as it can be seen MagentoFrameworkAppActionAction::dispatch(). You must have smth on the request like a product_id or product_sku.



    In a development environment if you don't have xdebug(you should really take care of that, it pays off) the fastest way to debug stuff is var_dump($object->getData()).



    On this specific event what you can do is inject the product repository in the constructor, get the product id from the request and load the product.



    smth like



    $product = $this->productRepository->getById($observer->getRequest()->getProductId())


    Once you have the product above should apply. You can add some extra checks like, is there a request on the observer data? is there a product id on the request and so on.






    share|improve this answer

























    • Sorry I use controller_action_predispatch_checkout_cart_add my mistake. How You check what item do You have in $observer? Curentlly I use $this->_logger->log(100,print_r( $value, true)); WIth Xdebug have some problems for different Question.

      – BartZalas
      Jul 14 at 21:05












    • Oh ok I found this in file $this->_eventManager->dispatch( 'checkout_cart_add_product_complete', ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()] ); Problem that I cannot find mine event

      – BartZalas
      Jul 14 at 21:18












    • Check edited answer please.

      – vitoriodachef
      Jul 14 at 21:24






    • 1





      I would also edit the question to be smth like. Get product custom attribute in observer that listens to x specific event. You might get more hits. Cheers.

      – vitoriodachef
      Jul 14 at 21:28











    • Thanks for ideas. This I tried before getById. I see with var_dumb there is my attribute protected 'extensionAttributes' => null protected 'customAttributeFactory' => object(MagentoFrameworkApiAttributeValueFactory)[292] protected '_objectManager' => object(MagentoFrameworkAppObjectManager)[43] ... protected 'customAttributesCodes' => null ... protected '_origData' => array (size=75) 'my_attribute' => string ' value'

      – BartZalas
      Jul 14 at 21:53
















    1














    If you are listening on checkout_cart_add_product_complete you have the following items on the $observer



     ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()]


    Your code should look smth like this



    $product = $observer->getProduct(); // or $observer->getData('product');
    $customAttribute = $product->getCustomAttribute('custom_attribute_code');
    // to avoid errors double check that this product
    // has the custom attribute associated to it
    $value = $customAttribute !== null ? $customAttribute->getValue() : null;


    It's also a good practice to use the debugger to see what is what and what properties and values are available on a given object.



    Hope this helps. Cheers.



    EDIT as result of the comment



    You do not have the product loaded at that point. You only have the controller instance and the request as it can be seen MagentoFrameworkAppActionAction::dispatch(). You must have smth on the request like a product_id or product_sku.



    In a development environment if you don't have xdebug(you should really take care of that, it pays off) the fastest way to debug stuff is var_dump($object->getData()).



    On this specific event what you can do is inject the product repository in the constructor, get the product id from the request and load the product.



    smth like



    $product = $this->productRepository->getById($observer->getRequest()->getProductId())


    Once you have the product above should apply. You can add some extra checks like, is there a request on the observer data? is there a product id on the request and so on.






    share|improve this answer

























    • Sorry I use controller_action_predispatch_checkout_cart_add my mistake. How You check what item do You have in $observer? Curentlly I use $this->_logger->log(100,print_r( $value, true)); WIth Xdebug have some problems for different Question.

      – BartZalas
      Jul 14 at 21:05












    • Oh ok I found this in file $this->_eventManager->dispatch( 'checkout_cart_add_product_complete', ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()] ); Problem that I cannot find mine event

      – BartZalas
      Jul 14 at 21:18












    • Check edited answer please.

      – vitoriodachef
      Jul 14 at 21:24






    • 1





      I would also edit the question to be smth like. Get product custom attribute in observer that listens to x specific event. You might get more hits. Cheers.

      – vitoriodachef
      Jul 14 at 21:28











    • Thanks for ideas. This I tried before getById. I see with var_dumb there is my attribute protected 'extensionAttributes' => null protected 'customAttributeFactory' => object(MagentoFrameworkApiAttributeValueFactory)[292] protected '_objectManager' => object(MagentoFrameworkAppObjectManager)[43] ... protected 'customAttributesCodes' => null ... protected '_origData' => array (size=75) 'my_attribute' => string ' value'

      – BartZalas
      Jul 14 at 21:53














    1












    1








    1







    If you are listening on checkout_cart_add_product_complete you have the following items on the $observer



     ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()]


    Your code should look smth like this



    $product = $observer->getProduct(); // or $observer->getData('product');
    $customAttribute = $product->getCustomAttribute('custom_attribute_code');
    // to avoid errors double check that this product
    // has the custom attribute associated to it
    $value = $customAttribute !== null ? $customAttribute->getValue() : null;


    It's also a good practice to use the debugger to see what is what and what properties and values are available on a given object.



    Hope this helps. Cheers.



    EDIT as result of the comment



    You do not have the product loaded at that point. You only have the controller instance and the request as it can be seen MagentoFrameworkAppActionAction::dispatch(). You must have smth on the request like a product_id or product_sku.



    In a development environment if you don't have xdebug(you should really take care of that, it pays off) the fastest way to debug stuff is var_dump($object->getData()).



    On this specific event what you can do is inject the product repository in the constructor, get the product id from the request and load the product.



    smth like



    $product = $this->productRepository->getById($observer->getRequest()->getProductId())


    Once you have the product above should apply. You can add some extra checks like, is there a request on the observer data? is there a product id on the request and so on.






    share|improve this answer















    If you are listening on checkout_cart_add_product_complete you have the following items on the $observer



     ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()]


    Your code should look smth like this



    $product = $observer->getProduct(); // or $observer->getData('product');
    $customAttribute = $product->getCustomAttribute('custom_attribute_code');
    // to avoid errors double check that this product
    // has the custom attribute associated to it
    $value = $customAttribute !== null ? $customAttribute->getValue() : null;


    It's also a good practice to use the debugger to see what is what and what properties and values are available on a given object.



    Hope this helps. Cheers.



    EDIT as result of the comment



    You do not have the product loaded at that point. You only have the controller instance and the request as it can be seen MagentoFrameworkAppActionAction::dispatch(). You must have smth on the request like a product_id or product_sku.



    In a development environment if you don't have xdebug(you should really take care of that, it pays off) the fastest way to debug stuff is var_dump($object->getData()).



    On this specific event what you can do is inject the product repository in the constructor, get the product id from the request and load the product.



    smth like



    $product = $this->productRepository->getById($observer->getRequest()->getProductId())


    Once you have the product above should apply. You can add some extra checks like, is there a request on the observer data? is there a product id on the request and so on.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jul 15 at 13:21









    Raj Mohan R

    1,6993 silver badges13 bronze badges




    1,6993 silver badges13 bronze badges










    answered Jul 14 at 19:13









    vitoriodachefvitoriodachef

    1,5204 silver badges28 bronze badges




    1,5204 silver badges28 bronze badges












    • Sorry I use controller_action_predispatch_checkout_cart_add my mistake. How You check what item do You have in $observer? Curentlly I use $this->_logger->log(100,print_r( $value, true)); WIth Xdebug have some problems for different Question.

      – BartZalas
      Jul 14 at 21:05












    • Oh ok I found this in file $this->_eventManager->dispatch( 'checkout_cart_add_product_complete', ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()] ); Problem that I cannot find mine event

      – BartZalas
      Jul 14 at 21:18












    • Check edited answer please.

      – vitoriodachef
      Jul 14 at 21:24






    • 1





      I would also edit the question to be smth like. Get product custom attribute in observer that listens to x specific event. You might get more hits. Cheers.

      – vitoriodachef
      Jul 14 at 21:28











    • Thanks for ideas. This I tried before getById. I see with var_dumb there is my attribute protected 'extensionAttributes' => null protected 'customAttributeFactory' => object(MagentoFrameworkApiAttributeValueFactory)[292] protected '_objectManager' => object(MagentoFrameworkAppObjectManager)[43] ... protected 'customAttributesCodes' => null ... protected '_origData' => array (size=75) 'my_attribute' => string ' value'

      – BartZalas
      Jul 14 at 21:53


















    • Sorry I use controller_action_predispatch_checkout_cart_add my mistake. How You check what item do You have in $observer? Curentlly I use $this->_logger->log(100,print_r( $value, true)); WIth Xdebug have some problems for different Question.

      – BartZalas
      Jul 14 at 21:05












    • Oh ok I found this in file $this->_eventManager->dispatch( 'checkout_cart_add_product_complete', ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()] ); Problem that I cannot find mine event

      – BartZalas
      Jul 14 at 21:18












    • Check edited answer please.

      – vitoriodachef
      Jul 14 at 21:24






    • 1





      I would also edit the question to be smth like. Get product custom attribute in observer that listens to x specific event. You might get more hits. Cheers.

      – vitoriodachef
      Jul 14 at 21:28











    • Thanks for ideas. This I tried before getById. I see with var_dumb there is my attribute protected 'extensionAttributes' => null protected 'customAttributeFactory' => object(MagentoFrameworkApiAttributeValueFactory)[292] protected '_objectManager' => object(MagentoFrameworkAppObjectManager)[43] ... protected 'customAttributesCodes' => null ... protected '_origData' => array (size=75) 'my_attribute' => string ' value'

      – BartZalas
      Jul 14 at 21:53

















    Sorry I use controller_action_predispatch_checkout_cart_add my mistake. How You check what item do You have in $observer? Curentlly I use $this->_logger->log(100,print_r( $value, true)); WIth Xdebug have some problems for different Question.

    – BartZalas
    Jul 14 at 21:05






    Sorry I use controller_action_predispatch_checkout_cart_add my mistake. How You check what item do You have in $observer? Curentlly I use $this->_logger->log(100,print_r( $value, true)); WIth Xdebug have some problems for different Question.

    – BartZalas
    Jul 14 at 21:05














    Oh ok I found this in file $this->_eventManager->dispatch( 'checkout_cart_add_product_complete', ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()] ); Problem that I cannot find mine event

    – BartZalas
    Jul 14 at 21:18






    Oh ok I found this in file $this->_eventManager->dispatch( 'checkout_cart_add_product_complete', ['product' => $product, 'request' => $this->getRequest(), 'response' => $this->getResponse()] ); Problem that I cannot find mine event

    – BartZalas
    Jul 14 at 21:18














    Check edited answer please.

    – vitoriodachef
    Jul 14 at 21:24





    Check edited answer please.

    – vitoriodachef
    Jul 14 at 21:24




    1




    1





    I would also edit the question to be smth like. Get product custom attribute in observer that listens to x specific event. You might get more hits. Cheers.

    – vitoriodachef
    Jul 14 at 21:28





    I would also edit the question to be smth like. Get product custom attribute in observer that listens to x specific event. You might get more hits. Cheers.

    – vitoriodachef
    Jul 14 at 21:28













    Thanks for ideas. This I tried before getById. I see with var_dumb there is my attribute protected 'extensionAttributes' => null protected 'customAttributeFactory' => object(MagentoFrameworkApiAttributeValueFactory)[292] protected '_objectManager' => object(MagentoFrameworkAppObjectManager)[43] ... protected 'customAttributesCodes' => null ... protected '_origData' => array (size=75) 'my_attribute' => string ' value'

    – BartZalas
    Jul 14 at 21:53






    Thanks for ideas. This I tried before getById. I see with var_dumb there is my attribute protected 'extensionAttributes' => null protected 'customAttributeFactory' => object(MagentoFrameworkApiAttributeValueFactory)[292] protected '_objectManager' => object(MagentoFrameworkAppObjectManager)[43] ... protected 'customAttributesCodes' => null ... protected '_origData' => array (size=75) 'my_attribute' => string ' value'

    – BartZalas
    Jul 14 at 21:53














    0














    Finally I get this done with customer session storage



    On this event I get custom attribute and save it on customer session




    checkout_cart_add_product_complete




     public function execute(MagentoFrameworkEventObserver $observer) 
    // get product custom attribute
    $product = $observer->getProduct();
    $customAttribute = $product->getCustomAttribute('custom_attribute');

    // store attribute in customer session
    $customer = $observer->getEvent()->getCustomer();
    $myArray = $customAttribute->getValue();
    $setValue = $this->customerSession->setMyValue($myArray);



    On this I get redirect after add to cart and take attribute from customer session




    controller_action_predispatch_checkout_cart_add




     public function execute(MagentoFrameworkEventObserver $observer) 
    // get Value from customer session
    $customer = $observer->getEvent()->getCustomer(); //Get customer object
    $newurl = $this->customerSession->getMyValue();

    //set redirect from attribute
    $controller = $observer->getControllerAction();
    $this->_actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
    $controller->getResponse()->setRedirect($newurl);






    share|improve this answer



























      0














      Finally I get this done with customer session storage



      On this event I get custom attribute and save it on customer session




      checkout_cart_add_product_complete




       public function execute(MagentoFrameworkEventObserver $observer) 
      // get product custom attribute
      $product = $observer->getProduct();
      $customAttribute = $product->getCustomAttribute('custom_attribute');

      // store attribute in customer session
      $customer = $observer->getEvent()->getCustomer();
      $myArray = $customAttribute->getValue();
      $setValue = $this->customerSession->setMyValue($myArray);



      On this I get redirect after add to cart and take attribute from customer session




      controller_action_predispatch_checkout_cart_add




       public function execute(MagentoFrameworkEventObserver $observer) 
      // get Value from customer session
      $customer = $observer->getEvent()->getCustomer(); //Get customer object
      $newurl = $this->customerSession->getMyValue();

      //set redirect from attribute
      $controller = $observer->getControllerAction();
      $this->_actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
      $controller->getResponse()->setRedirect($newurl);






      share|improve this answer

























        0












        0








        0







        Finally I get this done with customer session storage



        On this event I get custom attribute and save it on customer session




        checkout_cart_add_product_complete




         public function execute(MagentoFrameworkEventObserver $observer) 
        // get product custom attribute
        $product = $observer->getProduct();
        $customAttribute = $product->getCustomAttribute('custom_attribute');

        // store attribute in customer session
        $customer = $observer->getEvent()->getCustomer();
        $myArray = $customAttribute->getValue();
        $setValue = $this->customerSession->setMyValue($myArray);



        On this I get redirect after add to cart and take attribute from customer session




        controller_action_predispatch_checkout_cart_add




         public function execute(MagentoFrameworkEventObserver $observer) 
        // get Value from customer session
        $customer = $observer->getEvent()->getCustomer(); //Get customer object
        $newurl = $this->customerSession->getMyValue();

        //set redirect from attribute
        $controller = $observer->getControllerAction();
        $this->_actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
        $controller->getResponse()->setRedirect($newurl);






        share|improve this answer













        Finally I get this done with customer session storage



        On this event I get custom attribute and save it on customer session




        checkout_cart_add_product_complete




         public function execute(MagentoFrameworkEventObserver $observer) 
        // get product custom attribute
        $product = $observer->getProduct();
        $customAttribute = $product->getCustomAttribute('custom_attribute');

        // store attribute in customer session
        $customer = $observer->getEvent()->getCustomer();
        $myArray = $customAttribute->getValue();
        $setValue = $this->customerSession->setMyValue($myArray);



        On this I get redirect after add to cart and take attribute from customer session




        controller_action_predispatch_checkout_cart_add




         public function execute(MagentoFrameworkEventObserver $observer) 
        // get Value from customer session
        $customer = $observer->getEvent()->getCustomer(); //Get customer object
        $newurl = $this->customerSession->getMyValue();

        //set redirect from attribute
        $controller = $observer->getControllerAction();
        $this->_actionFlag->set('', MagentoFrameworkAppActionAction::FLAG_NO_DISPATCH, true);
        $controller->getResponse()->setRedirect($newurl);







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 2 days ago









        BartZalasBartZalas

        9575 silver badges13 bronze badges




        9575 silver badges13 bronze badges



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Magento Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f282021%2fget-product-custom-attribute-in-observer-that-listens-to-x-specific-event%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Get product attribute by attribute group code in magento 2get product attribute by product attribute group in magento 2Magento 2 Log Bundle Product Data in List Page?How to get all product attribute of a attribute group of Default attribute set?Magento 2.1 Create a filter in the product grid by new attributeMagento 2 : Get Product Attribute values By GroupMagento 2 How to get all existing values for one attributeMagento 2 get custom attribute of a single product inside a pluginMagento 2.3 How to get all the Multi Source Inventory (MSI) locations collection in custom module?Magento2: how to develop rest API to get new productsGet product attribute by attribute group code ( [attribute_group_code] ) in magento 2

            Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

            Magento 2.3: How do i solve this, Not registered handle, on custom form?How can i rewrite TierPrice Block in Magento2magento 2 captcha not rendering if I override layout xmlmain.CRITICAL: Plugin class doesn't existMagento 2 : Problem while adding custom button order view page?Magento 2.2.5: Overriding Admin Controller sales/orderMagento 2.2.5: Add, Update and Delete existing products Custom OptionsMagento 2.3 : File Upload issue in UI Component FormMagento2 Not registered handleHow to configured Form Builder Js in my custom magento 2.3.0 module?Magento 2.3. How to create image upload field in an admin form