Ad hoc form field data with setSchemaData

Silverstripe Version: 5

Question:

I’m trying to send some data to a custom form field template in a front end form but I can’t access the data.

On an OptionsetField I have

OptionsetField::create('MyField', 'Label', DataObject::get()->map())
   ->setSchemaData(['data' => ['myCustomKey' => 'yolo']])
   ->setTemplate('Forms/CustomOptionsetField'),

The code comment in FormField for setSchemaData:

If you want to pass around ad hoc data use the data array e.g. pass ['data' => ['myCustomKey' => 'yolo']]

In the CustomOptionsetField blade template I’ve tried:

$myCustomKey
$data.myCustomKey
$getSchemaData.myCustomKey
$getSchemaData.data.myCustomKey

I’m not yolo’ing anywhere.

Schema data is used “to render the FormField as a ReactJS Component on the front-end” and is not suitable for use in templates. I’m not sure why the property has that extra detail in the PHPDoc and that method doesn’t, but in any case you’ll need another way to do what you’re trying to do.

If the intention is to render a data attribute in the field, you can use setAttribute().
Alternatively since FormField is a subclass of ViewableData you could use setDynamicData() - anything you add via that method should be accessible as properties in the template.

Okay, Thank you for the reply!

This:

->setDynamicData('myCustomKey', 'yolo')

does work.

Out of interest, why doesn’t customise?

->customise(['myCustomKey' => 'yolo'])

Customise is also in ViewableData. No errors, no value.

Customise doesn’t work in a way that would be suitable for your use case.
See https://docs.silverstripe.org/en/5/developer_guides/templates/rendering_templates/ and https://docs.silverstripe.org/en/5/developer_guides/controllers/introduction/ for more information about how that method is used.

But it does on the form class… Weird. Is there not a standardised way to add arbitrary data to a templete then or are form field classes just different?