1. Регистрируем роут:
# modulename.routing.yml
entity.node.my_action:
path: '/node/{node}/my-action'
defaults:
_form: '\Drupal\modulename\Form\MyActionForm'
_title: 'My action'
requirements:
_permission: 'administer site configuration'
options:
_admin_route: TRUE
2. Создаём контроллер или форму:
<?php
// src/Form/MyAction.php
namespace Drupal\modulename\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\NodeInterface;
class MyActionForm extends FormBase {
/**
* {@inheritDoc}
*/
public function getFormId(): string {
return 'my_action_form';
}
/**
* {@inheritDoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL): array {
$form['actions'] = [
'#type' => 'actions',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Confirm'),
];
return $form;
}
/**
* {@inheritDoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state): void {
$node = $form_state->getBuildInfo()['args'][0]; /** @var NodeInterface $node */
...
}
}
3. Добавляем действие в ссылки:
// modulename.module
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Url;
/**
* Implements hook_entity_operation().
*/
function modulename_entity_operation(EntityInterface $entity): ?array {
if ($entity->getEntityTypeId() == 'node') {
$operations = [];
$operations['my_action'] = [
'title' => t('My action'),
'url' => Url::fromRoute('entity.node.my_action', ['node' => $entity->id()], ['query' => \Drupal::destination()->getAsArray()]),
'weight' => 100,
];
return $operations;
}
return NULL;
}
Написанное актуально для
Drupal 8+
Добавить комментарий