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).

  -- 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:


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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.