How can I change a form input to not be required? I want to change a form from required = True to False

&lt;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"&gt;


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 :

&lt;?php 

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

function alt_not_required_form_alter(array &amp;$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' =&gt; FALSE,
    );
  }
}
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(&amp;$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.