I would like to programmatically assign a different view mode to the entity depending on its queue position. I am doing this because I have a different image style in each of the view modes, so I always want the first item in the queue to automatically use a particular view mode, rather than rely on the user choosing the correct view modes when adding items to the collection.

I am trying to load the entire entity collection in hook_entity_view_mode_alter(), and then change the view mode there. Unfortunately I am unable to load the collection with its child items. I only get the collection definition using entity_collection_load().

If my goal is simply have different image styles based on queue position, then maybe I don't need different view modes and I only need to alter the image style somehow.

Any feedback or ideas are appreciated.

Comments

esolitos’s picture

Hi jlongbottom,
as you probably found out already this is not currently possible by default with Entity Collection using the given code.
I am actually planning (in the future) to have a Row plugin that will do exactly that, but this requires some changes also in the way the data is stored, since the view mode is currently tightly connected with the entity.

What you can do is create a new Row plugin in your module and simply extend the EntityCollectionRow class, you can copy most of the EntityCollectionRowViewMode code, customizing the build() function as you like will do the trick.

Otherwise you can use the hook_entity_collection_content_pre_insert and set the view mode of the items every time you add a new item, but this will not work if you reorder the collection. Another useful hook could be the hook_entity_collection_tree_alter, you can then alter the tree right after it has been loaded.

Does this help you?

jlongbottom’s picture

Hi esolitos,

Thanks for such a quick reply.

hook_entity_collection_tree_alter() is what I need. I didn't know about that hook.

How can I ensure that I am only altering a particular entity collection? This hook has NULL for the bundle name and type.

Other than searching the code for drupal_alter(), where should I have found this? I like this module, but it could use a little documentation.

esolitos’s picture

Yes, you're absolutely right we're lacking documentation and we're aware of that, it's something we're delaying since a while.

I have added, in the -dev release, a $context parameter to the drupal_alter, it was actually missing, now the hook likks like this hook_entity_collection_tree_alter( &$tree, $context);, where $context is an array with two keys: 'collection_name' and 'collection_bundle'.

jlongbottom’s picture

Awesome, I will take a look at the -dev version. Thank you!

esolitos’s picture

Version: 7.x-2.0-alpha8 » 7.x-2.x-dev
Status: Active » Fixed

Status: Fixed » Closed (fixed)

Automatically closed - issue fixed for 2 weeks with no activity.