1

I'm in the hook_entity_load in my module and I want to dynamically add a .js library which I already have defined.
The thing is i need to get to the block objec I'm on to add the library using $block['#attached']['library'][]

How do I get this block object?

2
  • 2
    Why in the load hook and not when the entity is viewed with hook_entity_view() What entity is this? In most cases, just because the entity is loaded doesn't mean it is used/displayed.
    – Berdir
    Mar 13, 2017 at 17:37
  • its a list of entities . I need to add .js under special conditions when i'm on a list of entities.
    – Diana
    Mar 13, 2017 at 17:48

1 Answer 1

3

The correct approach is doing it using a custom list builder, assuming you are using that and not a view.

class MyListBuilder extends EntityListBuilder {

  public function render() {
    $build = parent::render();
    $build['#attached']['library'][] = 'yourmodule/library';
  }
}

Then specify it in the annotation of your entity type.see Node/User or so on how to do that, most entity types specify either the default or a custom list builder.

If it's a view then you can implement one of the many views hooks, if it's not your own entity type then I'm not exactly sure why you need to add a JS there and you should explain in more detail what kind of list it is and what your JS does.

3
  • can you show me an example of where in the module to put this class?
    – Diana
    Mar 13, 2017 at 18:44
  • 1
    It doesn't really matter where you add it, you just have to put the right definition into the annotation. As I said, there are plenty of examples, almost every core enitty type has a list builder.
    – Berdir
    Mar 13, 2017 at 21:48
  • sounds like this is basically the same question as drupal.stackexchange.com/questions/231153/…. then it is a separate entity type, and instead of adding to the annotation, you need to implemnt hook_entity_type_alter() as commented there and extend NodeTypeListBuilder
    – Berdir
    Mar 14, 2017 at 0:13

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