Problems with altering a form I'm wanting to alter the commerce cart page form.

By using var_dump($form_id) or chrome inspect I can see the id is id="views-form-commerce-cart-form-orange-default-42". If I write my hook as :

function module_form_views_form_commerce_cart_form_orange_default_42_alter


I can see that I am altering the form. But this has been altered in my theme hence the extra bit on the id orange_default_42. If I do :

function testingstuffs_form_views_form_commerce_cart_form_alter


I cannot alter the form.   

How do I hook into this form correctly / is there  a correct way to find form ids?
The issue here is that there are probably two form IDs for the form. One is the form_id, and the lesser known one is the base_form_id. If a Drupal form is used more than once on a page, weird things come about. To get around this, form developers can set the form ID to be dynamic, so that each time the form is built, it's given a unique ID. Example:

class FooBarForm implements FormInterface {

  protected $id;

  public function __construct($type) {
    $this-&gt;id = $id;
  }

  public function getFormId() {
    return 'foo_bar_form-' . $this-&gt;id;
  }
}

class FooRouteController {

  public function fooBarForm(ContentEntityInterface $entity) {
    $form = new FooBarForm($entity-&gt;id());

    return \Drupal::formBuilder()-&gt;getForm($form);
  }
}


Forms can also implement BaseFormIdInterface, which requires them to implement BaseFormIdInterface::getBaseFormId(). The form ID returned from this hook will be the same for all instances of the form, and NOT dynamic.

class FooBarForm implements FormInterface, BaseFormIdInterface {

  protected $id;

  public function __construct($type) {
    $this-&gt;id = $id;
  }

  public function getFormId() {
    return 'foo_bar_form-' . $this-&gt;id;
  }

  public function getBaseFormId() {
    return 'foo_bar_form';
  }
}


The relevance of this is that there are actually multiple form alter hooks called, in this order:


hook_form_alter()
hook_form_BASE_FORM_ID_alter()
hook_form_FORM_ID_alter()


Looking at your hook - module_form_views_form_commerce_cart_form_orange_default_42_alter, it would appear you are implementing the third hook. The ID of 42 is being appended as part of the dynamic Form ID.

To find out the base form ID (if one exists), you can call the following in your form:

$form_state-&gt;getBuildInfo()

This will give you the build info, which you can dump with kint() or however you do your debugging. In the build info will be the base form ID (assuming it's set). If it is, you can implement the second form alter hook above, using that base form ID.