I want to change a form from required = True to False

<input data-drupal-selector="edit-attributes-alt" type="text" id="edit-attributes-alt--SMq1dTLhZG8" name="attributes[alt]" value="" size="60" maxlength="2048" placeholder="" class="form-text required" required="required" aria-required="true">

I thought that using form alter is the right thing to do but how can i use the $form_id if keeps changing ?

Here is my code :


use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\HttpFoundation\Request;

function alt_not_required_form_alter(array &$form, FormStateInterface $form_state, $data_drupal_selector) {
  if ($form_id == 'edit-attributes-alt--????') {
    $form['postal'] = array(
      // Don't make this field required. Use the validate hook.
      '#required' => FALSE,
  • This isn't an image widget by chance? alt sounds like an image alt text, and those are configurable in the UI. the form structure doesn't quite match that, though – Berdir Feb 24 '17 at 16:31

The third argument to hook_form_alter is $form_id - which will hold the id of the form, not an attribute. You need to know the form id of what you are trying to alter, which is not the literal id of a form input field.

Once you identify what form is showing this field, you can do:

function alt_not_required_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'form_id_foo') {
    $form['input_to_affect']['#required'] = FALSE;

Also, once you know what the form ID is, you can use hook_form_FORM_ID_alter and eliminate that if statement.

Plus, in your example, since we are altering existing form elements, you do not need to declare it as an array. You just access its properties. $form['postal'] = array(...) would take any existing form item named 'postal' and obliterate it, which will likely cause errors in validation or submission.

It might be helpful in learning to use xdebug or devel to dump arguments and variables so you can see what they are. Otherwise, it will be difficult for you to step through this.


This is the solution thanks to you all :

function alt_not_required_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'editor_image_dialog' ) {
$form['attributes']['alt']['#required'] = FALSE;

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.