Craft CMS {{ input }} Tag

January 2023

Craft CMS {{ input }} Tag

Craft CMS makes front end entry forms so easy. I like that you specify the section id and throw up the fields. If you're updating an existing entry make sure to include

{{ hiddenInput('entryId', }}

It all comes together pretty fast.

But I recently was working on a site where the purchased theme had ARIA attributes everywhere. There must be some way to include that in the twig {{ input }} tag. And data attributes too! There must be some way to add data attributes.

As much as I like working with Craft CMS I sometimes it difficult to find the information I'm looking for in their documentation. It could be because "input" and "aria" are pretty generic in the web development world so there were lots of google search results. It could be because Craft CMS templating is based on twig so should I be looking in the Craft CMS site or the twig site for my answers?

Let me take you on a little trip that eventually gave me the answer I was looking for. After a bunch of failed google searches I finally found the right search term "craftcms input aria". There were many links for how Craft CMS had made their backend more accessible but was also a link for craft\helpers\Html | Craft 3 Class Reference. No, I didn't actually want the php equivalent but if it gives me a place to look next I'd better check it out. The page is a long list of methods to help make html tags including a hyperlink tag, a list of radio buttons, and a label tag. Scrolling down a found my input tag.

The input() method lists parameters that look a lot like the {{ input }} tag:


public static string input ( $type, $name = null, $value = null, $options = [] )


{{ input('text', 'title', entry.title, {
 id: 'title',
}) }}

So type = text, name = title, value = entry.title and options is an object. The next step is learning more about how the options work which finally lead me to renderTagAttributes(). Here's the good stuff:

aria and data attributes get special handling when they are set to an array value. In these cases, the array will be "expanded" and a list of ARIA/data attributes will be rendered. For example, 'aria' => ['role' => 'checkbox', 'value' => 'true'] would be rendered as aria-role="checkbox" aria-value="true".

Change all the php arrays to my twig objects and the final template code is

{{ input('text', modelName ~ '[firstName]', model ? model.firstName : '', {
 id: modelName ~ '-firstName',
 required: true,
 aria: {'required': 'true'},
 class: 'form-control'
}) }}

Which gives me exactly what I want on the front end.