Drupal 8 Custom form display Modes

ok to get custom form display modes working in your module .... after some time of messing with this I seem to have it working:
and here is how...

1) create your form display and get id from url
at :admin/structure/display-modes/form/manage/

"Test This" gives m name ... node.test_this

in your modules
my_module.routing.yml

#admin/structure/display-modes/form/manage/node.test_this
#node.test_this is the name !
my_module.test_this:
 path: '/some-path/{node}/test_this'
 defaults:
   _entity_form: node.test_this
 requirements:
   _permission: 'some perm'

#Symfony\Component\Routing\Exception\RouteNotFoundException: Route "entity.node.test_this" fix
#when you go to www.site.com/node/NID  or save from your form mode
#yes you need this !!!!!! or you will have a bad time try with out lol!
entity.node.test_this:
 path: 'node/{node}'
 defaults:
  _controller: '\Drupal\node\Controller\NodeViewController::view'
 requirements:
   _permission: 'access content'

.... now in your module
my_module.module

/**
 * Implements hook_entity_type_alter().
 * inspiration from  form_mode_manager_entity_type_alter (THANK YOU !!!). 
 */
function my_module_entity_type_alter(array &$entity_types) {
  $form_modes = \Drupal::service('entity_display.repository')->getAllFormModes();
  foreach ($form_modes as $entity_type => $display_modes) {
    /* @var \Drupal\Core\Entity\EntityTypeInterface $entity */
    $entity = $entity_types[$entity_type];
    foreach ($display_modes as $machine_name => $form_display) {
      if ($machine_name != 'register') {
        // Get the correct canonical path to add operation.
        $path = $entity->getLinkTemplate('canonical') . "/$machine_name";
        $default_handler_class = $entity->getHandlerClasses()['form']['default'];
        $entity->setFormClass($machine_name, $default_handler_class)
          ->setLinkTemplate($machine_name, $path);
      }
    }
  }
}

function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  //dump($form_id);
}

now you can go to the path www.site.com/some-path/{nodeID}/test_this
and try to not have your chin hit the floor.

the cool thing as it gives a new form id to then alter

Category: