You are here

class AddForm in Linkit 8.4

Same name in this branch
  1. 8.4 src/Form/Attribute/AddForm.php \Drupal\linkit\Form\Attribute\AddForm
  2. 8.4 src/Form/Matcher/AddForm.php \Drupal\linkit\Form\Matcher\AddForm
  3. 8.4 src/Form/Profile/AddForm.php \Drupal\linkit\Form\Profile\AddForm

Provides a form to apply attributes to a profile.

Hierarchy

Expanded class hierarchy of AddForm

1 string reference to 'AddForm'
linkit.routing.yml in ./linkit.routing.yml
linkit.routing.yml

File

src/Form/Attribute/AddForm.php, line 20
Contains \Drupal\linkit\Form\Attribute\AddForm.

Namespace

Drupal\linkit\Form\Attribute
View source
class AddForm extends FormBase {

  /**
   * The profiles to which the attributes will be applied.
   *
   * @var \Drupal\linkit\ProfileInterface
   */
  protected $linkitProfile;

  /**
   * The attribute manager.
   *
   * @var \Drupal\linkit\AttributeManager
   */
  protected $manager;

  /**
   * Constructs a new AddForm.
   *
   * @param \Drupal\linkit\AttributeManager $manager
   *   The attribute manager.
   */
  public function __construct(AttributeManager $manager) {
    $this->manager = $manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.manager.linkit.attribute'));
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return "linkit_attribute_add_form";
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, ProfileInterface $linkit_profile = NULL) {
    $this->linkitProfile = $linkit_profile;
    $form['#attached']['library'][] = 'linkit/linkit.admin';
    $header = [
      'label' => $this
        ->t('Attributes'),
      'description' => $this
        ->t('Description'),
    ];
    $form['plugin'] = [
      '#type' => 'tableselect',
      '#header' => $header,
      '#options' => $this
        ->buildRows(),
      '#empty' => $this
        ->t('No attributes available.'),
      '#multiple' => FALSE,
    ];
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save and continue'),
      '#submit' => [
        '::submitForm',
      ],
      '#tableselect' => TRUE,
      '#button_type' => 'primary',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    if (empty($form_state
      ->getValue('plugin'))) {
      $form_state
        ->setErrorByName('plugin', $this
        ->t('No attribute selected.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $form_state
      ->cleanValues();

    /** @var \Drupal\linkit\AttributeInterface $plugin */
    $plugin = $this->manager
      ->createInstance($form_state
      ->getValue('plugin'));
    $plugin_id = $this->linkitProfile
      ->addAttribute($plugin
      ->getConfiguration());
    $this->linkitProfile
      ->save();
    $this
      ->logger('linkit')
      ->notice('Added %label attribute to the @profile profile.', [
      '%label' => $this->linkitProfile
        ->getAttribute($plugin_id)
        ->getLabel(),
      '@profile' => $this->linkitProfile
        ->label(),
    ]);
    $is_configurable = $plugin instanceof ConfigurableAttributeInterface;
    if ($is_configurable) {
      $form_state
        ->setRedirect('linkit.attribute.edit', [
        'linkit_profile' => $this->linkitProfile
          ->id(),
        'plugin_instance_id' => $plugin_id,
      ]);
    }
    else {
      drupal_set_message($this
        ->t('Added %label attribute.', [
        '%label' => $plugin
          ->getLabel(),
      ]));
      $form_state
        ->setRedirect('linkit.attributes', [
        'linkit_profile' => $this->linkitProfile
          ->id(),
      ]);
    }
  }

  /**
   * Builds the table rows.
   *
   * Only attributes that is not already applied to the profile are shown.
   *
   * @return array
   *   An array of table rows.
   */
  private function buildRows() {
    $rows = [];
    $applied_plugins = $this->linkitProfile
      ->getAttributes()
      ->getConfiguration();
    $all_plugins = $this->manager
      ->getDefinitions();
    uasort($all_plugins, function ($a, $b) {
      return strnatcasecmp($a['label'], $b['label']);
    });
    foreach (array_diff_key($all_plugins, $applied_plugins) as $definition) {

      /** @var \Drupal\linkit\AttributeInterface $plugin */
      $plugin = $this->manager
        ->createInstance($definition['id']);
      $row = [
        'label' => (string) $plugin
          ->getLabel(),
        'description' => (string) $plugin
          ->getDescription(),
      ];
      $rows[$plugin
        ->getPluginId()] = $row;
    }
    return $rows;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AddForm::$linkitProfile protected property The profiles to which the attributes will be applied.
AddForm::$manager protected property The attribute manager.
AddForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
AddForm::buildRows private function Builds the table rows.
AddForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
AddForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
AddForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
AddForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
AddForm::__construct public function Constructs a new AddForm.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
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. 1
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.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.