Skip to content
● Meet Grav Guard: keep every Grav site you run secure and up to date, all from one place. Free for up to 3 sites. Read more →

Generate select options in a form

Started by Muut Archive 11 years ago · 4 replies · 1558 views
11 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!

11 years ago

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

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

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

11 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 Muut Archive, 10 years ago
1 676 1 week ago
Archive · by Deleted User, 9 years ago
0 3043 9 years ago
Archive · by Muut Archive, 9 years ago
2 1983 9 years ago
Archive · by Muut Archive, 9 years ago
2 5338 9 years ago
Archive · by Muut Archive, 9 years ago
1 4135 9 years ago