View source
<?php
namespace Drupal\add_content_by_bundle\Plugin\views\area;
use Drupal\Component\Serialization\Json;
use Drupal\Component\Utility\Html;
use Drupal\Core\Access\AccessManagerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Routing\RedirectDestinationTrait;
use Drupal\Core\Url;
use Drupal\views\Plugin\views\area\AreaPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
class AddContentByBundle extends AreaPluginBase {
use RedirectDestinationTrait;
protected $accessManager;
public function __construct(array $configuration, $plugin_id, $plugin_definition, AccessManagerInterface $access_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->accessManager = $access_manager;
}
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static($configuration, $plugin_id, $plugin_definition, $container
->get('access_manager'));
}
protected function defineOptions() {
$options = parent::defineOptions();
$options['bundle'] = [
'default' => NULL,
];
$options['label'] = [
'default' => NULL,
];
$options['class'] = [
'default' => NULL,
];
$options['target'] = [
'default' => '',
];
$options['width'] = [
'default' => '600',
];
$options['form_mode'] = [
'default' => NULL,
];
$options['params'] = [
'default' => '',
];
return $options;
}
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
parent::buildOptionsForm($form, $form_state);
$entity_type = $this->view
->getBaseEntityType()
->id();
$bundles = \Drupal::service('entity_type.bundle.info')
->getBundleInfo($entity_type);
$bundlesList = [];
foreach ($bundles as $id => $bundle) {
$label = $bundle['label'];
$bundlesList[$id] = $label;
}
$form['bundle'] = [
'#title' => $this
->t('Add content bundle (Content) type'),
'#description' => $this
->t('The bundle (content) type of content to add.'),
'#type' => 'select',
'#options' => $bundlesList,
'#default_value' => !empty($this->options['bundle']) ? $this->options['bundle'] : '',
'#required' => TRUE,
];
if (\Drupal::service('module_handler')
->moduleExists('form_mode_control')) {
$form_modes = \Drupal::service('entity_display.repository')
->getFormModeOptions($entity_type);
if ($form_modes && is_array($form_modes) && count($form_modes) > 1) {
$form['form_mode'] = [
'#title' => $this
->t('Form mode'),
'#description' => $this
->t('The form mode to use for adding an entity.'),
'#type' => 'select',
'#options' => $form_modes,
'#default_value' => !empty($this->options['form_mode']) ? $this->options['form_mode'] : '',
];
}
}
$form['label'] = [
'#title' => $this
->t('Label'),
'#description' => $this
->t('The text of the link.'),
'#type' => 'textfield',
'#default_value' => $this->options['label'] ?: $this
->t('Add a new entry'),
'#required' => TRUE,
];
$form['class'] = [
'#title' => $this
->t('Class'),
'#description' => $this
->t('A CSS class to apply to the link. If using multiple classes, separate them by spaces.'),
'#type' => 'textfield',
'#default_value' => $this->options['class'],
];
$form['target'] = [
'#title' => $this
->t('Target'),
'#description' => $this
->t('Optionally have the form open on-page in a modal or off-canvas dialog.'),
'#type' => 'select',
'#default_value' => $this->options['target'],
'#options' => [
'' => $this
->t('Default'),
'tray' => $this
->t('Off-Screen Tray'),
'modal' => $this
->t('Modal Dialog'),
],
];
$form['width'] = [
'#title' => $this
->t('Dialog Width'),
'#description' => $this
->t('How wide the dialog should appear.'),
'#type' => 'number',
'#min' => '100',
'#default_value' => $this->options['width'],
'#states' => [
'invisible' => [
':input[name="options[target]"]' => [
'value' => '',
],
],
],
];
$form['params'] = [
'#title' => $this
->t('Additional Parameters'),
'#description' => $this
->t('List any additional paramters, separating the key and value with a pipe (|). The use of tokens for the view\'s arguments is supported. An example is {{ arguments.user_id }}.'),
'#type' => 'textarea',
'#default_value' => $this->options['params'],
];
}
public function validate() {
$errors = parent::validate();
if ($this->options['form_mode']) {
$entity_type = $this->view
->getBaseEntityType()
->id();
$form_modes = \Drupal::service('entity_display.repository')
->getFormModeOptionsByBundle($entity_type, $this->options['bundle']);
if (!isset($form_modes[$this->options['form_mode']])) {
$errors[] = $this
->t('%current_display: The %form_mode form display is not defined for the %bundle type.', [
'%current_display' => $this->displayHandler->display['display_title'],
'%form_mode' => $this->options['form_mode'],
'%bundle' => $this->options['bundle'],
]);
return $errors;
}
}
}
public function render($empty = FALSE) {
$account = \Drupal::currentUser();
if ($empty && empty($this->options['bundle'])) {
return [];
}
$bundle_type = $this->options['bundle'];
$entity_type = $this->view
->getBaseEntityType();
$params = $this
->getDestinationArray();
if (\Drupal::service('module_handler')
->moduleExists('form_mode_control') && ($form_mode = $this->options['form_mode'])) {
$params['display'] = $form_mode;
}
if ($this->options['params']) {
$this
->extractParams($params, $this->options['params']);
}
if ($entity_type
->id() === 'node') {
$url = Url::fromRoute('node.add', [
'node_type' => $bundle_type,
], [
'query' => $params,
]);
$access = $this->accessManager
->checkNamedRoute('node.add', [
'node_type' => $bundle_type,
], $account);
}
elseif ($entity_type
->id() === 'taxonomy_term') {
$url = Url::fromRoute('entity.taxonomy_term.add_form', [
'taxonomy_vocabulary' => $bundle_type,
], [
'query' => $params,
]);
$access = $this->accessManager
->checkNamedRoute('entity.taxonomy_term.add_form', [
'taxonomy_vocabulary' => $bundle_type,
], $account);
}
else {
$entity_links = $entity_type
->get('links');
if (isset($entity_links['add-form'])) {
$path = preg_replace('/\\{[_a-z]+\\}/', $bundle_type, $entity_links['add-form']);
}
elseif (isset($entity_links['add-page'])) {
$path = str_replace('{' . $entity_type
->id() . '}', $bundle_type, $entity_links['add-page']);
}
if (empty($path)) {
return;
}
$path = 'internal:' . $path;
$url = Url::fromUri($path, [
'query' => $params,
]);
$route_name = $url
->getRouteName();
$route_parameters = $url
->getrouteParameters();
$access = $this->accessManager
->checkNamedRoute($route_name, $route_parameters, $account);
}
if ($this->options['class']) {
$classes = explode(' ', $this->options['class']);
foreach ($classes as $index => $class) {
$classes[$index] = Html::getClass($class);
}
}
else {
$classes = [];
}
$element = [
'#type' => 'link',
'#title' => $this->options['label'],
'#url' => $url,
'#options' => [
'attributes' => [
'class' => $classes,
],
],
'#access' => $access,
];
if ($this->options['target']) {
$element['#options']['attributes']['class'][] = 'use-ajax';
$width = $this->options['width'] ?: 600;
$element['#options']['attributes']['data-dialog-options'] = Json::encode([
'width' => $width,
]);
switch ($this->options['target']) {
case 'tray':
$element['#options']['attributes']['data-dialog-renderer'] = 'off_canvas';
$element['#options']['attributes']['data-dialog-type'] = 'dialog';
break;
case 'modal':
$element['#options']['attributes']['data-dialog-type'] = 'modal';
break;
}
}
return $element;
}
protected function extractParams(array &$params, $input) {
$list = explode("\n", $input);
$list = array_map('trim', $list);
$list = array_filter($list, 'strlen');
$display = $this->view
->getDisplay();
$tokens = $display
->getArgumentsTokens();
foreach ($list as $text) {
$matches = [];
if (preg_match('/(.*)\\|(.*)/', $text, $matches)) {
$key = trim($matches[1]);
$value = trim($matches[2]);
}
elseif (strlen($text) <= 255) {
$key = $value = $text;
}
if ($tokens) {
$value = $display
->viewsTokenReplace($value, $tokens);
}
$params[$key] = $value;
}
}
}