Skip to content

Move multiple blocks in Magento 2 without xml

I need to move several elements of a layout without using layout.xml

I have followed the bellow code to create an observer and it correctly moves a single element. When I try adding the other elements to the update it still only moves one element.

namespace CompanyModuleObserver;

class LayoutLoadBefore implements MagentoFrameworkEventObserverInterface
{
    /**
     * add custom layout updates
     *
     * @param MagentoFrameworkEventObserver $observer
     * @return $this
     */
    public function execute(MagentoFrameworkEventObserver $observer)
    {
        $move = false;

        // add your checks here

        if ($move) {
            /** @var MagentoFrameworkViewLayoutInterface $layout */
            $layout = $observer->getData('layout');
            $layout->getUpdate()->addUpdate('<move element="blah" destination="to" before="-" />');
        }

        return $this;
    }
}

I Have tried:

if (isset($move) && $move) {
            /** @var LayoutInterface $layout */
            $layout = $observer->getData('layout');
         
            $layout->getUpdate()->addUpdate('<move element="product.info.details" destination="product.info.media" after="-"/>');
            $layout->getUpdate()->addUpdate('<move element="catalog.product.related" destination="product.info.media" after="-"/>');
            $layout->getUpdate()->addUpdate('<move element="product.info.upsell" destination="product.info.media" after="product.info.details"/>');
        }
    return $this;

and this:

if (isset($move) && $move) {
            /** @var LayoutInterface $layout */
            $layout = $observer->getData('layout');
            $updateXml = '<move element="product.info.details" destination="product.info.media" after="-"/><move element="catalog.product.related" destination="product.info.media" after="-"/>';
            
            $layout->getUpdate()->addUpdate($updateXml);
        }

        return $this; 

But neither works. Do anyone know how to achieve this?