Drupal - Cannot deal with multiple iterations of same form on one page

You could also add something like this to your form class

 /**
  * Keep track of how many times the form
  * is placed on a page.
  *
  * @var int
  */
protected static $instanceId;

/**
 * {@inheritdoc}
 */
public function getFormId() {
  if (empty(self::$instanceId)) {
    self::$instanceId = 1;
  }
  else {
    self::$instanceId++;
  }

  return 'my_form_id_' . self::$instanceId;
}

Yes, each form must have a unique form ID. See https://www.drupal.org/node/766146 and the comments there.

You need to find something that uniquely identifies each form and put that in the form ID.
As commented there, that can be a bit tricky as getFormId() is called very early, so you need to instantiate the form object yourself and pass it to the form builder.

See FormBuilder::getFormId() for what happens when you pass in a string, it is passed to $this->classResolver->getInstanceFromDefinition($form_arg);, that creates the object and uses the create() method if available, you can use that or just do it yourself with a new Object(), then pass that to getForm() instead.

Tags:

Forms

8