Jump to content

Hooks: JS is not being injected


dragan
 Share

Recommended Posts

$this->addHookBefore('InputfieldTextarea::render', function($event) {
	$field = $event->object;
	if($field->name == 'body_offer') {
		$del = '';
		foreach($this->wire->pages->get(11229)->textblocks as $item) {
			$field->entityEncodeText = false;
			$body = str_replace(PHP_EOL, '', $item->body);
			$body = addslashes($body);
			$title = $item->title;
			$field->description .= $del . "<a href=\"#\" class=\"ckesnippet\" data-snippet=\"$body\">$title</a>";
			$del = ' | ';
		}
    }
    $js = wire('config')->urls->templates . 'scripts/ckesnippets.js';
    $event->return = str_replace("</html>", "\n<script type='text/javascript' src='$js'></script>\n</html>", $event->return);
});

I'm trying to add custom text-blocks from repeater fields into CKEditor. I've stolen the whole idea (and code) from @bernhard

Problem is: The links are actually being rendered, but the Javascript is not loaded, i.e. the $event->return line doesn't seem to work. If I inspect the HTML, my additional script-tag is nowhere to be seen. I don't get any errors either. Running latest PW dev + PHP 7.1.19.

  • Like 1
Link to comment
Share on other sites

Shot in the dark, but is '</html>' rendered in 'InputfieldTextarea::render'? I know it's rendered in 'Page::render'. Might be worth taking a look at what $event->return is actually outputting. Maybe just echo $event->return. 

  • Like 1
Link to comment
Share on other sites

I think Tom is right. Inputfield render is the inputfield markup not the whole <html>.

Why not just use the core scripts array?

$this->wire("config")->scripts->add("/xxx/xxx.js");

  • Like 1
Link to comment
Share on other sites

11 minutes ago, Soma said:

Why not just use the core scripts array?

$this->wire("config")->scripts->add("/xxx/xxx.js");

jep, just take care when using AJAX loaded fields. if you add your JS via a ::render hook it will not get loaded. You need to load it via ::renderready

 

 

  • Like 2
Link to comment
Share on other sites

1 hour ago, Soma said:

$this->wire("config")->scripts->add("/xxx/xxx.js");

oops, of course. Works like a charm now. .

 

1 hour ago, bernhard said:

::renderready

Thanks for the heads-up. Will keep it in mind.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...