You are here

class CclAddForm in Custom Contextual Links 8

Hierarchy

Expanded class hierarchy of CclAddForm

1 string reference to 'CclAddForm'
ccl.routing.yml in ./ccl.routing.yml
ccl.routing.yml

File

src/Form/CclAddForm.php, line 14
Contains \Drupal\ccl\Form\CclAddForm.

Namespace

Drupal\ccl\Form
View source
class CclAddForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'ccl_add_form';
  }
  public function buildForm(array $form, \Drupal\Core\Form\FormStateInterface $form_state, $clid = NULL) {

    // Check if we are in edit mode and load the link values.
    if ($clid) {
      $link = db_query('SELECT * FROM {ccl} WHERE clid = :clid', [
        ':clid' => $clid,
      ])
        ->fetchObject();
      $form_state
        ->set([
        'clid',
      ], $clid);
      $form_state
        ->set([
        'link',
      ], $link);

      // Unserialize options.
      $link->options = unserialize($link->options);
      $node_options = $link->options['node_options'];
      if ($node_options == 'node') {
        $title = db_query('SELECT title FROM {node} WHERE nid = :nid', [
          ':nid' => $link->options['node_id'],
        ])
          ->fetchField();
        $nid_text = $title . ' [nid:' . $link->options['node_id'] . ']';
      }
    }
    $form = [];

    // Pull in library, js and css for the form.
    $form['#attached']['library'][] = [
      'system',
      'ui.button',
    ];
    $form['#attached']['js'][] = drupal_get_path('module', 'ccl') . '/ccl.js';
    $form['#attached']['css'][] = drupal_get_path('module', 'ccl') . '/ccl.css';
    $form['link_group'] = [
      '#type' => 'fieldset',
      '#title' => t('Link'),
      '#collapsible' => TRUE,
    ];
    $form['link_group']['ccl_title'] = [
      '#type' => 'textfield',
      '#title' => t('Title'),
      '#description' => t('The title of this link as it will be displayed in the contextual widget.'),
      '#size' => 40,
      '#default_value' => $clid ? $link->title : '',
      '#maxlength' => 255,
      '#required' => TRUE,
    ];
    $form['link_group']['ccl_link'] = [
      '#type' => 'textfield',
      '#title' => t('URL'),
      '#default_value' => $clid ? $link->link : '',
      '#description' => t('The URL of this link.'),
      '#size' => 40,
      '#maxlength' => 255,
      '#required' => TRUE,
    ];
    $form['link_group']['advanced'] = [
      '#type' => 'fieldset',
      '#title' => t('Advanced Options'),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    ];
    $form['link_group']['advanced']['advanced_css'] = [
      '#type' => 'textfield',
      '#title' => t('CSS Class'),
      '#default_value' => $clid && isset($link->options['advanced_css']) ? $link->options['advanced_css'] : '',
      '#description' => t('Add class name(s) to the link. Multiple classes should be seperated by a space. Example: "%example".', [
        '%example' => "colorbox-load extra-class",
      ]),
      '#size' => 40,
      '#maxlength' => 255,
    ];
    $form['link_group']['advanced']['advanced_anchor'] = [
      '#type' => 'textfield',
      '#title' => t('Anchor'),
      '#default_value' => $clid && isset($link->options['advanced_anchor']) ? $link->options['advanced_anchor'] : '',
      '#description' => t('Append an anchor string to the end of the link. Do not use the "#" at the beginning of the string.'),
      '#size' => 40,
      '#maxlength' => 255,
    ];
    $form['link_group']['advanced']['advanced_query'] = [
      '#type' => 'textfield',
      '#title' => t('Query String'),
      '#default_value' => $clid && isset($link->options['advanced_query']) ? $link->options['advanced_query'] : '',
      '#description' => t('Append a query string to the end of the link. Do not use the "?" at the beginning of the query. Tokens can be used for this field as well.<br />Example: "%example".', [
        '%example' => "width=500&height=500&iframe=true&user=[current-user:uid]",
      ]),
      '#size' => 40,
      '#maxlength' => 255,
    ];
    $form['link_group']['advanced']['advanced_target'] = [
      '#type' => 'select',
      '#title' => t('Link Target'),
      '#options' => [
        'default' => t('Default (no target attribute)'),
        '_top' => t('Open link in window root'),
        '_blank' => t('Open link in new window'),
      ],
      '#default_value' => $clid && isset($link->options['advanced_target']) ? $link->options['advanced_target'] : '',
      '#description' => t('Set a target attribute for the link.'),
    ];
    $form['link_group']['advanced']['advanced_destination'] = [
      '#type' => 'checkbox',
      '#title' => t('Include destination parameter in Link'),
      '#default_value' => $clid && isset($link->options['advanced_destination']) ? $link->options['advanced_destination'] : TRUE,
      '#description' => t('If checked, the current page path will be added to the link\'s "destination" parameter (which will return the user to this page if they submit a form from the link target).'),
    ];
    $form['link_group']['token_group'] = [
      '#type' => 'fieldset',
      '#title' => t('Tokens'),
      '#description' => t("Token replacements will be performed for the link title and for the URL. Note that 'Node' tokens will not be replaced for links that are added to blocks."),
      '#collapsible' => TRUE,
      '#collapsed' => TRUE,
    ];
    if (\Drupal::moduleHandler()
      ->moduleExists('token')) {
      $form['link_group']['token_group']['tokens'] = [
        '#theme' => 'token_tree',
        '#token_types' => [
          'node',
        ],
        '#global_types' => TRUE,
        '#click_insert' => TRUE,
      ];
    }
    else {
      $form['link_group']['token_group']['token_tree'] = [
        '#markup' => '<p>' . t('Enable the <a href="@drupal-token">Token module</a> to view the available token browser.', [
          '@drupal-token' => 'http://drupal.org/project/token',
        ]) . '</p>',
      ];
    }
    $form['options_group'] = [
      '#type' => 'fieldset',
      '#title' => t('Options'),
      '#collapsible' => TRUE,
    ];
    $form['options_group']['ccl_type'] = [
      '#type' => 'radios',
      '#title' => t('Link Type'),
      '#description' => t('Select if this link should be displayed for a node or for a block.'),
      '#options' => [
        'node' => t('Node'),
      ],
      '#default_value' => $clid ? $link->type : 'node',
    ];
    $form['options_group']['node_options'] = [
      '#type' => 'radios',
      '#title' => t('Show link for'),
      '#description' => t('Select if this link should be displayed for all nodes, all nodes of a content type or a specific node.'),
      '#options' => [
        'node' => t('Single node'),
        'ct' => t('Content type'),
        'global' => t('All nodes'),
      ],
      '#default_value' => isset($node_options) ? $node_options : 'node',
      '#states' => [
        'visible' => [
          ':input[name="ccl_type"]' => [
            'value' => 'node',
          ],
        ],
      ],
    ];

    // Load the content type names.
    $types = node_type_get_names();
    $form['options_group']['node_type'] = [
      '#type' => 'select',
      '#title' => t('Content Type'),
      '#description' => t('The content type this link will be displayed for.'),
      '#options' => $types,
      '#default_value' => $clid ? $link->options['node_type'] : -1,
      '#states' => [
        'visible' => [
          ':input[name="node_options"]' => [
            'value' => 'ct',
          ],
          ':input[name="ccl_type"]' => [
            'value' => 'node',
          ],
        ],
      ],
    ];
    $form['options_group']['node_id'] = [
      '#type' => 'textfield',
      '#title' => t('Node ID'),
      '#description' => t('Enter the title of the node or the id of the node this link should be added to.'),
      '#size' => 40,
      '#maxlength' => 128,
      '#default_value' => isset($nid_text) ? $nid_text : '',
      '#autocomplete_path' => 'admin/config/user-interface/ccl/autocomplete',
      '#states' => [
        'visible' => [
          ':input[name="node_options"]' => [
            'value' => 'node',
          ],
          ':input[name="ccl_type"]' => [
            'value' => 'node',
          ],
        ],
      ],
    ];
    $form['ccl_save_link'] = [
      '#type' => 'submit',
      '#value' => t('Save Link'),
    ];
    return $form;
  }
  public function validateForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $values = $form_state
      ->getValues();

    // Check that that we can get the node id and transform it for saving.
    if ($values['ccl_type'] == 'node' && $values['node_options'] == 'node') {
      if (is_numeric($values['node_id'])) {
        $form_state
          ->setValueForElement($form['options_group']['node_id'], $values['node_id']);
      }
      elseif (preg_match('/\\[nid:[0-9]*\\]/', $values['node_id'], $match)) {
        $form_state
          ->setValueForElement($form['options_group']['node_id'], substr(rtrim($match[0], ']'), 5));
      }
      else {
        $form_state
          ->setErrorByName('nid', t('Enter a node id or use the autocomplete widget to select an existing node.'));
      }
    }
  }
  public function submitForm(array &$form, \Drupal\Core\Form\FormStateInterface $form_state) {

    // Clean up the values array.
    $form_state
      ->cleanValues();
    $values = $form_state
      ->getValues();

    // Extract the options out of the values.
    $options = [];
    foreach ($values as $key => $data) {
      if (strpos($key, 'ccl_') === FALSE) {
        $options[$key] = $data;
      }
    }
    $record = [
      'type' => $values['ccl_type'],
      'title' => $values['ccl_title'],
      'link' => $values['ccl_link'],
      'options' => serialize($options),
    ];
    if (!$form_state
      ->get([
      'clid',
    ])) {
      $record['clid'] = $form_state
        ->get([
        'clid',
      ]);
      $res = \Drupal::database()
        ->merge('ccl')
        ->fields($record)
        ->key([
        'clid',
      ])
        ->execute();
    }
    else {
      $res = \Drupal::database()
        ->insert('ccl')
        ->fields($record)
        ->execute();
    }
    if ($res) {
      drupal_set_message(t('Contextual link saved.'));
      _ccl_update_cache();
    }
    else {
      drupal_set_message(t('There was an error writing this record to the database. Please try again.'), 'error');
    }
    drupal_goto('admin/config/user-interface/ccl');
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CclAddForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
CclAddForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
CclAddForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
CclAddForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
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::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
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.