1

I have created a custom block, as I want to add this layout to my current layout.

Following is my block:

<referenceContainer name="sidebar.main">
        <block class="Vendor\ModuleName\Block\Frontend\Block" name="ucTntlZsQVjVytW4xjtfdypv9LTzRsFP" template="Vendor_ModuleName::myBlock.phtml"/>
    </referenceContainer>

I want to add this block to my current block for that I created following event:

core_layout_render_element

Now how can I add this block to layout using PHP

Need Help!!

7
  • May I know the purpose why you created an event for adding a custom block? It can be added simply. May 30, 2019 at 10:19
  • i want to add a slider on any page at any location according to his need..
    – Waqar Ali
    May 30, 2019 at 10:21
  • For That purpose why you don't try widget? May 30, 2019 at 10:22
  • Then as you described xml sample code, is perfect one. You just need to use same <block> tag in the required xml layout files. May 30, 2019 at 10:23
  • @RutveeSojitra i have already done this by widget .. but my client want this functionality in admin form
    – Waqar Ali
    May 30, 2019 at 10:23

1 Answer 1

2

Try this event: layout_load_before

<event name="layout_load_before">
    <observer name="bannerlayoutloadbefore" instance="Vendor\ModuleName\Observer\Bannerlayoutloadbefore" shared="false" />
</event>

And use the below php code to render the layout:

$layout = '<referenceContainer name="sidebar.main">
        <block class="Vendor\ModuleName\Block\Frontend\Block" name="ucTntlZsQVjVytW4xjtfdypv9LTzRsFP" template="Vendor_ModuleName::myBlock.phtml"/>
    </referenceContainer>';
$observer->getLayout()->getUpdate()->addUpdate($layout);

Use the above code in your observer's execute function.

6
  • It seems bad practice to write layout XML inside PHP.
    – Ben Crook
    May 30, 2019 at 10:28
  • @BenCrook any other way to do this??
    – Waqar Ali
    May 30, 2019 at 10:29
  • 1
    Yes but I have checked Amasty's extension who uses the same code in their Part Finder extension to load dynamic layout and I think they are reputed Magento extension provider. I am just trying answere just according to the question Waqar asked. May 30, 2019 at 10:30
  • @SukumarGorai i m trying this .. Thank for Your answer
    – Waqar Ali
    May 30, 2019 at 10:38
  • 1
    @SukumarGorai thank you this worked for me i have been strucked in this issue from last 15 days thank you so much
    – Waqar Ali
    May 30, 2019 at 11:36

Your Answer

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

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