You are here

class AddContentByBundle in Add Content by Bundle Views Area Plugin 1.x

Defines an area plugin to display a bundle-specific node/add link.

Plugin annotation

@ViewsArea("add_content_by_bundle");

Hierarchy

Expanded class hierarchy of AddContentByBundle

File

src/Plugin/views/area/AddContentByBundle.php, line 21

Namespace

Drupal\add_content_by_bundle\Plugin\views\area
View source
class AddContentByBundle extends AreaPluginBase {
  use RedirectDestinationTrait;

  /**
   * The access manager.
   *
   * @var \Drupal\Core\Access\AccessManagerInterface
   */
  protected $accessManager;

  /**
   * Constructs a new plugin instance.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin ID for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Access\AccessManagerInterface $access_manager
   *   The access manager.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, AccessManagerInterface $access_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->accessManager = $access_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('access_manager'));
  }

  /**
   * {@inheritdoc}
   */
  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;
  }

  /**
   * {@inheritdoc}
   */
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);

    // Use the entity_type defined for the view.
    $entity_type = $this->view
      ->getBaseEntityType()
      ->id();

    // Get all bundle types for our entity type.
    $bundles = \Drupal::service('entity_type.bundle.info')
      ->getBundleInfo($entity_type);

    // Assembled an options list of the bundles.
    $bundlesList = [];
    foreach ($bundles as $id => $bundle) {
      $label = $bundle['label'];
      $bundlesList[$id] = $label;
    }

    // New content bundle type.
    // TODO: preselect if a single bundle specified for the view?
    $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 the Form Mode Control module is installed, expose an option to use it.
    if (\Drupal::service('module_handler')
      ->moduleExists('form_mode_control')) {
      $form_modes = \Drupal::service('entity_display.repository')
        ->getFormModeOptions($entity_type);

      // Only expose the form element if our entity type has more than one
      // form mode.
      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' => [
        // Show this number field only if a dialog is chosen above.
        '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'],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function validate() {
    $errors = parent::validate();

    // Validate that the specified form mode exists for the specified bundle.
    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;
      }
    }
  }

  /**
   * {@inheritdoc}
   */
  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();

    // Assemble query params.
    $params = $this
      ->getDestinationArray();

    // If set, add form_mode to URL.
    if (\Drupal::service('module_handler')
      ->moduleExists('form_mode_control') && ($form_mode = $this->options['form_mode'])) {
      $params['display'] = $form_mode;
    }

    // If configured to add params, parse into our array.
    if ($this->options['params']) {
      $this
        ->extractParams($params, $this->options['params']);
    }

    // Try to be entity-type agnostic.
    if ($entity_type
      ->id() === 'node') {

      // Link to add a node of the specified type, then return to our view.
      $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') {

      // Link to add a term of the specified type, then return to our view.
      $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 {

      // Try to get the entity creation path.
      $entity_links = $entity_type
        ->get('links');
      if (isset($entity_links['add-form'])) {

        // Replace the bundle token with the specified value.
        $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)) {

        // An entity we don't know how to process, so exit.
        // TODO: throw a warning?
        return;
      }

      // Prepend the path to make a valid internal URI.
      $path = 'internal:' . $path;
      $url = Url::fromUri($path, [
        'query' => $params,
      ]);

      // Now use the URL to check access.
      $route_name = $url
        ->getRouteName();
      $route_parameters = $url
        ->getrouteParameters();
      $access = $this->accessManager
        ->checkNamedRoute($route_name, $route_parameters, $account);
    }

    // Parse and sanitize provided classes.
    if ($this->options['class']) {
      $classes = explode(' ', $this->options['class']);
      foreach ($classes as $index => $class) {
        $classes[$index] = Html::getClass($class);
      }
    }
    else {
      $classes = [];
    }

    // Assemble elements into a link render array.
    $element = [
      '#type' => 'link',
      '#title' => $this->options['label'],
      '#url' => $url,
      '#options' => [
        'attributes' => [
          'class' => $classes,
        ],
      ],
      '#access' => $access,
    ];

    // Apply the selected dialog options.
    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;
  }

  /**
   * Parse provided text into key-value pairs, checking for tokens.
   *
   * @param array $params
   *   The array to which parsed values will be added.
   * @param string $input
   *   The configured input to parse.
   */
  protected function extractParams(array &$params, $input) {
    $list = explode("\n", $input);
    $list = array_map('trim', $list);
    $list = array_filter($list, 'strlen');
    $display = $this->view
      ->getDisplay();

    // @todo possible to support additional tokens?
    $tokens = $display
      ->getArgumentsTokens();
    foreach ($list as $text) {

      // Check for an explicit key.
      $matches = [];
      if (preg_match('/(.*)\\|(.*)/', $text, $matches)) {

        // Trim key and value to avoid unwanted spaces issues.
        $key = trim($matches[1]);
        $value = trim($matches[2]);
      }
      elseif (strlen($text) <= 255) {
        $key = $value = $text;
      }

      // Check for tokens in the value.
      if ($tokens) {
        $value = $display
          ->viewsTokenReplace($value, $tokens);
      }
      $params[$key] = $value;
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AddContentByBundle::$accessManager protected property The access manager.
AddContentByBundle::buildOptionsForm public function Provide a form to edit options for this plugin. Overrides AreaPluginBase::buildOptionsForm
AddContentByBundle::create public static function Creates an instance of the plugin. Overrides PluginBase::create
AddContentByBundle::defineOptions protected function Information about options for all kinds of purposes will be held here. Overrides AreaPluginBase::defineOptions
AddContentByBundle::extractParams protected function Parse provided text into key-value pairs, checking for tokens.
AddContentByBundle::render public function Render the area. Overrides AreaPluginBase::render
AddContentByBundle::validate public function Validate that the plugin is correct and can be saved. Overrides HandlerBase::validate
AddContentByBundle::__construct public function Constructs a new plugin instance. Overrides HandlerBase::__construct
AreaPluginBase::$areaType public property The type of this area handler, i.e. 'header', 'footer', or 'empty'.
AreaPluginBase::adminSummary public function Provide text for the administrative summary. Overrides HandlerBase::adminSummary
AreaPluginBase::init public function Overrides Drupal\views\Plugin\views\HandlerBase::init(). Overrides HandlerBase::init 1
AreaPluginBase::isEmpty public function Does that area have nothing to show. 1
AreaPluginBase::preRender public function Performs any operations needed before full rendering. 1
AreaPluginBase::usesGroupBy public function Provides the handler some groupby. Overrides HandlerBase::usesGroupBy
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
HandlerBase::$field public property With field you can override the realField if the real field is not set.
HandlerBase::$moduleHandler protected property The module handler. 3
HandlerBase::$query public property Where the $query object will reside. 7
HandlerBase::$realField public property The actual field in the database table, maybe different on other kind of query plugins/special handlers.
HandlerBase::$relationship public property The relationship used for this field.
HandlerBase::$table public property The table this handler is attached to.
HandlerBase::$tableAlias public property The alias of the table of this handler which is used in the query.
HandlerBase::$viewsData protected property The views data service.
HandlerBase::acceptExposedInput public function Take input from exposed handlers and assign to this handler, if necessary. 1
HandlerBase::access public function Check whether given user has access to this handler. Overrides ViewsHandlerInterface::access 4
HandlerBase::adminLabel public function Return a string representing this handler's name in the UI. Overrides ViewsHandlerInterface::adminLabel 4
HandlerBase::breakString public static function Breaks x,y,z and x+y+z into an array. Overrides ViewsHandlerInterface::breakString
HandlerBase::broken public function Determines if the handler is considered 'broken', meaning it's a placeholder used when a handler can't be found. Overrides ViewsHandlerInterface::broken
HandlerBase::buildExposedForm public function Render our chunk of the exposed handler form when selecting. 1
HandlerBase::buildExposeForm public function Form for exposed handler options. 2
HandlerBase::buildExtraOptionsForm public function Provide a form for setting options. 1
HandlerBase::buildGroupByForm public function Provide a form for aggregation settings. 1
HandlerBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides PluginBase::calculateDependencies 10
HandlerBase::canExpose public function Determine if a handler can be exposed. 2
HandlerBase::caseTransform protected function Transform a string by a certain method.
HandlerBase::defaultExposeOptions public function Set new exposed option defaults when exposed setting is flipped on. 2
HandlerBase::defineExtraOptions public function Provide defaults for the handler.
HandlerBase::displayExposedForm public function Displays the Expose form.
HandlerBase::ensureMyTable public function Ensure the main table for this handler is in the query. This is used a lot. Overrides ViewsHandlerInterface::ensureMyTable 2
HandlerBase::exposedInfo public function Get information about the exposed form for the form renderer. 1
HandlerBase::getDateField public function Creates cross-database SQL dates. 2
HandlerBase::getDateFormat public function Creates cross-database SQL date formatting. 2
HandlerBase::getEntityType public function Determines the entity type used by this handler. Overrides ViewsHandlerInterface::getEntityType
HandlerBase::getField public function Shortcut to get a handler's raw field value. Overrides ViewsHandlerInterface::getField
HandlerBase::getJoin public function Get the join object that should be used for this handler. Overrides ViewsHandlerInterface::getJoin
HandlerBase::getModuleHandler protected function Gets the module handler.
HandlerBase::getTableJoin public static function Fetches a handler to join one table to a primary table from the data cache. Overrides ViewsHandlerInterface::getTableJoin
HandlerBase::getViewsData protected function Gets views data service.
HandlerBase::hasExtraOptions public function If a handler has 'extra options' it will get a little settings widget and another form called extra_options. 1
HandlerBase::isAGroup public function Returns TRUE if the exposed filter works like a grouped filter. 1
HandlerBase::isExposed public function Determine if this item is 'exposed', meaning it provides form elements to let users modify the view.
HandlerBase::multipleExposedInput public function Define if the exposed input has to be submitted multiple times. This is TRUE when exposed filters grouped are using checkboxes as widgets. 1
HandlerBase::placeholder protected function Provides a unique placeholders for handlers.
HandlerBase::postExecute public function Run after the view is executed, before the result is cached. Overrides ViewsHandlerInterface::postExecute
HandlerBase::preQuery public function Run before the view is built. Overrides ViewsHandlerInterface::preQuery 2
HandlerBase::query public function Add anything to the query that we might need to. Overrides PluginBase::query 7
HandlerBase::sanitizeValue public function Sanitize the value for output. Overrides ViewsHandlerInterface::sanitizeValue
HandlerBase::setModuleHandler public function Sets the module handler.
HandlerBase::setRelationship public function Called just prior to query(), this lets a handler set up any relationship it needs. Overrides ViewsHandlerInterface::setRelationship
HandlerBase::setViewsData public function
HandlerBase::showExposeButton public function Shortcut to display the expose/hide button. 2
HandlerBase::showExposeForm public function Shortcut to display the exposed options form. Overrides ViewsHandlerInterface::showExposeForm
HandlerBase::storeExposedInput public function If set to remember exposed input in the session, store it there. 1
HandlerBase::submitExposed public function Submit the exposed handler form.
HandlerBase::submitExposeForm public function Perform any necessary changes to the form exposes prior to storage. There is no need for this function to actually store the data.
HandlerBase::submitExtraOptionsForm public function Perform any necessary changes to the form values prior to storage. There is no need for this function to actually store the data.
HandlerBase::submitFormCalculateOptions public function Calculates options stored on the handler. 1
HandlerBase::submitGroupByForm public function Perform any necessary changes to the form values prior to storage. There is no need for this function to actually store the data. 1
HandlerBase::submitTemporaryForm public function A submit handler that is used for storing temporary items when using multi-step changes, such as ajax requests.
HandlerBase::validateExposed public function Validate the exposed handler form. 4
HandlerBase::validateExposeForm public function Validate the options form. 2
HandlerBase::validateExtraOptionsForm public function Validate the options form.
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$definition public property Plugins's definition.
PluginBase::$displayHandler public property The display object this plugin is for.
PluginBase::$options public property Options for this plugin will be held here.
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::$renderer protected property Stores the render API renderer. 3
PluginBase::$usesOptions protected property Denotes whether the plugin has an additional options form. 8
PluginBase::$view public property The top object of a view. 1
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::destroy public function Clears a plugin. Overrides ViewsPluginInterface::destroy 2
PluginBase::doFilterByDefinedOptions protected function Do the work to filter out stored options depending on the defined options.
PluginBase::filterByDefinedOptions public function Filter out stored options depending on the defined options. Overrides ViewsPluginInterface::filterByDefinedOptions
PluginBase::getAvailableGlobalTokens public function Returns an array of available token replacements. Overrides ViewsPluginInterface::getAvailableGlobalTokens
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 2
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::getProvider public function Returns the plugin provider. Overrides ViewsPluginInterface::getProvider
PluginBase::getRenderer protected function Returns the render API renderer. 1
PluginBase::globalTokenForm public function Adds elements for available core tokens to a form. Overrides ViewsPluginInterface::globalTokenForm
PluginBase::globalTokenReplace public function Returns a string with any core tokens replaced. Overrides ViewsPluginInterface::globalTokenReplace
PluginBase::INCLUDE_ENTITY constant Include entity row languages when listing languages.
PluginBase::INCLUDE_NEGOTIATED constant Include negotiated languages when listing languages.
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginBase::listLanguages protected function Makes an array of languages, optionally including special languages.
PluginBase::pluginTitle public function Return the human readable name of the display. Overrides ViewsPluginInterface::pluginTitle
PluginBase::preRenderAddFieldsetMarkup public static function Moves form elements into fieldsets for presentation purposes. Overrides ViewsPluginInterface::preRenderAddFieldsetMarkup
PluginBase::preRenderFlattenData public static function Flattens the structure of form elements. Overrides ViewsPluginInterface::preRenderFlattenData
PluginBase::queryLanguageSubstitutions public static function Returns substitutions for Views queries for languages.
PluginBase::setOptionDefaults protected function Fills up the options of the plugin with defaults.
PluginBase::submitOptionsForm public function Handle any special handling on the validate form. Overrides ViewsPluginInterface::submitOptionsForm 16
PluginBase::summaryTitle public function Returns the summary of the settings in the display. Overrides ViewsPluginInterface::summaryTitle 6
PluginBase::themeFunctions public function Provide a full list of possible theme templates used by this style. Overrides ViewsPluginInterface::themeFunctions 1
PluginBase::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides TrustedCallbackInterface::trustedCallbacks 6
PluginBase::unpackOptions public function Unpack options over our existing defaults, drilling down into arrays so that defaults don't get totally blown away. Overrides ViewsPluginInterface::unpackOptions
PluginBase::usesOptions public function Returns the usesOptions property. Overrides ViewsPluginInterface::usesOptions 8
PluginBase::validateOptionsForm public function Validate the options form. Overrides ViewsPluginInterface::validateOptionsForm 15
PluginBase::viewsTokenReplace protected function Replaces Views' tokens in a given string. The resulting string will be sanitized with Xss::filterAdmin. 1
PluginBase::VIEWS_QUERY_LANGUAGE_SITE_DEFAULT constant Query string to indicate the site default language.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.
TrustedCallbackInterface::TRIGGER_WARNING constant Untrusted callbacks trigger E_USER_WARNING errors.