TransWikia.com

Entry ancestors is null in dynamic asset subfolder path or during EVENT_AFTER_SAVE event

Craft CMS Asked on May 2, 2021

I’d like to use the slug of the top-level entry in a structure in an asset’s dynamic folder subpath.

I have a structure where the entry I’m concerned with for this question can sit at either the second or third level. Forgive this very dubious example: possible locations for clothing in a bedroom (socks get left on the floor in this bedroom).

Bedroom
  -- Wardrobe
      -- Shirt
      -- Jacket
  -- Socks

Shirts and Jackets have a parent of Wardrobe, Socks have a parent of the Bedroom. Still with me?

Items of clothing have an Asset field which has a dynamic subfolder path, where the only thing I’m really concerned about is the top level item in the structure (the bedroom). The asset subfolder path for these items of clothing are therefore:

/bedroom/Clothing/socks.jpg
/bedroom/Clothing/shirt.jpg
/bedroom/Clothing/jacket.jpg

In other words, <structure top level slug>/Clothing/<entry slug>

I have tried to make use of ancestors but any element queries using it are returning null when saving the entry.

{ancestors.level(1).one() ? ancestors.level(1).one().slug : parent.slug}/Clothing/{slug}/

I’m also seeing the same in an Entry::EVENT_AFTER_SAVE event (checking it’s not a draft or revision), where (ModelEvent) $event->sender->ancestors->level(1)->one() returns null for the entry being saved.

In both cases, parent has a correct value, but that’s no use for things in the Wardrobe.

How do I get at the slug for the top level entry in a structure, for use in an asset’s subfolder path?

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP