Drupal 9 image field migration

The problem is to add multiple times the same form on the page and process them. You can try to do it, but submitForm will be initiated for all forms, since they have the same id.
By default you can try to add the form in this way, but for builder form_id will be already present.

$form['multiple_form'] = \Drupal::formBuilder()->getForm('Drupal\my_module\Form\MyForm');

The idea is to create custom method, to which we'll pass an ID. And edit getFormId() method. The lines below should be added to your Form class.

private $custom_id;
  
public function getFormId(){
  return 'my_module_form_' . $this->custom_id;
}
public function setCustomId($id) {
  $this->custom_id = $id;
}

And now we can get instance of our Form class and add the ID in loop.

$formObject = \Drupal::service('class_resolver')->getInstanceFromDefinition('Drupal\my_module\Form\MyForm');

$formObject->setCustomId($id);
$formRenderable = \Drupal::formBuilder()->getForm($formObject);

$form['multiple_form'] = $form_renderable;

Add new comment

The content of this field is kept private and will not be shown publicly.
  • No HTML tags allowed.