Installing Library Using Drupal & Composer

PROBLEM
The instructions on drupal.org on how to install a library using composer suck. Or maybe I’m just doing it wrong? I don’t know. But it happened again. I need another library from some outside source.

I thought I just needed to modify my composer.json file and run composer install and it was good but I forgot the other step.

SOLUTION
You also need to run composer require and whatever you named your library.

Here’s the code from my composer.json:

		{
			"type": "package",
			"package": {
				"name": "addon/youtube",
				"version": "2.1.18",
				"type": "drupal-library",
				"dist": {
					"url": "https://download.ckeditor.com/youtube/releases/youtube_2.1.18.zip",
					"type": "zip"
				}
			}
		},

Save the file. Then run:

$ composer require addon/youtube

That should do it. Maybe run another $ composer install so everything is good.

Background Opacity Affecting Text Opacity

PROBLEM
Why do I always forget this? Hopefully I’ll remember why this happens this time with a simple blog post!

When you add opacity to a div, it affects the text opacity as well. Ex.

Your CSS is something like this:

.header_background {
	opacity: .8;
	color: #FFFFFF;
	background-color: #475260;
}

SOLUTION
Do not just use opacity like that. Use it like this:

.header_background {
	color: #FFFFFF;
	background: rgba(47, 52, 60, .8);
}

Now it’s nice:

Get Human-Readable Name Of Media Bundle In Drupal 8

PROBLEM
I need to get the label/name of the bundle of a media entity for a preprocess. Unfortunately, the following code to get the label of the bundle does not work for media:

$current_entity->type->entity->label()

I’ve tried to google various things but nothing came up that was helpful. The code $current_entity->bundle() works to get the machine name of the bundle; but how can we get the human-readable name of the bundle?

SOLUTION
The solution requires something really stupid. If anyone has a method I can call instead, more than welcome to comment!

\Drupal\media\Entity\MediaType::load($current_entity->bundle())->label()

That’s really stupid!

By the way, just to remember, how to get the entity type you can use:

$current_entity->getEntityTypeId()

I think this ticket could possibly make the solution easier: https://www.drupal.org/project/drupal/issues/969180. All entities should use the same methods to get the type, bundle, label, etc. Also, label shouldn’t be ambiguous. It should either be for the title of the entity or for what the entity actually is.

Change Theme To Admin For Custom Module Page

I’ll forgo the PROBLEM/SOLUTION in this one since it’s so quick.

I wanted to make the pages (forms) of a custom module I was creating use the admin theme instead of the public facing theme. Turns out it was really easy.

In the .routing.yml file, add the following:

  options:
    _admin_route: TRUE

So a cleaned-up example of the yml looks like this:

whatever_your_form_is.form:
  path: '/whatever/your/path/is'
  defaults:
    _form: '\Drupal\module_name\Form\WhateverYourFormIs'
    _title: 'Page/Form Title'
  requirements:
    _role: 'authenticated'
  options:
    _admin_route: TRUE

Need this in my arsenal.

Unexpected Error With Form Controller

This is going to be a stupid one but I’m going to blog about it anyway.

PROBLEM
While setting up a new custom module for Drupal 8, I need to set up a form. Since I’ve done this many times before, I copied and pasted stuff from another module which worked.

While renaming things and putting things in the right spot, when I went to test the form I got the following error:

TypeError: Argument 2 passed to Symfony\Component\HttpKernel\Event\FilterControllerEvent::__construct() must be callable, object given, called in /var/www/docroot/vendor/symfony/http-kernel/HttpKernel.php on line 138 in Symfony\Component\HttpKernel\Event\FilterControllerEvent->__construct() (line 32 of /var/www/docroot/vendor/symfony/http-kernel/Event/FilterControllerEvent.php)

Google was completely useless! It seems I was the only one in history to get this.

SOLUTION
Considering how fucking burnt out I am without having a break in more than a year, I completely missed it. The solution was so simple.

I guess I had renamed my file wrong in the /module_name/src/Form/ folder. After renaming everything again to bullshit, I found I guess that was my issue.

