I'm quite new to Drupal so bear with me here.

I've created an entity using Drupal Console, specifically using drupal generate:entity:content. Which works perfectly. Kudos to the Drupal console guys.

This specific entity will deal with adding some meta tags on specific URLs thru the site.

It has several fields that need to be completed: url, keywords(if any), one open graph tag, and a tag value.

After looking through this question I've decided that using hook_page_attachments is the way to go for me.

The logic for adding the tags is quite simple:

  • Get the entity.
    • $entity = \Drupal::entityTypeManager()->getStorage('meta_tag_entity')
  • Grab the current url.
  • Loop through the entity url fields and check if any matches the current url.
  • If it does, simply add the tags.

And that's it.

The problem boils down this.

After I've loaded the entity ($entity = \Drupal::entityTypeManager()->getStorage('meta_tag_entity')) I have no idea how to grab all the url fields.

I've looked over this question but it's not quite what I'm looking for.

2 Answers 2


You should be able to use either get or getFields on your entity object if it is derived from ContentEntityBase.

See: https://drupal.stackexchange.com/a/232219/57

So, after you load the entity:

$fields = $my_entity->getFields();


$foo = $my_entity->get('bar')->value;

getStorage() does not load the entity.

It loads the storage handler that is able to load entities.

Usually you don't have one entity, you have many, one for each URL.

So you don't want to loop over fields in PHP, you want to do a query against the DB to find if you have an entity that matches the current url.

Look for entity query, there are various related questions on this site as well as documentation/tutorials elsewhere. For example: https://www.sitepoint.com/drupal-8-version-entityfieldquery/. Try that and if you still have a problem, I'd recommend you ask a more specific question with code you came up with.

Also, did you consider using the metatags module, which does something very similar, although based on a field on other entities and not a standalone entity: http://drupal.org/project/metatag

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.