I'm trying to create a custom block for a site but the block is not appearing in the editor dialogue. I've gone through multiple tutorials and changed my code a lot but it simply won't work.
What I've checked:
The block is added through a plugin but it also doesn't work when
moved to the theme.
I know the plugin is working correctly as I can use other wp
hooks/actions with no issues within the plugin.
I have tried using both 'init' & 'enqueue_block_assets' but neither
work.
I have verified all the file locations and paths are correct as I
have echoed them out to check.
I have changed to the default theme and it still does not appear.
Any help would be appreciated.
Here is the js block src (which is compiled):
import { registerBlockType } from '#wordpress/blocks'
registerBlockType('ghs/landing-page-block', {
title: 'Landing Page',
apiVersion: 2,
category: 'design',
icon: 'smiley',
description: 'Layout for the GHS landing page',
keywords: ['GHS', 'landing', 'page', 'front'],
edit: () => {
return (<div>hello</div>)
},
save: () => {
return (<div>hello</div>)
}
});
and the php registering it:
add_action('init', function() {
$asset_file = include( WP_PLUGIN_DIR . '/ghs-custom-blocks/assets/js/landing-page-block.asset.php');
wp_register_script('ghs-landing-page',
WP_PLUGIN_DIR . '/ghs-custom-blocks/assets/js/landing-page-block.js',
$asset_file['dependencies'],
$asset_file['version']);
register_block_type('ghs/landing-page-block', [
'api_version' => 2,
'editor_script' => 'ghs-landing-page',
]);
});
Solved it, it was because I was using WP_PLUGIN_DIR instead of plugin_dir_url(__FILE__). It meant the js request url was from the root instead of the wp installation.
Related
In Nuxt v2 we could add some scripts to an page like this:
head() {
return {
title: this.pageTitle,
script: [
{
src: this.scriptSrc,
type: 'text/javascript',
defer: true,
callback: () => {
this.setScriptLoaded(true)
}
}
]
}
}
But as you can see it's hard coded.
I need to add a new script at runtime under especial circumstances (e.g. if user click on a button.)
I know that we could just use Vanilla JS to add scripts dynamically like this:
const script = document.createElement('script')
script.setAttribute('src', this.scriptSrc)
document.head.appendChild(script)
But I wonder if there is a Nuxt solution?
I created a new page in my module by creating a new front controller. I want to add js and css files to this page but I am unable to do so. I have tried a couple of things, but none are working for me.
I tried adding the setMedia() function in the front controller:
public function setMedia()
{
parent::setMedia();
$this->registerJavascript(
'module-easypaymentoption-front',
'modules/' . $this->module->name . '/views/js/front.js',
[
'priority' => 200,
'attribute' => 'async',
]
);
}
I have also tried to load it by using the actionFrontControllerSetMedia hook in the main module php file:
public function hookActionFrontControllerSetMedia()
{
Media ::addJsDef([
'easypaymentoption' => $this->context->link->getModuleLink($this->name, 'validation', [], true),
]);
$this->context->controller->registerJavascript('modules-easypaymentoption',
'modules/' . $this->name . '/views/js/front.js');
$this->context->controller->registerStylesheet(
'module-easypaymentoption-style',
'modules/' . $this->name . '/views/css/front.css'
);
}
I also tried to add by using the hookHeader in the main module php file:
public function hookHeader()
{
$this->context->controller->addCSS($this->_path . '/views/css/front.css');
}
None of these I tried are working, can anyone help me out please?
Any help is very much appreciated.
You can use the hooks in the module main files, and not in the frontControllers.
Try this in your controllers/front/yourcontrollername.php file:
public function setMedia()
{
parent::setMedia();
$this->context->controller->registerJavascript(
'mymodulename',
'modules/'.$this->module->name.'/views/js/mymodulejs.js',
array(
'position' => 'bottom',
'priority' => 150
)
);
}
And don't forget to clear the cache, or try to reset your module if it's not working, because this is the official way to add JS and CSS to PrestaShop frontControllers.
I have replied to this on the PrestaShop forum where it was also posted, forum post
Try adding them in the hookDisplayHeader
Or, if your version is > 1.7.6.0 you can try:
$this->context->controller->registerStylesheet(sha1($css_path), $cssUrl, ['media' => 'all', 'priority' => xx]);
$this->context->controller->registerJavascript(sha1($js_path), $jsUrl, ['position' => 'bottom', 'priority' => xx]);
where css_path, js_path and xx are your variables.
Also in hookDisplayHeader.
I want to use autocomplete.js in my application.
I have installed the package using yarn add #tarekraafat/autocomplete.js. I am using webpack 4.28 to bundle the javascript files and have require("#tarekraafat/autocomplete.js/dist/js/autoComplete"); to import the package into the application and placed the bundled file at the bottom before the closing BODY tag.
In my custom.js file, I am creating a new instance of autoComplete as follows:
new autoComplete({
data: {
src: async () => {
document.querySelector("#autoComplete_results_list").style.display = "none";
document.querySelector("#autoComplete").setAttribute("placeholder", "Loading...");
const source = await fetch("/employee/search");
const data = await source.json();
return data;
},
key: "name"
},
selector: "#autoComplete",
placeHolder: "type employee name to search...",
threshold: 0,
searchEngine: "strict",
highlight: true,
dataAttribute: { tag: "value", value: "" },
maxResults: Infinity,
renderResults: {
destination: document.querySelector("#autoComplete"),
position: "afterend"
},
onSelection: feedback => {
document.querySelector(".selection").innerHTML = feedback.selection.food;
document
.querySelector("#autoComplete")
.setAttribute("placeholder", `${event.target.closest(".autoComplete_result").id}`);
console.log(feedback);
}
});
However, on running the application, I am getting an error Uncaught ReferenceError: autoComplete is not defined with a reference to the location where I am creating the new instance.
I have read the getting started documentation and looked at the demo code and I can't figure out what I am missing. How do I resolve the error?
Your problem is in your import, you are not import the autoComplete correctly, so when you using the new autoComplete you are having error.
Change the require("#tarekraafat/autocomplete.js/dist/js/autoComplete"); to import autoComplete from '#tarekraafat/autocomplete.js';, put this on top of your file, right after jquery or something
Write your code inside
$(document).ready(function(){
// Write your Code Here
});
I am currently building app in React.js that is suppose to be a advanced widget. Main requirement is that app should initialise only when at some point in time someone will execute function:
startApp({
someData: 'test',
wrap: 'domSelector'
});
i found this article Link, where author claims you can do this:
<div id="MyApp"></div>
<script>
window.runReactApplication({
user: { name: 'BTM', email: 'example#example.com' }
}, document.querySelector('#MyApp'));
</script>
and index.js
function runApplication(data, node) {
ReactDOM.render(<App data={data} />, node);
}
window.runReactApplication = runApplication;
It doesnt work for me as i get runReactApplication is undefined error.
Just out of curiosity i tried to wrap execution around timeout and it worked:
<script>
setTimeout(function() {
window.runReactApplication({
user: { name: 'BTM', email: 'example#example.com' }
}, document.querySelector('#MyApp'));
}, 150);
</script>
i can guess that in production its not a big problem because i can include app code first and then script so i have guarantee that function is added to the window.
But in development environment its a problem i dont know how to solve, and having timeout around function is obviously crazy. Anyone has an idea ?
You can use dynamic imports instead of setTimeout.
Let's say all of your react logic is bundled inside of index.js. Simply do the following to ensure that index.js has been downloaded and run before the desired DOM attachment:
import('index.js').then(() => {
window.runReactApplication({
user: { name: 'BTM', email: 'example#example.com' }
}, document.querySelector('#MyApp'));
}
If you want to preload the index.js file for optimal speed, simply add
<script src="index.js"></script>
to the head of your index.html file.
In the broader context, however, I am not sure why your startApp function wouldn't simply be:
function startApp(params){
const {data, selector} = params;
ReactDOM.render({
<App data={data} />
}, document.querySelector(selector));
}
And you could just bind this as a callback to whatever html event you want (i.e., onClick for a button, onLoad for the document loading, etc.).
button.onclick = startApp({data:{email: me#test.com}, selector: 'domSelector'});
i have a file javascripts/jsx/dashboard_card/DashboardCard.js in my rails app (canvas-lms), and the code is present below.
code :
//React.createElement(
// 'button',
//{
//'aria-expanded': this.state.editing,
//'aria-controls': this.colorPickerID(),
// className: 'Button Button--icon-action-rev ic-DashboardCard__header-button ddddddd',
// onClick: this.settingsClick,
//ref: 'settingsToggle' },
//React.createElement('i', { className: 'icon-compose icon-Line ccccccc xxxxxxxx', 'aria-hidden': 'true','visibility': 'hidden' }),
//React.createElement(
//'span',
//{ className: 'screenreader-only' },
// I18n.t("Choose a color or course nickname for %{course}", { course: this.state.nicknameInfo.nickname })
//)
//)
i changed this code and even commented. but the changes which i made in this file are not getting reflected in my rails application. how to restart the react.js in rails application? I restarted rails server also. but nothing is changing.