Question

I try to input several forms into one page via Controller. With code which is under, I see those forms but after submit one of them, nothing happens. Any of data is send to database. Has anyone idea how to fix this?

<?php

namespace Drupal\Core\Entity\ContentEntityForm;
namespace Drupal\student\Controller;
use Drupal\node\Entity\Node;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\node\NodeInterface;
use Drupal\node\Entity;
use Drupal\node\NodeForm;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Url;
use Drupal\Core\Link;
use Drupal\Core\Routing;
use Drupal\Core\Entity\ContentEntityForm;

class SFormController extends ControllerBase {

  function new_form() { 
    
    $build = [];
  
    foreach ($stud as $id => $name) {
      
      $node = \Drupal\node\Entity\Node::create(['type' => 'student']);
      $form = \Drupal::service('entity.form_builder')->getForm($node, 'student_form');
      
      $build[] = $form;
    }   
    return $build;
  }
}

?>
Was it helpful?

Solution

You need to make the form ID dynamic, so that it is different for each instance on the page. As you're extending EntityForm, you'll have to extend it, then register your form on the node class, and finally call your form class.

  1. Extend the entity form:

    class MyEntityForm extends EntityForm {
      public function getFormId() {
        // The dynamic form ID allows for the form to be
        // reused on a page.
        return parent::getFormId() . '-' . $this->getEntity()->id();
      }
    }
    
  1. Register your form class on the node entity type:

    /**
     * Implements hook_entity_type_alter().
     */
    function HOOK_entity_type_alter(array &$entity_types) {
      $node = &$entity_types['node'];
      $node->setFormClass('my_form_type', 'Drupal\[MODULE]\Form\MyEntityForm');
    }
    
  2. Call your form from your controller:

      $form = \Drupal::service('entity.form_builder')->getForm($node, 'my_form_type');
    
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top