-
-
Save bangpound/8a3fe1a997e6c5643fad624da20e3439 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Implements hook_form_FORM_ID_alter(). | |
* | |
* Modifies the content form for page manager variants to add an "edit content" | |
* link on blocks that are entities. | |
* | |
* @param $form | |
* @param $form_state | |
*/ | |
function caxy_form_page_manager_block_page_content_alter(&$form, &$form_state) { | |
// Identify the form elements that refer to blocks. These children all have a | |
// key that is a UUID. Filter out non-UUIDs. The array key stays the same. | |
/** @var array $uuids */ | |
$uuids = array_filter(Element::children($form['blocks']), [Uuid::class, 'isValid']); | |
if (!empty($uuids)) { | |
/** @var EntityRepositoryInterface $repository */ | |
$repository = \Drupal::service('entity.repository'); | |
// Load all of the entities in this page variant. The array keys will be | |
// the same as in the source array $uuids. | |
/** @var EntityInterface[] $entities */ | |
$entities = array_filter(array_map(function ($uuid) use ($repository, $form) { | |
$args = explode(':', $form['blocks'][$uuid]['id']['#markup'], 2); | |
if (count($args) !== 2) { | |
return FALSE; | |
} | |
return call_user_func_array([$repository, 'loadEntityByUuid'], $args); | |
}, $uuids)); | |
// Loop through each UUID and use the entity at the same index in $entities | |
// to generate an `edit-form` link. This link opens in a new window because | |
// modal entity forms are hard. | |
foreach (array_intersect_key($uuids, $entities) as $k => $v) { | |
/** @var EntityInterface $entity */ | |
$entity = $entities[$k]; | |
// Using `array_merge` allows the edit content link to be first in the | |
// operations list. | |
$form['blocks'][$v]['operations']['#links'] = array_merge([ | |
'edit-content' => [ | |
'title' => 'Edit content', | |
'url' => $entity->toUrl('edit-form'), | |
'attributes' => [ | |
'rel' => 'noopener noreferrer', | |
'target' => '_blank', | |
], | |
] | |
], $form['blocks'][$v]['operations']['#links']); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment