Skip to content
Grav 2.0 is officially stable. Read the announcement →
Archive

Generate select options in a form

Started by Muut Archive 10 years ago · 4 replies · 1375 views
10 years ago

Hello.
I am trying to get a dynamic list of subpages in a form <select> field.

Here’s an extract of what I’m trying to write in the frontmatter:

YAML
content:
    items: @self.children
form:
    name: select-a-page
    fields:
        -
            name: page
            label: 'What page?'
            type: select
            options:
                '{% for p in page.collection %},{{ p.slug }}:{{ p.title }},{% endfor %}'
            validate:
                required: true

But it gets an Invalid frontmattererror when saving. How can I do this?

Thanks!

10 years ago

Nevermind for the Invalid, it was something else. It does save, but the selector is empty.

10 years ago

There's no way to do what you are trying to do. The problem is that even if you enable Twig processing in frontmatter: pages: frontmatter: process_twig: true (in system.yaml), when that runs the collection defined by the content items has not been processed.

The way you should do dynamic options is to call a static function.

You can put this function in a plugin or even in your theme. You just need to reference it adaquately.

10 years ago

Hi, thank you a lot for your answer, I will look into this.
What would the function look like? I understand how to call it, but not exactly how to write it.

10 years ago

It just needs to return a PHP array in a name/value format. e.g.

JS

$options = [
  'option-a' => 'Option A',
  'option-b' => 'Option B'
];

return $options;
---

Suggested topics

Topic Participants Replies Views Activity
Archive · by Deleted User, 9 years ago
0 1366 9 years ago
Archive · by Muut Archive, 9 years ago
2 940 9 years ago
Archive · by Muut Archive, 9 years ago
2 4069 9 years ago
Archive · by Muut Archive, 9 years ago
1 2960 9 years ago
Archive · by Muut Archive, 9 years ago
3 1124 9 years ago