Select field: save selected structure as yaml

I have structure field on site.yml with two text fields:

authors:
  label: Auteurs
  type: structure
  sortBy: lastnames asc
  fields:
    firstnames:
      label: First names
      type: text
    lastnames:
      label: Last names
      type: text

I select a structure from that field in a select field on a page via a query:

  author:
    label: Author
    type: select
    options: query
    query: 
      fetch: site.authors.toStructure.sortBy('lastnames', 'ASC')
      text: "{{ structureItem.lastnames }} {{ structureItem.firstnames }}"

How do I save the selected structure as yaml? I want to render the structure fields separately in my template.

The default value seems to be the index of the item in the original structure field, which is a bit strange to me (because changes to that list invalidate all saved values in the dependent select field).

You can set the value that gets stored. You might want to consider using the AutoID plugin.

  author:
    label: Author
    type: select
    options: query
    query: 
      fetch: site.authors.toStructure.sortBy('lastnames', 'ASC')
      text: "{{ structureItem.lastnames }} {{ structureItem.firstnames }}"
      value: "{{structureItem.lastnames}}"

So no way to store it as yaml then? Bummer.

To clarify: I want to be able to render ...->lastnames() and ->firstnames() independently. AutoID would still require me to loop through the $site->authors() field any time I want to render these in a template, which seems a bit inefficient.

Yes, but in most cases the reason to use a select field and query options from somewhere is to make a relation, so when the relation doesn’t exists anymore because it was deleted, then you probably don’t want to output anything. But that depends on use case, of course. An author will still be an author, even if they are deleted later.

But the select field can’t store/read stuff in yaml format, so in order to do so, you would have to create a custom field. Or you just store lastname and firstname as string. Why do you want to store the information in yaml format?

 value: "{{structureItem.firstnames}} {{structureItem.lastnames}}"

And then output it as such.

Or if you need separate data:

value: "{{structureItem.lastnames}} - {{structureItem.firstnames}}"

In template:

$author = $page->author()->toData('-');
dump($author);

Gives you an array to loop through.

Array
(
    [0] => Simpson
    [1] => Maggie
)

Yes, was going to output them with commas and then split, “firstnames” and “lastnames” have their order implied in their names anyway :slight_smile:.

Didn’t know the toData() method, interesting. That will do it for now, no time for a custom field (probably all sorts of caveats there too).

Thanks for the suggestions!