2

Let's say I have a simple form with some id like myform. This form has field called Mobile number with id mobile_number.If a user enter mobile number less than 10, it will prompt error like It must be 10 digits.

Form validation snippet:

public function validateForm(array &$form, FormStateInterface $form_state) {

  if (strlen($form_state->getValue('mobile_number')) < 10) {
    $form_state->setErrorByName('mobile_number', $this->t('It must be 10 digits.'));
  }

}

On inspect I found something like below markups

<div class="messages__wrapper layout-container">
      <div class="messages messages--error" aria-label="Error message" role="contentinfo">
      <div role="alert">
              <h2 class="visually-hidden">Error message</h2>
                It must be 10 digits.
            </div>
  </div>


</div>

I want to manipulate markups in either of two scenarios:

1) For whole website

2) Only for form with id myform.

How can I achieve that?

I am using 8.1.3

1

You can use this twig to theme the status message:

status-messages.html.twig

{#
/**
 * @file
 * Default theme implementation for status messages.
 *
 * Displays status, error, and warning messages, grouped by type.
 *
 * An invisible heading identifies the messages for assistive technology.
 * Sighted users see a colored box. See http://www.w3.org/TR/WCAG-TECHS/H69.html
 * for info.
 *
 * Add an ARIA label to the contentinfo area so that assistive technology
 * user agents will better describe this landmark.
 *
 * Available variables:
 * - message_list: List of messages to be displayed, grouped by type.
 * - status_headings: List of all status types.
 * - display: (optional) May have a value of 'status' or 'error' when only
 *   displaying messages of that specific type.
 * - attributes: HTML attributes for the element, including:
 *   - class: HTML classes.
 *
 * @ingroup themeable
 */
#}
{% for type, messages in message_list %}
  <div role="contentinfo" aria-label="{{ status_headings[type] }}"{{ attributes|without('role', 'aria-label') }}>
    {% if type == 'error' %}
      <div role="alert">
    {% endif %}
      {% if status_headings[type] %}
        <h2 class="visually-hidden">{{ status_headings[type] }}</h2>
      {% endif %}
      {% if messages|length > 1 %}
        <ul>
          {% for message in messages %}
            <li>{{ message }}</li>
          {% endfor %}
        </ul>
      {% else %}
        {{ messages|first }}
      {% endif %}
    {% if type == 'error' %}
      </div>
    {% endif %}
  </div>
{% endfor %}

I'm not sure, if you can get the form id in this template. But you can try to narrow down the kind of error message and make the modifications to this twig conditional.

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.