0
votes

I'm trying to create my own FormField and FieldHolder templates in Silverstripe v3.6.

I've created a FieldList called $Fields and then I loop over its fields to set the custom template on each:

    foreach($Fields->dataFields() as $field) {
        $type = $field->Type();
        // Field holder
        if ($type == "checkbox") {
          $field->setFieldHolderTemplate('CustomCheckboxField_holder');
        } else {
          $field->setFieldHolderTemplate('CustomFormField_holder');
        }
        // Field
        if ($type == "dropdown") {
          $field->setTemplate('CustomSelectField');
        } else if ($type == "optionset") {
          $field->setTemplate('CustomRadioField');
        } else if ($type == "checkbox") {
          $field->setTemplate('CustomCheckboxField');
        } else {
          $field->addExtraClass('custom-form-control');
        }
    }

I've placed the templates in mysite/templates/Includes, eg. CustomCheckboxField.ss drops the normal classes in favour of custom-control-input:

<input $getAttributesHTML("class") class="custom-control-input<% if extraClass %> $extraClass<% end_if %>" />

This works, but only if I include the default FormField.ss and FormField_holder.ss templates in the same folder (copied from framework/templates/forms).

Why do they need to be included, when I'm overriding them? Shouldn't Silverstripe fall back to the originals in the framework folder if they are required? Every one of the fields in my custom form has a custom template (except HeadingFields), so they shouldn't be needed.

I would like to know if I'm doing this correctly. Thank you!

1
You can enable source file comment hints via configuration on SSViewer to see which templates are being rendered and where. You're correct in that the templates you don't use will fall back to default (framework) versions.scrowler
Thanks @RobbieAverill, I can see a hidden field and the submit button in my form rely on the framework field templates I copied into /mysite/templates/Includes but did not rename/customise (FormField.ss, FormField_holder.ss, HeaderField.ss). If I remove those three templates, all the custom fields break. I also forgot to mention above that including any custom templates in this folder breaks the CMS. It seems Silverstripe looks for all other field templates in the same folder and gets confused if they aren't there.SalutBarbu

1 Answers

1
votes

Turns out my problem was due to an error in the documentation for v3.4 that had been picked up along the way. The directory for form field templates should be mysite/templates/forms (NOT Includes).

The answer was found here: SilverStripe custom FormField_Holder