1

I've seen a tutorial about enhancing Drupal's elements using Vue.js validation component. The input markup is like this:

<input class="username form-text required" autocapitalize="none" type="text" id="edit-name" name="name" value="" size="60" maxlength="60" v-model="name" v-validate.initial="name" data-rules="required|alpha|min:3"> 
<input type="text" id="edit-mail" name="mail" value="" size="60" maxlength="254" class="form-text required" v-model="mail" v-validate.initial="email" data-rules="required|email">

But how do I add the Vue.js custom attributes to these input field?

1

I suppose you only want to add Vue specific attributes to certain form elements, not every single one of them (including admin/backend forms).

Presuming you are using Drupal 8, I'd recommend enabling Twig debugging. That will help you to identify which fields you want to alter.

Once twig debugging is enabled Drupal should expose theming details for each element. In your case you need to know about template and hook names.

Chrome DevTools

The input field shown in the screenshot is using input.html.twig template file from core/themes/classy/templates/form/input.html.twig, and theme hook is input__textfield

For your specific question, I recommend adding those attributes via preprocess hooks in your theme. For example;

<?php
function YOURTHEME_preprocess_input__textfield(&$variables) {
  $element = $variables['element'];

  if ($element['#name'] === 'title') {
    $variables['attributes']['autocapitalize'] = 'none';
    $variables['attributes']['v-model'] = 'name';
    $variables['attributes']['v-validate.initial'] = 'name';
    $variables['attributes']['data-rules'] = 'required|alpha|min:3';
  }
}

My example above is NOT very specific, it only alters "textfields" with the name "title". I recommend targeting more specific form elements.

  • Thank you very much for your answer. I am using Drupal 7, but I get the general idea of your answer. I'll try this using D7. – montesajudy Apr 10 '18 at 7:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.