/** * {@inheritdoc} */ public function preprocessVariables(Variables $variables) { $breadcrumb =& $variables['breadcrumb']; // Determine if breadcrumbs should be displayed. $breadcrumb_visibility = $this->theme->getSetting('breadcrumb'); if ($breadcrumb_visibility == 0 || $breadcrumb_visibility == 2 && \Drupal::service('router.admin_context')->isAdminRoute() || empty($breadcrumb)) { $breadcrumb = []; return; } // Optionally get rid of the homepage link. $show_breadcrumb_home = $this->theme->getSetting('breadcrumb_home'); if (!$show_breadcrumb_home) { array_shift($breadcrumb); } if ($this->theme->getSetting('breadcrumb_title') && !empty($breadcrumb)) { $request = \Drupal::request(); $route_match = \Drupal::routeMatch(); $page_title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject()); if (!empty($page_title)) { $breadcrumb[] = ['text' => $page_title, 'attributes' => new Attribute(['class' => ['active']])]; // Add cache context based on url. $variables->addCacheContexts(['url']); } } }
/** * {@inheritdoc} */ public function build() { $block = array('#theme' => 'fblikebutton', '#layout' => $this->configuration['layout'], '#show_faces' => $this->configuration['show_faces'], '#action' => $this->configuration['action'], '#font' => $this->configuration['font'], '#color_scheme' => $this->configuration['color_scheme'], '#width' => $this->configuration['iframe_width'], '#height' => $this->configuration['iframe_height'], '#other_css' => $this->configuration['iframe_css'], '#language' => $this->configuration['language']); // If it's not for the current page if ($this->configuration['block_url'] != '<current>') { $block['#url'] = $this->configuration['block_url']; } else { // Avoid this block to be cached $block['#cache'] = array('max-age' => 0); /** * Drupal uses the /node path to refers to the frontpage. That's why facebook * could point to www.example.com/node instead of wwww.example.com. * * To avoid this, we check if the current path is the frontpage */ // Check if the path is pointing home if (\Drupal::routeMatch()->getRouteName() == 'view.frontpage.page_1') { global $base_url; $block['#url'] = $base_url; } else { $block['#url'] = Url::fromRoute('<current>', array(), array('absolute' => true))->toString(); } } return $block; }
/** * {@inheritdoc} */ public function build() { $items = array(); // When on a node page, the parameter is already upcast as a node. $node = \Drupal::routeMatch()->getParameter('node'); if ($node) { // Read about entity query at http://www.sitepoint.com/drupal-8-version-entityfieldquery/. // See query API at https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Query%21QueryInterface.php/interface/QueryInterface/8. // The static method for using the query service would have been: // $query = \Drupal::entityQuery('node'); // Use injected queryFactory to look for items that are related // to the show that matches the input nid. $query = $this->entity_query->get('node')->condition('status', 1)->condition('type', 'tv_episode')->sort('field_related_season.entity.field_season_number.value', 'DESC')->sort('field_episode_number', 'DESC')->range(0, 5)->condition('field_related_season.entity.field_related_show.entity.nid', $node->id()); $nids = $query->execute(); // Note that entity_load() is deprecated. // The static method of loading the entity would have been: // \Drupal\node\Entity\Node::load(); // Use the injected entityManager to load the results into an array of node objects. $nodes = $this->entity_manager->getStorage('node')->loadMultiple($nids); foreach ($nodes as $node) { // Create a render array for each title field. // Note that field_view_field() is deprecated, use the view method on the field. $title = $node->title->view('full'); // Entities have a handy toLink() method. $items[] = $node->toLink($title); } } // Return a render array for a html list. return ['#theme' => 'item_list', '#items' => $items, '#cache' => ['contexts' => ['route']]]; }
/** * {@inheritdoc} */ public function build() { $request = \Drupal::request(); $route_match = \Drupal::routeMatch(); $title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject()); return array('#markup' => $title); }
/** * {@inheritdoc} */ public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { $OriginalValue = ''; if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) { $FiledsView = $items->view(); $LangCode = $items->getLangcode(); $FieldName = $FiledsView['#field_name']; $node = (array) $node; $arrayValues = array_values($node); if (isset($arrayValues[0]['langcode']['x-default']) && $arrayValues[0]['langcode']['x-default'] != $LangCode) { if ($FieldName != 'title') { if (isset($arrayValues[0][$FieldName]['x-default'][0]['value'])) { $OriginalValue = $arrayValues[0][$FieldName]['x-default'][0]['value']; } } else { if (isset($arrayValues[0][$FieldName]['x-default'])) { $OriginalValue = $arrayValues[0][$FieldName]['x-default']; } } $Title = $OriginalValue; $OriginalValue = Unicode::truncate($OriginalValue, 200, TRUE); $OriginalValue = '<div class="original_text" title="' . $Title . '"><span class="original">ORIGINAL: </span>' . $OriginalValue . '</div>'; } } $element['value'] = $element + array('#type' => 'textfield', '#default_value' => isset($items[$delta]->value) ? $items[$delta]->value : NULL, '#size' => $this->getSetting('size'), '#placeholder' => $this->getSetting('placeholder'), '#maxlength' => $this->getFieldSetting('max_length'), '#attributes' => array('class' => array('text-full')), '#suffix' => $OriginalValue); return $element; }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { //TODO v2 Send Email via Cron not on Submit $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id()); $username = $user->get('name')->value; $userId = $user->get('uid')->value; $mailManager = \Drupal::service('plugin.manager.mail'); $jobNode = \Drupal::routeMatch()->getParameter('node'); $jobNodeTitle = $jobNode->getTitle(); $companyNodeEntity = $jobNode->get('field_company'); $companyNode = \Drupal\node\Entity\Node::load($companyNodeEntity->entity->id()); $companyEmail = $companyNode->field_email->value; $resumeFileId = $form_state->getValue('resume'); $resumeFile = db_select('file_managed', 'f')->condition('f.fid', $resumeFileId, '=')->fields('f', array('uri'))->execute()->fetchField(); $atttachment = array('filepath' => $resumeFile); $module = 'job_mailer'; $key = 'apply_job'; $params['job_title'] = $jobNodeTitle; $params['message'] = "<html>\n <p>Please see attached resume for user: {$username}\n </html>"; $params['attachment'] = $atttachment; $langcode = \Drupal::currentUser()->getPreferredLangcode(); $send = true; $reply = \Drupal::config('system.site')->get('mail'); $result = $mailManager->mail($module, $key, $companyEmail, $langcode, $params, $reply, $send); db_insert('user_job_application')->fields(array('job_id' => $jobNode->id(), 'user_id' => $userId, 'date' => date('Y-m-d H:i:s')))->execute(); drupal_set_message('Your application has been sent.'); }
/** * @event kernel.controller * @priority 9999 * @param FilterControllerEvent $e */ static function onRequest($e) { if ($variants = Submodules::fastInvoke('route_alter_variants')[\Drupal::routeMatch()->getRouteName()] ?? NULL) { foreach ($variants as $variant) { if (!isset($variant['applies']) || is_callable($variant['applies']) && $variant['applies']()) { $e->setController($variant['controller']); break; } } } }
/** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items, $langcode) { // Get the current node. $node = \Drupal::routeMatch()->getParameter('node'); // Build the field quiz answer form $form_object = new FieldQuizAnswerForm($node, $items); $form = \Drupal::formBuilder()->getForm($form_object); $elements = array(); // Add the output to the node. $elements[] = $build['field_quiz'] = ['#theme' => 'field_quiz_question_view', '#form' => $form]; return $elements; }
/** * Access check, to be called from * - module.routing.yml * - hook_entity_operation * * @param \Drupal\workflow_operations\WorkflowTransitionInterface|NULL $transition * * @return \Drupal\Core\Access\AccessResult */ public function revertAccess(WorkflowTransitionInterface $transition = NULL, AccountInterface $account = NULL, $return_as_object = TRUE) { //public function access(EntityInterface $entity, $operation, AccountInterface $account = NULL, $return_as_object = FALSE) { if ($transition) { // Called from hook_entity_operation } else { // Called from module.routing.yml /* @var $transition WorkflowTransitionInterface */ $route_match = \Drupal::routeMatch(); $transition = $route_match->getParameter('workflow_transition'); } return $this->access($transition, 'revert', $account, $return_as_object); }
/** * Tests altering of the configuration translation forms. */ public function testConfigTranslationFormAlter() { $form_builder = \Drupal::formBuilder(); $add_form = $form_builder->getForm('Drupal\\config_translation\\Form\\ConfigTranslationAddForm', \Drupal::routeMatch(), $this->pluginId, $this->langcode); $edit_form = $form_builder->getForm('Drupal\\config_translation\\Form\\ConfigTranslationEditForm', \Drupal::routeMatch(), $this->pluginId, $this->langcode); // Test that hook_form_BASE_FORM_ID_alter() was called for the base form ID // 'config_translation_form'. $this->assertTrue($add_form['#base_altered']); $this->assertTrue($edit_form['#base_altered']); // Test that hook_form_FORM_ID_alter() was called for the form IDs // 'config_translation_add_form' and 'config_translation_edit_form'. $this->assertTrue($add_form['#altered']); $this->assertTrue($edit_form['#altered']); }
/** * Takes the user to the node creation page for the type of a given node. */ public function addAnotherAccess(NodeInterface $node) { if (!$node->access('create')) { return AccessResult::forbidden(); } $config = \Drupal::config('addanother.settings'); $account = \Drupal::currentUser(); $type = $node->getType(); if (\Drupal::routeMatch()->getRouteName() == 'entity.node.edit_form' && !$config->get('tab_edit.' . $type)) { return AccessResult::forbidden(); } if ($config->get('tab.' . $type) && $account->hasPermission('use add another')) { return AccessResult::allowed(); } return AccessResult::forbidden(); }
/** * Set the properly exception for event. */ public function onAccessDeniedException(GetResponseForExceptionEvent $event) { if ($event->getException() instanceof AccessDeniedHttpException) { $admin_only = \Drupal::config('m4032404.settings')->get('admin_only'); $route = \Drupal::routeMatch()->getRouteObject(); $is_admin = \Drupal::service('router.admin_context')->isAdminRoute($route); if ($admin_only && !$is_admin) { // @todo revisit this when r4032login is ready for 8.x. if (function_exists('r4032login_redirect')) { return r4032login_redirect(); } } else { $event->setException(new NotFoundHttpException()); } } }
/** * {@inheritdoc} */ public function build() { $id = $this->configuration['message']; // Figure out what page is being viewed. $path = \Drupal::routeMatch()->getRouteName(); $messages = $this->options(); if ($id == 0) { // Calculate which message to show based on a hash of the path and the // site's private key. The message initially chosen for each page on a // specific site will thus be pseudo-random, yet we will consistently // display the same message on any given page on that site. $private_key = \Drupal::service('private_key')->get(); $id = hexdec(substr(md5($path . $private_key), 0, 2)) % count($messages) + 1; } return array('#markup' => $messages[$id]); }
/** * {@inheritdoc} */ public function applies(RouteMatchInterface $route_match) { $this->oUser = \Drupal::currentUser(); $aUserRoles = $this->oUser->getRoles(); $bEditorRoleActive = FALSE; foreach ($aUserRoles as $sUserRole) { if ($sUserRole == 'editor') { $bEditorRoleActive = true; } } $route = \Drupal::routeMatch()->getRouteObject(); $bIsAdminPath = \Drupal::service('router.admin_context')->isAdminRoute($route); if ($bEditorRoleActive === TRUE && $bIsAdminPath === TRUE) { return true; } }
/** * Overrides \Drupal\Core\Entity\EntityFormController::submit(). */ public function submitForm(array &$form, FormStateInterface $form_state) { // Build the block object from the submitted values. parent::submitForm($form, $form_state); $field_collection_item = $this->entity; // TODO: Create new revision every edit? Might be better to make it an // option. In either case, it doesn't work as is. The default // revision of the host isn't getting updated to point to the new // field collection item revision. // $field_collection_item->setNewRevision(); if (\Drupal::routeMatch()->getRouteName() == 'field_collection_item.add_page') { $host = entity_load(\Drupal::routeMatch()->getParameter('host_type'), \Drupal::routeMatch()->getParameter('host_id')); } else { $host = $field_collection_item->getHost(); } $form_state->setRedirect($host->urlInfo()->getRouteName(), $host->urlInfo()->getRouteParameters()); }
/** * {@inheritdoc} */ public function preprocess(array &$variables, $hook, array $info) { $breadcrumb =& $variables['breadcrumb']; // Optionally get rid of the homepage link. $show_breadcrumb_home = $this->theme->getSetting('breadcrumb_home'); if (!$show_breadcrumb_home) { array_shift($breadcrumb); } if ($this->theme->getSetting('breadcrumb_title') && !empty($breadcrumb)) { $request = \Drupal::request(); $route_match = \Drupal::routeMatch(); $page_title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject()); if (!empty($page_title)) { $breadcrumb[] = ['text' => $page_title, 'attributes' => new Attribute(['class' => ['active']])]; } } }
/** * Custom function to return the active layout to be used for the active page. */ function omega_return_active_layout() { $theme = \Drupal::theme()->getActiveTheme()->getName(); $front = \Drupal::service('path.matcher')->isFrontPage(); $node = \Drupal::routeMatch()->getParameter('node'); $term = \Drupal::routeMatch()->getParameter('taxonomy_term'); //$view = \Drupal::routeMatch()->getParameter('view_id'); // setup default layout $defaultLayout = theme_get_setting('default_layout', $theme); $layout = $defaultLayout; // if it is a node, check for and assign alternate layout if ($node) { $type = $node->getType(); $nodeLayout = theme_get_setting('node_type_' . $type . '_layout', $theme); $layout = $nodeLayout ? $nodeLayout : $defaultLayout; } // if it is a views page, check for and assign alternate layout /* if ($view) { $viewData = Views::getView($view); //dsm($viewData); //$viewLayout = theme_get_setting('view_' . $view . '_layout'); //$layout = $viewLayout ? $viewLayout : $defaultLayout; } */ // if it is a term page, check for and assign alternate layout if ($term) { $vocab = $term->getVocabularyId(); $vocabLayout = theme_get_setting('taxonomy_' . $vocab . '_layout'); $layout = $vocabLayout ? $vocabLayout : $defaultLayout; } // if it is the front page, check for an alternate layout // this should come AFTER all other adjustments // This ensures if someone has set an individual node page, term page, etc. // as the front page, the front page setting has more priority if ($front) { $homeLayout = theme_get_setting('home_layout', $theme); $layout = $homeLayout ? $homeLayout : $defaultLayout; } return $layout; }
/** * Pre-processes variables for the "breadcrumb" theme hook. * * See theme function for list of available variables. * * @see bootstrap_breadcrumb() * @see theme_breadcrumb() * * @ingroup theme_preprocess */ function bootstrap_preprocess_breadcrumb(&$variables) { $breadcrumb =& $variables['breadcrumb']; // Optionally get rid of the homepage link. $show_breadcrumb_home = bootstrap_setting('breadcrumb_home'); if (!$show_breadcrumb_home) { array_shift($breadcrumb); } if (bootstrap_setting('breadcrumb_title') && !empty($breadcrumb)) { $request = \Drupal::request(); $route_match = \Drupal::routeMatch(); $page_title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject()); if (!empty($page_title)) { $breadcrumb[] = array('text' => $page_title, 'attributes' => new Attribute(array('class' => array('active')))); } } }
/** * {@inheritdoc} */ public function build() { $config = \Drupal::config('site_map.settings'); $route_name = \Drupal::routeMatch()->getRouteName(); if ($route_name == 'blog.user_rss') { $feedurl = Url::fromRoute('blog.user_rss', array('user' => \Drupal::routeMatch()->getParameter('user'))); } elseif ($route_name == 'blog.blog_rss') { $feedurl = Url::fromRoute('blog.blog_rss'); } else { $feedurl = $config->get('rss_front'); } $feed_icon = array('#theme' => 'feed_icon', '#url' => $feedurl, '#title' => t('Syndicate')); $output = drupal_render($feed_icon); // Re-use drupal core's render element. $more_link = array('#type' => 'more_link', '#url' => Url::fromRoute('site_map.page'), '#attributes' => array('title' => t('View the site map to see more RSS feeds.'))); $output .= drupal_render($more_link); return array('#type' => 'markup', '#markup' => $output); }
/** * {@inheritdoc} */ public function blockContents() { $sharethis_config = $this->configFactory->get('sharethis.settings'); $config = $this->configFactory->get('system.site'); if ($sharethis_config->get('location') == 'block') { // First Get all of the options for sharethis widget from database. $data_options = $this->getOptions(); $current_path = \Drupal::routeMatch()->getRouteName() ? Url::fromRouteMatch(\Drupal::routeMatch())->getInternalPath() : ''; $path = isset($current_path) ? $current_path : '<front>'; global $base_url; $path_obj = Url::fromUri($base_url . '/' . $path, array('absolute' => TRUE)); $m_path = $path_obj->toString(); $request = \Drupal::request(); $route_match = \Drupal::routeMatch(); $mtitle = $this->titleResolver->getTitle($request, $route_match->getRouteObject()); $m_title = is_object($mtitle) ? $mtitle->getUntranslatedString() : $config->get('name'); return $this->renderSpans($data_options, $m_title, $m_path); } }
/** * {@inheritdoc} */ public function preprocessVariables(Variables $variables, $hook, array $info) { /** @var \Drupal\filter\FilterFormatInterface $current_format */ $current_format = \Drupal::routeMatch()->getParameter('filter_format'); $current_format_id = $current_format ? $current_format->id() : FALSE; // Create a place holder for the tabs. $build['tabs'] = ['#theme' => 'item_list__filter_tips__tabs', '#items' => [], '#attributes' => ['class' => ['nav', 'nav-tabs', 'filter-formats'], 'role' => 'tablist']]; // Create a placeholder for the panes. $build['panes'] = ['#theme_wrappers' => ['container__filter_tips__panes'], '#attributes' => ['class' => ['tab-content']]]; foreach (filter_formats(\Drupal::currentUser()) as $format_id => $format) { // Set the current format ID to the first format. if (!$current_format_id) { $current_format_id = $format_id; } $tab = ['#type' => 'link', '#title' => $format->label(), '#url' => Url::fromRoute('filter.tips', ['filter_format' => $format_id]), '#attributes' => ['role' => 'tab', 'data-toggle' => 'tab', 'data-target' => "#{$format_id}"]]; if ($current_format_id === $format_id) { $tab['#wrapper_attributes']['class'][] = 'active'; } $build['tabs']['#items'][] = $tab; $tips = []; // Iterate over each format's enabled filters. /** @var \Drupal\filter\Plugin\FilterBase $filter */ foreach ($format->filters() as $name => $filter) { // Ignore filters that are not enabled. if (!$filter->status) { continue; } $tip = $filter->tips(TRUE); if (isset($tip)) { $tips[] = ['#markup' => $tip]; } } // Construct the pane. $pane = ['#theme_wrappers' => ['container__filter_tips'], '#attributes' => ['class' => ['tab-pane', 'fade'], 'id' => $format_id], 'list' => ['#theme' => 'item_list', '#items' => $tips]]; if ($current_format_id === $format_id) { $pane['#attributes']['class'][] = 'active'; $pane['#attributes']['class'][] = 'in'; } $build['panes'][] = $pane; } $variables['tips'] = $build; }
/** * A custom access check. * * @param \Drupal\Core\Session\AccountInterface $account * Run access checks for this account. */ public function access(AccountInterface $account) { // Check for available parameters. $nid = \Drupal::routeMatch()->getParameter('node'); $fid = \Drupal::routeMatch()->getParameter('file'); if ($nid && $fid) { // Update cover. $node = \Drupal\node\Entity\Node::load($nid); if (_photos_access('editAlbum', $node)) { // Allowed to update album cover image. return AccessResult::allowed(); } else { // Deny access. return AccessResult::forbidden(); } } elseif ($fid) { // Check if edit or delete. $current_path = \Drupal::service('path.current')->getPath(); $path_args = explode('/', $current_path); if (isset($path_args[4])) { if ($path_args[4] == 'edit' || $path_args[4] == 'to_sub') { if (_photos_access('imageEdit', $fid)) { // Allowed to edit image. return AccessResult::allowed(); } } elseif ($path_args[4] == 'delete') { if (_photos_access('imageDelete', $fid)) { // Allowed to delete image. return AccessResult::allowed(); } } } // Deny access. return AccessResult::forbidden(); } else { return AccessResult::neutral(); } }
public function securePagesRedirect() { $current_path = \Drupal::service('path.current')->getPath(); $current_route_name = \Drupal::routeMatch()->getRouteName(); //If user selected to force SSL for the entire site or //current page is the HTTPS test page, //there's no need to check pages and roles. if (!$this->securepages_entire_site && $current_route_name !== $this::SECURE_PAGES_TEST_HTTPS_CONNECTION_ROUTE) { $account = \Drupal::currentUser(); $page_match = $this->securePagesMatch($current_path); $role_match = $this->securePagesRoles($account); } else { $page_match = TRUE; $role_match = TRUE; } if ($this->request_method == 'POST') { $this->securePagesLog('POST request skipped in service', $this->path); } elseif ($this->is_https) { //Conditions for when current page is using HTTPS. if ($page_match === 0 && $this->securepages_switch && !$role_match) { $this->securePagesLog('Switch Path to insecure (Path: "@path")', $this->path); return FALSE; } } else { //Conditions for when current page is NOT using HTTPS if ($this->securepages_entire_site) { $this->securePagesLog('Switch to secure(force SSL for entire site)', $this->path); return TRUE; } elseif ($role_match) { $this->securePagesLog('Switch User to secure', $this->path); return TRUE; } elseif ($page_match) { $this->securePagesLog('Switch Path to secure', $this->path); return TRUE; } } return NULL; }
/** * Act on a specific type of entity before it is created or updated. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity object. * * @ingroup entity_crud * @see hook_entity_presave() */ function hook_ENTITY_TYPE_presave(Drupal\Core\Entity\EntityInterface $entity) { if ($entity->isTranslatable()) { $route_match = \Drupal::routeMatch(); \Drupal::service('content_translation.synchronizer')->synchronizeFields($entity, $entity->language()->getId(), $route_match->getParameter('source_langcode')); } }
/** * {@inheritdoc} */ public function viewExposedFormBlocks() { // Avoid interfering with the admin forms. $route_name = \Drupal::routeMatch()->getRouteName(); if (strpos($route_name, 'views_ui.') === 0) { return; } $this->view->initHandlers(); if ($this->usesExposed() && $this->getOption('exposed_block')) { $exposed_form = $this->getPlugin('exposed_form'); return $exposed_form->renderExposedForm(TRUE); } }
/** * {@inheritdoc} */ public function projectStorage($key) { $projects = array(); // On certain paths, we should clear the data and recompute the projects for // update status of the site to avoid presenting stale information. $route_names = array('update.theme_update', 'system.modules_list', 'system.theme_install', 'update.module_update', 'update.module_install', 'update.status', 'update.report_update', 'update.report_install', 'update.settings', 'system.status', 'update.manual_status', 'update.confirmation_page', 'system.themes_page'); if (in_array(\Drupal::routeMatch()->getRouteName(), $route_names)) { $this->keyValueStore->delete($key); } else { $projects = $this->keyValueStore->get($key, array()); } return $projects; }
/** * Provide a standard set of Apply/Cancel/OK buttons for the forms. Also provide * a hidden op operator because the forms plugin doesn't seem to properly * provide which button was clicked. * * TODO: Is the hidden op operator still here somewhere, or is that part of the * docblock outdated? */ public function getStandardButtons(&$form, FormStateInterface $form_state, $form_id, $name = NULL) { $form['actions'] = array('#type' => 'actions'); if (empty($name)) { $name = t('Apply'); if (!empty($this->stack) && count($this->stack) > 1) { $name = t('Apply and continue'); } $names = array(t('Apply'), t('Apply and continue')); } // Views provides its own custom handling of AJAX form submissions. Usually // this happens at the same path, but custom paths may be specified in // $form_state. $form_url = $form_state->get('url') ?: Url::fromRouteMatch(\Drupal::routeMatch()); // Forms that are purely informational set an ok_button flag, so we know not // to create an "Apply" button for them. if (!$form_state->get('ok_button')) { $form['actions']['submit'] = array('#type' => 'submit', '#value' => $name, '#id' => 'edit-submit-' . Html::getUniqueId($form_id), '#submit' => array(array($this, 'standardSubmit')), '#button_type' => 'primary', '#ajax' => array('url' => $form_url)); // Form API button click detection requires the button's #value to be the // same between the form build of the initial page request, and the // initial form build of the request processing the form submission. // Ideally, the button's #value shouldn't change until the form rebuild // step. However, \Drupal\views_ui\Form\Ajax\ViewsFormBase::getForm() // implements a different multistep form workflow than the Form API does, // and adjusts $view->stack prior to form processing, so we compensate by // extending button click detection code to support any of the possible // button labels. if (isset($names)) { $form['actions']['submit']['#values'] = $names; $form['actions']['submit']['#process'] = array_merge(array('views_ui_form_button_was_clicked'), \Drupal::service('element_info')->getInfoProperty($form['actions']['submit']['#type'], '#process', array())); } // If a validation handler exists for the form, assign it to this button. $form['actions']['submit']['#validate'][] = [$form_state->getFormObject(), 'validateForm']; } // Create a "Cancel" button. For purely informational forms, label it "OK". $cancel_submit = function_exists($form_id . '_cancel') ? $form_id . '_cancel' : array($this, 'standardCancel'); $form['actions']['cancel'] = array('#type' => 'submit', '#value' => !$form_state->get('ok_button') ? t('Cancel') : t('Ok'), '#submit' => array($cancel_submit), '#validate' => array(), '#ajax' => array('path' => $form_url), '#limit_validation_errors' => array()); // Compatibility, to be removed later: // TODO: When is "later"? // We used to set these items on the form, but now we want them on the $form_state: if (isset($form['#title'])) { $form_state->set('title', $form['#title']); } if (isset($form['#section'])) { $form_state->set('#section', $form['#section']); } // Finally, we never want these cached -- our object cache does that for us. $form['#no_cache'] = TRUE; }
/** * Collects the IDs of the visible nodes on the current page. * * @param int|null $nid * A node ID to save. * * @return array * The array of saved node IDs. */ public static function visibleNodes($nid = NULL) { static $nids = array(); if (isset($nid)) { $nids[$nid] = $nid; } elseif (empty($nids)) { ///** @var NodeInterface $node */ //$node = NULL; if ($node = \Drupal::routeMatch()->getParameter('node')) { $nid = $node->id(); $nids[$nid] = $nid; } } return $nids; }
/** * {@inheritdoc} */ function buildForm(array $form, FormStateInterface $form_state, array $build = NULL) { // Store the entity in the form state so we can easily create the job in the // submit handler. $form_state->set('entity', $build['#entity']); $overview = $build['content_translation_overview']; $form['#title'] = $this->t('Translations of @title', array('@title' => $build['#entity']->label())); $form['actions'] = array('#type' => 'details', '#title' => t('Operations'), '#open' => TRUE, '#attributes' => array('class' => array('tmgmt-source-operations-wrapper'))); $form['actions']['request'] = array('#type' => 'submit', '#button_type' => 'primary', '#value' => $this->t('Request translation'), '#submit' => array('::submitForm')); tmgmt_add_cart_form($form['actions'], $form_state, 'content', $form_state->get('entity')->getEntityTypeId(), $form_state->get('entity')->id()); // Inject our additional column into the header. array_splice($overview['#header'], -1, 0, array(t('Pending Translations'))); // Make this a tableselect form. $form['languages'] = array('#type' => 'tableselect', '#header' => $overview['#header'], '#options' => array()); $languages = \Drupal::languageManager()->getLanguages(); // Check if there is a job / job item that references this translation. $entity_langcode = $form_state->get('entity')->language()->getId(); $items = tmgmt_job_item_load_latest('content', $form_state->get('entity')->getEntityTypeId(), $form_state->get('entity')->id(), $entity_langcode); foreach ($languages as $langcode => $language) { if ($langcode == LanguageInterface::LANGCODE_DEFAULT) { // Never show language neutral on the overview. continue; } // Since the keys are numeric and in the same order we can shift one element // after the other from the original non-form rows. $option = array_shift($overview['#rows']); if ($langcode == $entity_langcode) { $additional = array('data' => array('#markup' => '<strong>' . t('Source') . '</strong>')); // This is the source object so we disable the checkbox for this row. $form['languages'][$langcode] = array('#type' => 'checkbox', '#disabled' => TRUE); } elseif (isset($items[$langcode])) { $item = $items[$langcode]; $states = JobItem::getStates(); $path = \Drupal::routeMatch()->getRouteName() ? Url::fromRouteMatch(\Drupal::routeMatch())->getInternalPath() : ''; $destination = array('destination' => $path); $additional = \Drupal::l($states[$item->getState()], $item->urlInfo()->setOption('query', $destination)); // Disable the checkbox for this row since there is already a translation // in progress that has not yet been finished. This way we make sure that // we don't stack multiple active translations for the same item on top // of each other. $form['languages'][$langcode] = array('#type' => 'checkbox', '#disabled' => TRUE); } else { // There is no translation job / job item for this target language. $additional = t('None'); } // Inject the additional column into the array. // The generated form structure has changed, support both an additional // 'data' key (that is not supported by tableselect) and the old version // without. if (isset($option['data'])) { array_splice($option['data'], -1, 0, array($additional)); // Append the current option array to the form. $form['languages']['#options'][$langcode] = $option['data']; } else { array_splice($option, -1, 0, array($additional)); // Append the current option array to the form. $form['languages']['#options'][$langcode] = $option; } } return $form; }
/** * Gets the route match. * * @return \Drupal\Core\Routing\RouteMatchInterface */ protected function getRouteMatch() { if (!$this->routeMatch) { $this->routeMatch = \Drupal::routeMatch(); } return $this->routeMatch; }