I working with dynamic event in Magento 2, i detected dynamic event call 3 times(example: customer_address_save_after event). This problem in here because i only want run once times this dynamic event.

How to fix this issue ?


Instead of flags you can use Registry class.

create instance from constructor

public function __construct(\Magento\Framework\Registry $registry) {
        $this->_coreRegistry = $registry;

to register

$this->_coreRegistry->register('customer_address_save_observer_executed_' . $customerAddress->getId(),true);

to get the from register weather it's executed or not? if executed just return this otherwise it will execute.

if($this->_coreRegistry->registry('customer_address_save_observer_executed_' . $customerAddress->getId()))
                    return $this;
  • I try again but it not working – Thao Pham Dec 11 '15 at 7:27
  • @Bill, post your code. – Bojjaiah Dec 11 '15 at 7:48
  • I create registry as you but it still run 3 times – Thao Pham Dec 11 '15 at 7:57

You should be able to set a flag and check it before running your code.

if($flag) { //check if flag is already set
    return; // return, flag is set
} else {
    fn(); //your code here
    $flag = true;

Flag can be a session flag or something you add to the original object and check after.

Something (pretty) similar can be found here.

  • When declare $flag first times, Where i can get value to avoid undefined variable ? – Thao Pham Nov 24 '15 at 3:57

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.