Attached JS Libraries Not Working When Caching Turned Off On Block

PROBLEM
Came across a weird one yesterday. I had just finished touches on a HighCharts block. I noticed that it wasn’t refreshing with updated content. Well I know what to do about that.

I added the getCacheMaxAge(). But then! Oh no!

I got a JS error saying HighCharts wasn’t defined. What the? And viewing the source, the two libraries I was including in the block were not included. What happened?

SOLUTION
I’m not fully sure why this happened the way it did. I tried several other things like adding the kill switch (\Drupal::service("page_cache_kill_switch")->trigger();) and adding "#cache" => array("max-age" => 0) to the returned array in the build method.

I then just decided to try a shot in the dark and instead of making the cached age 0, I made it 1 (as in one second)… So just this in the build method:

return array(
	...
	"#cache" => array(
		"max-age" => 1
	),
	...

So… whatever Drupal. It works… until it doesn’t.

Used Drupal 8 Functions That Don’t Work In Drupal 9

Not really a problem/solution post.

We’re upgrading to Drupal 9! Let me tell you, what a crock that Upgrade Status module is. It’s a trap! It does so little it’s almost laughable. It primarily told me that all my .info.yml files just needed core_version_requirement: ^8.8 || ^9 and they were good.

That’s not true. It’s a scam. We upgraded to D9 and things broke all over the place. Symphony has been giving us the most trouble. Sometimes the error will tell you what to change it to, most of the times not.

Anyway, here’s a blog post of stuff I had to figure out how to change on my own since simply googling for it won’t yield the fix you’re looking for.

\Drupal::service(“path.alias_storage”)->aliasExists

If you’re trying to check if an alias exists like this:

if (\Drupal::service("path.alias_storage")->aliasExists($node_path, "en")) {

That function doesn’t exist anymore. It takes more to figure this out now; especially since the return of this isn’t true or false; it’s the fucking path.

Your new code for this is:

$possible_node_alias = \Drupal::service("path_alias.manager")->getPathByAlias($node_path);
// is this path a node path? if so, it's the equivalent of aliasExists returning true
if (str_starts_with($possible_node_alias, "/node/") && is_numeric(str_replace("/node/", "", $possible_node_alias))) {

In the if, that’s where it would be true if the alias is in use.

\Drupal::service(“path_alias.manager”)->save

This one was a little easier to track down.

Before it was:

\Drupal::service("path_alias.manager")->save("/node/" . $node_id, $archive_url, "en");

Now it’s:

$path_alias = \Drupal\path_alias\Entity\PathAlias::create(array("path" => "/node/" . $nid, "alias" => $archive_url));
$path_alias->save();

Yay for more lines of code that do the same fucking thing as before!

I’ll update this blog post if there are any more I get stuck on and google doesn’t have the answer.