I’m filling this under silly mistakes that I hope I never make again! #stupidjanny

How To Determine If You’re On A Node In Drupal 8

PROBLEM
Preamble: If you don’t know how yet to embed media into Drupal, I recommend looking at how to embed stuff into Drupal 8 by Lullabot. It doesn’t go over everything (since you definitely need custom stuff) but it’s a good start.

We are using Entity Embed along with a few other contributed Drupal modules to be able to insert media into the WYSIWYG. I created a custom module in order to do this. I use hooks such as
HOOK_preprocess_entity_embed_container and HOOK_form_entity_embed_dialog_alter in order to get this functionality to work. I also have a template which outputs the media. Images output as img, files output as a link with file name and opens in a new window.

We were now asked to attach a content type in our content. Instead of creating a field, I wanted to be able to insert this content into the WYSIWYG.

After modifying my custom module which will render the entity, I ran into an interesting issue. I did not want to render the full entity in the WYSIWYG. First, it would render the whole thing and it would not put in the stuff we put into our .theme file. It didn’t look right.

I only want the entity to be rendered on the node screen (i.e. in our public facing theme… when it’s actually on a node).

The template in our custom module renders it in both the WYSIWYG and on the “node” side. So… how do I get it to only render on the “node” side?

SOLUTION
There are several states when it’s on the “node” side. I’m adding a variable in HOOK_preprocess_entity_embed_container which will tell the template to render the entity or else just say the name of the node it’s inserting. Just using
$node_info = \Drupal::routeMatch()->getParameter("node"); doesn’t work. $node_info is NULL on preview. However, if you also do:

$node_info = \Drupal::routeMatch()->getParameter("node");
if (empty($node_info)) {
	$node_info = \Drupal::routeMatch()->getParameter("node_preview");
}

then a:

if (gettype($node_info) == "object") {
	$variables["node_render"] = true;
}

which will tell the template to render the entity via the {{ children }}. So far this code hasn’t triggered any PHP or Drupal errors or warnings (fingers crossed).

Not sure if I’ll need this again but it’s probably handy to have since we are also using workbench, have nodes in draft, and have a preview.

Hook “More” Link In Views For Drupal 8

PROBLEM
I needed a way to modify the Custom URL in the Pager for the More link for Views. I added a Contextual Filter so that the particular display can be put onto any page and it will display items from the current office.

This URL needs to be dynamic and change depending on where on the site this view is placed.

What Views needs here is some tokens!

SOLUTION
I looked into hooking “container” but that seems messy as I’m not sure where else it’s used. It’s doable that way but I primarily tried to look at the view.

In my preprocess, THEME_views_pre_render, I tried to dig further into the ViewsExecutable class. It turns out, the display_plugin method was what I was looking for.

Here’s some of my code:

function THEME_views_pre_render(\Drupal\views\ViewExecutable $view) {
	// target your view and display
	if (($view->id() == "my_view") && ($view->current_display == "my_display")) {
		// this is just what's actually in the field to begin with... i.e. "success-story" in my screen shot above
		$ending_part_of_uri = $view->display_handler->getOption("link_url");

		// call a function or whatever to get the part of your uri
		$starting_part_of_uri = _THEME_function_to_dynamically_get_URI();

		// now set the link to whatever
		$view->display_handler->setOption("link_url", $starting_part_of_uri . $ending_part_of_uri));
	}
}

Turn Off Caching For Paragraph In Drupal 8

PROBLEM
I had an interesting one. I’ve blogged about Drupal 8 caching before and how annoying it is. I’ve solved the issue of caching custom blocks and caching on a specific view.

But what about paragraphs?

We needed to make content in a paragraph dynamic and change on every page load. We want a random item to display from an array of items. I noticed that this happened when the user was logged in but not anonymously. I don’t know if I have caching turned off for authenticated users or what.

After some digging, I couldn’t find a good way to turn caching off with config and I wasn’t about to turn caching off for every page. I also couldn’t find a way to do it in the preprocess of the paragraph.

