Dynamic Select field in Frontend Form

Hey there,

I’m trying to fill a select field with dynamic options, like pages from a certain subfolder, but it does not seem to work in frontend forms.

  name: contact
    - name: Name
      type: text
      label: "Your Name"
    - name: Recipient
      type: select
      label: "send to"
      '@data-options': '\Grav\Theme\MyOwnTheme::getRecipients'

So is there a way to populate a select with dynamic options? Or is it possible to create a complete custom Form-Field-Type?

What version of Grav are you using? If I recall correctly, Twig variables will be available in FrontMatter in 1.1 (which is in Beta currently).

Ok, sounds good! But I’m using version 1.0.10 and a Beta is not an option for this project. Think I’m going to write a for this if there is no other way.

You can call a static method from the YAML definition of a form even in Grav 1.0.

See this example to get the available Timezones in the system/blueprints/system.yaml - https://github.com/getgrav/grav/blob/develop/system/blueprints/config/system.yaml#L59

And the corresponding static function it calls in Utils: https://github.com/getgrav/grav/blob/develop/system/src/Grav/Common/Utils.php#L363-L387

That’s exactly what I have tried, but it does not seem to work in the frontend with the form plugin. I even tried to use that example and added the following to my form frontmatter in the form.md file

  name: 'MyForm'
    - name: timezone
      type: select
      size: medium
      classes: fancy
      data-options@: '\Grav\Common\Utils::timezones'
      default: ''
        '': 'Default (Server Timezone)'

The result is, that the select input is shown, but only has one option: 'Default (Server Timezone)'
Also the label is not shown, and i tried to use the key ‘data-options@’, as in your given example, as well as ‘@data-options’ li in my systems system.yaml

So I guess, this does not work in frontend forms. Can anybody reproduce that behavior?

I have Grav 1.1.3 and can’t get a select field to dynamically populate from my theme.

data-options@: ‘\Grav\Theme\MyGravTheme::getElementSizeOptions’

public static function getElementSizeOptions() {
    $sizes = [
      'full' => 'Full Width',
      'eighty' => '80%',
      'sixty' => '60%',
      'half' => '50%',
      'forty' => '40%'
    return $sizes;

The frontend theme class is probably not loaded in the admin (it is in the frontend). Can you put this in a plugin instead?

I have the same problem as timbo in a front-end form, can’t populate even from

data-options@: ‘\Grav\Common\Utils::timezones’

Also tried from my own plugin, doesn't populate either

data-options@: ‘\Grav\Plugin\MyPlugin::myutil’

Just updated to last version of Grav. Is there another way of doing this?

I finally solved this by writing a simple Plugin, so build the form “by-hand” and so populate the select boxes direct in the twig template.