class CustomContextualLinkForm in Custom Contextual Links 8.2
Class CustomContextualLinkForm.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
- class \Drupal\ccl\Form\CustomContextualLinkForm
- class \Drupal\Core\Entity\EntityForm implements EntityFormInterface
Expanded class hierarchy of CustomContextualLinkForm
File
- src/
Form/ CustomContextualLinkForm.php, line 19
Namespace
Drupal\ccl\FormView source
class CustomContextualLinkForm extends EntityForm {
/**
* Module Handler Service.
*
* @var \Drupal\Core\Extension\ModuleHandler
*/
protected $moduleHandler;
/**
* CCL Service.
*
* @var \Drupal\ccl\CclService
*/
protected $cclService;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
protected $eventDispatcher;
/**
* CustomContextualLinkForm constructor.
*
* @param \Drupal\Core\Extension\ModuleHandler $module_handler
* Inject Module handler service.
* @param \Drupal\ccl\CclService $ccl_service
* Inject CCL service.
* @param \Drupal\Core\Entity\EntityTypeManager $entity_type_manager
* Inject EntityType Manager.
* @param \Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher $event_dispatcher
* Inject EventDispatcher service.
*/
public function __construct(ModuleHandler $module_handler, CclService $ccl_service, EntityTypeManager $entity_type_manager, EventDispatcher $event_dispatcher) {
$this->moduleHandler = $module_handler;
$this->cclService = $ccl_service;
$this->entityTypeManager = $entity_type_manager;
$this->eventDispatcher = $event_dispatcher;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static($container
->get('module_handler'), $container
->get('ccl.service'), $container
->get('entity_type.manager'), $container
->get('event_dispatcher'));
}
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
$form['#attached']['library'][] = 'ccl/ccl';
$form['#attributes']['class'][] = 'ccl-form';
/** @var \Drupal\ccl\Entity\CustomContextualLink $custom_contextual_link */
$custom_contextual_link = $this->entity;
$form['label'] = [
'#type' => 'textfield',
'#title' => $this
->t('Label'),
'#maxlength' => 255,
'#default_value' => $custom_contextual_link
->label(),
'#description' => $this
->t("Label for the Custom Contextual Link. This for internal identification."),
'#required' => TRUE,
];
$form['id'] = [
'#type' => 'machine_name',
'#default_value' => $custom_contextual_link
->id(),
'#machine_name' => [
'exists' => '\\Drupal\\ccl\\Entity\\CustomContextualLink::load',
],
'#disabled' => !$custom_contextual_link
->isNew(),
];
$form['title'] = [
'#type' => 'textfield',
'#title' => $this
->t('Link Title'),
'#description' => $this
->t('The title of this link as it will be displayed in the contextual widget.'),
'#default_value' => $custom_contextual_link
->get('title'),
'#required' => TRUE,
];
$form['link'] = [
'#type' => 'textfield',
'#title' => $this
->t('URL'),
'#default_value' => $custom_contextual_link
->get('link'),
'#description' => $this
->t('The URL of this link.'),
'#required' => TRUE,
];
$form['advanced'] = [
'#type' => 'details',
'#title' => $this
->t('Advanced Options'),
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#tree' => TRUE,
];
$form['advanced']['css'] = [
'#type' => 'textfield',
'#title' => $this
->t('CSS Class'),
'#default_value' => $custom_contextual_link
->getAdvancedOption('css'),
'#description' => $this
->t('Add class name(s) to the link. Multiple classes should be seperated by a space. Example: "%example".', [
'%example' => "colorbox-load extra-class",
]),
];
$form['advanced']['anchor'] = [
'#type' => 'textfield',
'#title' => $this
->t('Anchor'),
'#default_value' => $custom_contextual_link
->getAdvancedOption('anchor'),
'#description' => $this
->t('Append an anchor string to the end of the link. Do not use the "#" at the beginning of the string.'),
];
$form['advanced']['query'] = [
'#type' => 'textfield',
'#title' => $this
->t('Query String'),
'#default_value' => $custom_contextual_link
->getAdvancedOption('query'),
'#description' => $this
->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]",
]),
];
$form['advanced']['target'] = [
'#type' => 'select',
'#title' => $this
->t('Link Target'),
'#options' => [
'default' => $this
->t('Default (no target attribute)'),
'_top' => $this
->t('Open link in window root'),
'_blank' => $this
->t('Open link in new window'),
],
'#default_value' => $custom_contextual_link
->getAdvancedOption('target'),
'#description' => $this
->t('Set a target attribute for the link.'),
];
$form['token_group'] = [
'#type' => 'details',
'#collapsible' => TRUE,
'#collapsed' => TRUE,
'#title' => $this
->t('Tokens'),
'#description' => $this
->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.<br>Because contextual links are heavily cached, dynamic tokens like 'Current date' might not work as expected."),
];
if ($this->moduleHandler
->moduleExists('token')) {
$form['token_group']['tokens'] = [
'#theme' => 'token_tree_link',
'#token_types' => [
'node',
],
'#global_types' => TRUE,
'#click_insert' => TRUE,
'#dialog' => TRUE,
];
}
else {
$form['token_group']['token_tree'] = [
'#markup' => '<p>' . $this
->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',
'#tree' => FALSE,
'#title' => $this
->t('Options'),
];
$form['options_group']['type'] = [
'#type' => 'radios',
'#title' => $this
->t('Link Type'),
'#description' => $this
->t('Select if this link should be displayed for a node or for a block.'),
'#options' => [
'node' => $this
->t('Node'),
],
'#default_value' => $custom_contextual_link
->get('type'),
'#required' => TRUE,
];
$form['options_group']['options'] = [
'#type' => 'container',
'#tree' => TRUE,
];
$form['options_group']['options']['node_option'] = [
'#type' => 'radios',
'#title' => $this
->t('Show link for'),
'#description' => $this
->t('Select if this link should be displayed for all nodes, all nodes of a content type or a specific node.'),
'#options' => [
'node' => $this
->t('Single node'),
'ct' => $this
->t('Content type'),
'global' => $this
->t('All nodes'),
],
'#default_value' => $custom_contextual_link
->getLinkOption('node_option'),
'#states' => [
'visible' => [
':input[name="type"]' => [
'value' => 'node',
],
],
],
];
// Load the content type names.
$types = node_type_get_names();
$form['options_group']['options']['node_type'] = [
'#type' => 'select',
'#title' => $this
->t('Content Type'),
'#description' => $this
->t('The content type this link will be displayed for.'),
'#options' => $types,
'#default_value' => $custom_contextual_link
->getLinkOption('node_type'),
'#states' => [
'visible' => [
':input[name="options[node_option]"]' => [
'value' => 'ct',
],
':input[name="type"]' => [
'value' => 'node',
],
],
],
];
$defaultNid = $custom_contextual_link
->getLinkOption('node_id');
$defaultNode = NULL;
try {
$nodeStorage = $this->entityTypeManager
->getStorage('node');
$defaultNode = $defaultNid ? $nodeStorage
->load($defaultNid) : NULL;
} catch (Exception $exception) {
$this
->logger('ccl')
->error($exception
->getMessage());
}
$form['options_group']['options']['node_id'] = [
'#type' => 'entity_autocomplete',
'#target_type' => 'node',
'#title' => $this
->t('Node ID'),
'#description' => $this
->t('Enter the title of the node or the id of the node this link should be added to.'),
'#default_value' => $defaultNode,
'#states' => [
'visible' => [
':input[name="options[node_option]"]' => [
'value' => 'node',
],
':input[name="type"]' => [
'value' => 'node',
],
],
],
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
$url = $form_state
->getValue('link');
if (strpos($url, '/') !== 0 && strpos($url, 'http') !== 0) {
$form_state
->setErrorByName('link', $this
->t("Internal links need to start with a '/' and external links with 'http'"));
}
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
/** @var \Drupal\ccl\Entity\CustomContextualLink $custom_contextual_link */
$custom_contextual_link = $this->entity;
try {
$custom_contextual_link
->clearOptions();
$status = $custom_contextual_link
->save();
switch ($status) {
case SAVED_NEW:
$this
->messenger()
->addMessage($this
->t('Created the %label Custom Contextual Link.', [
'%label' => $custom_contextual_link
->label(),
]));
break;
default:
$this
->messenger()
->addMessage($this
->t('Saved the %label Custom Contextual Link.', [
'%label' => $custom_contextual_link
->label(),
]));
}
$this->eventDispatcher
->dispatch('ccl_update_cache');
try {
$form_state
->setRedirectUrl($custom_contextual_link
->toUrl('collection'));
} catch (EntityMalformedException $exception) {
$this
->logger('ccl')
->error($exception
->getMessage());
}
} catch (EntityStorageException $exception) {
$this
->logger('ccl')
->error($exception
->getMessage());
$this
->messenger()
->addError($this
->t('There was an error saving the link. Please consult the error log for more details.'));
}
}
}
Members
Name![]() |
Modifiers | Type | Description | Overrides |
---|---|---|---|---|
CustomContextualLinkForm:: |
protected | property | CCL Service. | |
CustomContextualLinkForm:: |
protected | property |
The entity type manager. Overrides EntityForm:: |
|
CustomContextualLinkForm:: |
protected | property | ||
CustomContextualLinkForm:: |
protected | property |
Module Handler Service. Overrides EntityForm:: |
|
CustomContextualLinkForm:: |
public static | function |
Instantiates a new instance of this class. Overrides FormBase:: |
|
CustomContextualLinkForm:: |
public | function |
Gets the actual form array to be built. Overrides EntityForm:: |
|
CustomContextualLinkForm:: |
public | function |
Form submission handler for the 'save' action. Overrides EntityForm:: |
|
CustomContextualLinkForm:: |
public | function |
Form validation handler. Overrides FormBase:: |
|
CustomContextualLinkForm:: |
public | function | CustomContextualLinkForm constructor. | |
DependencySerializationTrait:: |
protected | property | An array of entity type IDs keyed by the property name of their storages. | |
DependencySerializationTrait:: |
protected | property | An array of service IDs keyed by property name used for serialization. | |
DependencySerializationTrait:: |
public | function | 1 | |
DependencySerializationTrait:: |
public | function | 2 | |
EntityForm:: |
protected | property | The entity being used by this form. | 7 |
EntityForm:: |
protected | property | The name of the current operation. | |
EntityForm:: |
private | property | The entity manager. | |
EntityForm:: |
protected | function | Returns an array of supported actions for the current entity form. | 29 |
EntityForm:: |
protected | function | Returns the action form element for the current entity form. | |
EntityForm:: |
public | function | Form element #after_build callback: Updates the entity with submitted data. | |
EntityForm:: |
public | function |
Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface:: |
2 |
EntityForm:: |
public | function |
Form constructor. Overrides FormInterface:: |
10 |
EntityForm:: |
protected | function | Copies top-level form values to entity properties | 7 |
EntityForm:: |
public | function |
Returns a string identifying the base form. Overrides BaseFormIdInterface:: |
5 |
EntityForm:: |
public | function |
Gets the form entity. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface:: |
1 |
EntityForm:: |
public | function |
Returns a unique string identifying the form. Overrides FormInterface:: |
10 |
EntityForm:: |
public | function |
Gets the operation identifying the form. Overrides EntityFormInterface:: |
|
EntityForm:: |
protected | function | Initialize the form state and the entity before the first form build. | 3 |
EntityForm:: |
protected | function | Prepares the entity object before the form is built first. | 3 |
EntityForm:: |
protected | function | Invokes the specified prepare hook variant. | |
EntityForm:: |
public | function | Process callback: assigns weights and hides extra fields. | |
EntityForm:: |
public | function |
Sets the form entity. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the entity manager for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the entity type manager for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the module handler for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
Sets the operation for this form. Overrides EntityFormInterface:: |
|
EntityForm:: |
public | function |
This is the default entity object builder function. It is called before any
other submit handler to build the new entity object to be used by the
following submit handlers. At this point of the form workflow the entity is
validated and the form state… Overrides FormInterface:: |
17 |
EntityForm:: |
public | function | ||
EntityForm:: |
public | function | ||
FormBase:: |
protected | property | The config factory. | 1 |
FormBase:: |
protected | property | The request stack. | 1 |
FormBase:: |
protected | property | The route match. | |
FormBase:: |
protected | function | Retrieves a configuration object. | |
FormBase:: |
protected | function | Gets the config factory for this form. | 1 |
FormBase:: |
private | function | Returns the service container. | |
FormBase:: |
protected | function | Gets the current user. | |
FormBase:: |
protected | function | Gets the request object. | |
FormBase:: |
protected | function | Gets the route match. | |
FormBase:: |
protected | function | Gets the logger for a specific channel. | |
FormBase:: |
protected | function |
Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: |
|
FormBase:: |
public | function | Resets the configuration factory. | |
FormBase:: |
public | function | Sets the config factory for this form. | |
FormBase:: |
public | function | Sets the request stack object to use. | |
LinkGeneratorTrait:: |
protected | property | The link generator. | 1 |
LinkGeneratorTrait:: |
protected | function | Returns the link generator. | |
LinkGeneratorTrait:: |
protected | function | Renders a link to a route given a route name and its parameters. | |
LinkGeneratorTrait:: |
public | function | Sets the link generator service. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 29 |
MessengerTrait:: |
public | function | Gets the messenger. | 29 |
MessengerTrait:: |
public | function | Sets the messenger. | |
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 1 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. | |
UrlGeneratorTrait:: |
protected | property | The url generator. | |
UrlGeneratorTrait:: |
protected | function | Returns the URL generator service. | |
UrlGeneratorTrait:: |
public | function | Sets the URL generator service. | |
UrlGeneratorTrait:: |
protected | function | Generates a URL or path for a specific route based on the given parameters. |