Issue #3419186 by Ruturaj Chaubey, phthlaap, balintpekker, smustgrave: Add a hook_ENTITY_TYPE_form_mode_alter()

merge-requests/6779/merge
catch 2024-04-20 07:56:23 +01:00
parent cae640d345
commit 386e810b2b
4 changed files with 40 additions and 2 deletions

View File

@ -87,7 +87,11 @@ class EntityFormDisplay extends EntityDisplayBase implements EntityFormDisplayIn
$bundle = $entity->bundle();
// Allow modules to change the form mode.
\Drupal::moduleHandler()->alter('entity_form_mode', $form_mode, $entity);
\Drupal::moduleHandler()->alter(
[$entity_type . '_form_mode', 'entity_form_mode'],
$form_mode,
$entity
);
// Check the existence and status of:
// - the display for the form mode,

View File

@ -1877,6 +1877,23 @@ function hook_entity_form_mode_alter(&$form_mode, \Drupal\Core\Entity\EntityInte
}
}
/**
* Change the form mode of a specific entity type currently being displayed.
*
* @param string $form_mode
* The form_mode currently displaying the entity.
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity that is being viewed.
*
* @ingroup entity_crud
*/
function hook_ENTITY_TYPE_form_mode_alter(string &$form_mode, \Drupal\Core\Entity\EntityInterface $entity): void {
// Change the form mode for nodes with 'article' bundle.
if ($entity->bundle() == 'article') {
$form_mode = 'custom_article_form_mode';
}
}
/**
* Alter the settings used for displaying an entity form.
*

View File

@ -819,3 +819,12 @@ function entity_test_query_entity_test_access_alter(AlterableInterface $query) {
$query->condition('entity_test_query_access.name', 'published entity');
}
}
/**
* Implements hook_ENTITY_TYPE_form_mode_alter().
*/
function entity_test_entity_test_form_mode_alter(&$form_mode, EntityInterface $entity): void {
if ($entity->getEntityTypeId() === 'entity_test' && $entity->get('name')->value === 'test_entity_type_form_mode_alter') {
$form_mode = 'compact';
}
}

View File

@ -73,9 +73,10 @@ class EntityFormTest extends BrowserTestBase {
}
/**
* Tests hook_entity_form_mode_alter().
* Tests hook_entity_form_mode_alter() and hook_ENTITY_TYPE_form_mode_alter().
*
* @see entity_test_entity_form_mode_alter()
* @see entity_test_entity_test_form_mode_alter()
*/
public function testEntityFormModeAlter() {
// Create compact entity display.
@ -107,6 +108,13 @@ class EntityFormTest extends BrowserTestBase {
$entity2->save();
$this->drupalGet($entity2->toUrl('edit-form'));
$this->assertSession()->elementNotExists('css', 'input[name="field_test_text[0][value]"]');
$entity3 = EntityTest::create([
'name' => 'test_entity_type_form_mode_alter',
]);
$entity3->save();
$this->drupalGet($entity3->toUrl('edit-form'));
$this->assertSession()->elementNotExists('css', 'input[name="field_test_text[0][value]"]');
}
/**