I am wanting to do custom javascript to manipulate the Widget Options when adding a widget (using the WYSIWYG editor) in the Admin panel.

I have found that the layout handle adminhtml_widget_index is being loaded via AJAX to get that content, however, I have noticed that any script tags in my template file are being removed.

For demonstration purposes the phtml file I am using looks like

// Module_Vendor::test.phtml
<?php
/** @var \Magento\Backend\Block\Template $block */
?>
<h2>Modal windows strip custom js...</h2>
<script>
    alert('Just kidding, JAVASCRIPT works in modals');
</script>

I have the <h2> tag showing on the widget modal form, but looking at the source there is no script tag.

Looking further into how the widget renders, using the \Magento\Widget\Block\Adminhtml\Widget class, there is a protected $_formScripts array that might be used with a plugin which could solve the issue, however I'm wondering if there is another way to render custom javascript on the Insert Widget modal form?

If anyone has any useful information, I'd be delighted to hear it.

Thanks in advance!

As a side note there is an initialisation of the wysiwyg widget javascript component which is added as a string to the $_formScripts array, which doesn't seem like best practice, so even if using the $_formScripts array is how we should do it, if you could provide an example of how, that would also be fantastic!

有帮助吗?

解决方案

So using the test template (I should've tested it before posting) the JS alert is showing as expected. I had specific JS issues with the other JS I was trying to render, but the source still doesn't show the script tag, which is what led me to think this is where it was broken.

This could be a good place for custom widget JS discussion, or determining best practice, but I'm going to mark this as answered.

Edit: To be clear, adding a custom block to the admin_widget_index layout file actually did render the custom javascript, there is just some tricky preprocessing that Magento does to script elements, where the JS is loaded anonymously... I'm not actually sure how it works, but the JS is running, so I didn't have to use the _formScripts array at all.

An example layout xml file looks like

<!-- vendor/mycompany/module-modify-widget-options/view/adminhtml/layout/adminhtml_widget_index.xml -->
<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/layout_generic.xsd">
<body>
    <referenceContainer name="root">
        <block class="\Magento\Backend\Block\Template" template="Module_Vendor::test.phtml" name="test_edit_modal"/>
    </referenceContainer>
</body>
</layout>
许可以下: CC-BY-SA归因
scroll top