SOLUTION
There’s kinda like a kill switch, I guess. I think we should probably use this sparingly as there’s a reason why Drupal caches so much (it is a HUGE footprint!).

I put this code inside my preprocess function of my paragraph in my .theme file:

\Drupal::service("page_cache_kill_switch")->trigger();

It took me a bit to find it as googling around doesn’t yield the results I’d expect.

And note, this is how I solved it for the mean time… This way might not be the best but it works. Until I am told that this is very dangerous or whatever and we find a better way, this is what I did.

Default Value Of Today’s Date On Timestamp In Drupal 8

PROBLEM
One of the stupidest things in Drupal 8 is the Timestamp field. If only I knew what I know now. All well, we’re stuck with it.

Its default value cannot be set to today’s date. When saving the field as null in the field settings, going to a new node, the default value is when you saved the field. Ours was two years ago since that’s when I started working on this site. So default dates for our Timestamp field were like “09/04/2018 02:43:02 PM”.

Not good. How do you make the default date the date of the new node (like today’s date and time)?

SOLUTION
I first installed a patch on a ticket on drupal.org (patch #14) which allowed the field setting to be null. Since the Timestamp field sucks, it doesn’t give you the option of today’s date like the Date field does. So, I had to add to our custom module the way to do that.

// see if we need to worry about the publication date
if (isset($form["field_publication_date"])) {
	// if it's a new form
	if ($form_id == "node_" . $your_content_type . "_form") {
		// set the default value to a new date time (which by default is "now")
		$form["field_publication_date"]["widget"][0]["value"]["#default_value"] = new DrupalDateTime();
	}

	// end if we have a field_publication_date
}

This code can go inside a preprocess like hook_form_alter. You also don’t need to do it the way that I did with the $form_id. There might be a new node hook somewhere that you could add this to maybe. Obviously, the field_publication_date should be changed to whatever your Timestamp field machine name is called.

Drupal 8 Composer/Drush Errors Plugin Does Not Exist

PROBLEM
You done f**ked up. You did a $ composer uninstall on a module before you disabled it. You go in to import or do something else drush related. Boom! Errors!

I recently received the following errors when I accidentally did this with views_accordion:

The "views_accordion" plugin does not exist. Valid plugin IDs for Drupal\views\Plugin\ViewsPluginManager are: entity_reference_revisions, serializer, data_export, default, default_summary, entity_reference, grid, html_list, opml, rss, table, unformatted_summary
[warning] include_once(/appdata/www/web/modules/contrib/views_accordion/views_accordion.module): failed to open stream: No such file or directory Extension.php:147
[warning] include_once(): Failed opening '/appdata/www/web/modules/contrib/views_accordion/views_accordion.module' for inclusion (include_path='/appdata/www/vendor/pear/archive_tar:/appdata/www/ACF-D8-Enterprise/vendor/pear/console_getopt:/appdata/www/ACF-D8-Enterprise/vendor/pear/pear-core-minimal/src:/appdata/www/vendor/pear/pear_exception:.:/opt/rh/rh-php72/root/usr/share/pear:/opt/rh/rh-php72/root/usr/share/php') Extension.php:147

SOLUTION
You will need to re-install the missing module again, then do a cache refresh, then disable it, then uninstall it. Like the following:

$ composer require drupal/views_accordion
$ drush cr
$ drush pm:uninstall views_accordion
$ composer remove views_accordion
$ drush cr

The first $ drush cr refreshes the cache. This step is very important because it then determines the link to the “newer” views_accordion module. That was the key! Then you should be able to disable the module and uninstall it the correct way.

Need to remember this for later! Mistakes happen.

BONUS
Here’s a command I put in my “to remember” pile as well. If you get an error about The following module is missing from the file system... error, you can do the following:

$ drush sql-query "DELETE FROM key_value WHERE collection='system.schema' AND name='the_module_its_bitching_about';"

The the_module_its_bitching_about is the machine name of the module it’s bitching about.