custom_add_content-8.x-1.2/custom_add_content.module
custom_add_content.module
<?php
/**
* @file
* Custom add content.
*/
use Drupal\Core\Form\FormStateInterface;
use Drupal\menu_link_content\Entity\MenuLinkContent;
/**
* Implements hook_form_alter().
*
* When a new content type is created/edited/deleted we must update menu.
* The rebuild action is automatically triggered by core on CT alter.
*/
function custom_add_content_form_alter(&$form, FormStateInterface $form_state, $form_id) {
switch ($form_id) {
case 'node_type_add_form':
$form['actions']['submit']['#submit'][] = 'custom_add_content_new_node_type_add';
break;
case 'node_type_delete_form':
// Our handler goes first.
array_unshift($form['actions']['submit']['#submit'], 'custom_add_content_new_node_type_rem');
break;
default:
break;
}
}
/**
* Custom submit handler for node type adding. We add a menu item.
*/
function custom_add_content_new_node_type_add($form, FormStateInterface $form_state) {
try {
$values = $form_state->getValues();
$item = MenuLinkContent::create([
'title' => $values['name'],
'link' => ['uri' => 'internal:/node/add/' . $values['type']],
'menu_name' => 'custom-add-content-page',
'expanded' => TRUE,
]);
$item->save();
}
catch (Exception $e) {
\Drupal::logger('custom_add_content')->notice($e->getMessage());
}
}
/**
* Custom submit handler for node type remove.
*
* We remove the corresponding menu item.
*/
function custom_add_content_new_node_type_rem($form, FormStateInterface $form_state) {
try {
$path = \Drupal::service('path.current')->getPath();
$parts = explode('/', $path);
$ct_machine_name = $parts[5];
if (!empty($ct_machine_name)) {
$menu = Drupal::entityTypeManager()
->getStorage('menu_link_content')
->loadByProperties(['link__uri' => 'internal:/node/add/' . $ct_machine_name]);
if (!empty($menu)) {
$first = array_values($menu)[0];
$first->delete();
}
}
}
catch (Exception $e) {
\Drupal::logger('custom_add_content')->notice($e->getMessage());
}
}
/**
* Implements hook_theme().
*
* Custom twig template.
*/
function custom_add_content_theme() {
return [
'custom_add_content_page_add' => [
'variables' => ['menu_name' => NULL, 'items' => NULL],
],
];
}
