Dynamically insert form in page

I’m looking for a way to insert a form to a page’s frontmatter from within a plugin

By looking at the code of the Grav Import Plugin I’ve managed to read the form definition in YAML format from a file and add it to the page header. The page HTML source contains the basic form outline because of the variable template: form but the form fields from the YAML file are missing.

Usually a form is defined right in the page’s frontmatter. By looking at a dump($page) output I can see the form definition from the file inside the header and also the page’s frontmatter version in the frontmatter:

#items: null
#header: {#230 ▼
  +"title": "Demo"
  +"template": "form"
  +"myplugin.merged": Data {#266 ▶}
  +"form": array:1 [▼
    "form" => array:4 [▼
      "name" => "my-custom-form"
      "fields" => array:1 [▼
        0 => array:7 [▼
          "name" => "content"
          "id" => "textarea1"
          "label" => "Page Content"
          "size" => "long" 
          "placeholder" => "Write your content here"
          "type" => "textarea"
          "validate" => array:1 [▶]
        ]
      ]
      "buttons" => array:1 [▶]
      "process" => array:1 [▶]
    ]
  ]
}
#frontmatter: """
  title: 'My Demo'

  template: form

  form:

      name: textarea-form

      name: my-default-form

      fields:

          -

              name: content

              id: textarea2

              label: 'Page Content'

              size: long

              placeholder: 'Write the content here'

              type: textarea

              validate:

                  required: true

      buttons:

          -

              type: submit

              value: Submit

              classes: null

      process:

          -

              addpage: null
  """
#language: "en"

Regarding terminology I have been confused by the meaning of ‘header’ and ‘frontmatter’. This confusion got even bigger when I searched the API
where I find:

array header( array $var = null)

Get/set file header.

Parameters
array	$var	
Return Value
array

and

string frontmatter( string $var = null)

Get/set frontmatter content.

Parameters
string	$var	
Return Value
string

My question is two fold:

  1. can someone explain the difference between header and frontmatter
  2. how can I add the form YAML to the page in order to get a working form

header() gets and sets a single variable, or the whole page header parsed in an array format.

frontmatter() gets and sets the YAML multi-line string that defines the page header.

As for the form… not sure if it’s even doable, as form processing could rely on the form being defined in the page header, not at runtime.

Thanks for the explanation. I keep trying :slight_smile: