/**
  * Adds some descriptive text to our entity list.
  *
  * @return array
  *   Renderable array.
  */
 public function render()
 {
     $build['description'] = array('#markup' => $this->t("<p>This is a list of the countries currently" . " defined for use on your Drupal site. This country data adheres to" . " the @iso standard for country and zone naming used by payment" . " providers and package couriers.</p>" . "<p>To make a country available for use at checkout or in a user's" . " address book, 'Enable' the country using the widget in the" . " 'Operations' for that country. You may also 'Disable' a country to" . " prevent customers from selecting that country as a billing or" . " shipping address.</p>" . "<p>You may also use the 'Edit' widget in the 'Operations' column to" . " edit a country's name or address format.</p>", ['@iso' => Link::fromTextAndUrl('ISO 3166', Url::fromUri('http://en.wikipedia.org/wiki/ISO_3166'))->toString()]));
     $build += parent::render();
     $build['table']['#empty'] = $this->t('No countries have been configured yet.');
     return $build;
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $enabled_link = Link::fromTextAndUrl(t('enabled'), Url::fromRoute('system.modules_list'));
     $form['#attached']['library'][] = 'system/drupal.system';
     $form['exclude_node_title_search'] = ['#type' => 'checkbox', '#title' => $this->t('Remove node title from search pages'), '#description' => $this->t('Select if you wish to remove title from search pages. You need to have Search module @link.', ['@link' => $enabled_link]), '#default_value' => $this->excludeNodeTitleManager->isSearchExcluded(), '#disabled' => !\Drupal::moduleHandler()->moduleExists('search')];
     $form['content_type'] = ['#type' => 'fieldset', '#title' => $this->t('Exclude title by content types'), '#description' => $this->t('Define title excluding settings for each content type.'), '#collapsible' => TRUE, '#collapsed' => FALSE, '#tree' => TRUE];
     foreach ($this->bundleInfo->getBundleInfo('node') as $node_type => $node_type_info) {
         $form['#attached']['drupalSettings']['exclude_node_title']['content_types'][$node_type] = $node_type_info['label'];
         $form['content_type'][$node_type]['content_type_value'] = ['#type' => 'select', '#title' => $node_type_info['label'], '#default_value' => $this->excludeNodeTitleManager->getBundleExcludeMode($node_type), '#options' => ['none' => $this->t('None'), 'all' => $this->t('All nodes...'), 'user' => $this->t('User defined nodes...')]];
         $entity_view_modes = $this->entityDisplayRepository->getViewModes('node');
         $modes = [];
         foreach ($entity_view_modes as $view_mode_name => $view_mode_info) {
             $modes[$view_mode_name] = $view_mode_info['label'];
         }
         $modes += ['nodeform' => $this->t('Node form')];
         switch ($form['content_type'][$node_type]['content_type_value']['#default_value']) {
             case 'all':
                 $title = $this->t('Exclude title from all nodes in the following view modes:');
                 break;
             case 'user defined':
                 $title = $this->t('Exclude title from user defined nodes in the following view modes:');
                 break;
             default:
                 $title = $this->t('Exclude from:');
         }
         $form['content_type'][$node_type]['content_type_modes'] = ['#type' => 'checkboxes', '#title' => $title, '#default_value' => $this->excludeNodeTitleManager->getExcludedViewModes($node_type), '#options' => $modes, '#states' => ['invisible' => ['select[name="content_type[' . $node_type . '][content_type_value]"]' => ['value' => 'none']]]];
     }
     $form['#attached']['library'][] = 'exclude_node_title/drupal.exclude_node_title.admin';
     return parent::buildForm($form, $form_state);
 }
 /**
  * {@inheritdoc}
  */
 public function build(RouteMatchInterface $route_match)
 {
     $config = \Drupal::config('uc_cart.settings');
     $text = $config->get('breadcrumb_text');
     $links[] = Link::createFromRoute($this->t('Home'), '<front>');
     $links[] = Link::fromTextAndUrl($text, Url::fromUri('internal:/' . $config->get('breadcrumb_url'), ['absolute' => TRUE]));
     $breadcrumb = new Breadcrumb();
     $breadcrumb->setLinks($links);
     return $breadcrumb;
 }
 /**
  * {@inheritdoc}
  */
 public function buildConfigurationForm(array $form, FormStateInterface $form_state)
 {
     $form['wps_email'] = array('#type' => 'email', '#title' => $this->t('PayPal e-mail address'), '#description' => $this->t('The e-mail address you use for the PayPal account you want to receive payments.'), '#default_value' => $this->configuration['wps_email']);
     $form['wpp_server'] = array('#type' => 'select', '#title' => $this->t('API server'), '#description' => $this->t('Sign up for and use a Sandbox account for testing.'), '#options' => array('https://api-3t.sandbox.paypal.com/nvp' => $this->t('Sandbox'), 'https://api-3t.paypal.com/nvp' => $this->t('Live')), '#default_value' => $this->configuration['wpp_server']);
     $form['api'] = array('#type' => 'details', '#title' => $this->t('API credentials'), '#description' => $this->t('@link for information on obtaining credentials.  You need to acquire an API Signature.  If you have already requested API credentials, you can review your settings under the API Access section of your PayPal profile.', ['@link' => Link::fromTextAndUrl($this->t('Click here'), Url::fromUri('https://developer.paypal.com/docs/classic/api/apiCredentials/'))->toString()]), '#open' => TRUE);
     $form['api']['api_username'] = array('#type' => 'textfield', '#title' => $this->t('API username'), '#default_value' => $this->configuration['api']['api_username']);
     $form['api']['api_password'] = array('#type' => 'textfield', '#title' => $this->t('API password'), '#default_value' => $this->configuration['api']['api_password']);
     $form['api']['api_signature'] = array('#type' => 'textfield', '#title' => $this->t('Signature'), '#default_value' => $this->configuration['api']['api_signature']);
     return $form;
 }
 /**
  * Displays a list of an order's packaged products.
  *
  * @param \Drupal\uc_order\OrderInterface $uc_order
  *   The order.
  *
  * @return array|\Symfony\Component\HttpFoundation\RedirectResponse
  *   A render array, or a redirect response if there are no packaged products.
  */
 public function listOrderPackages(OrderInterface $uc_order)
 {
     $shipping_type_options = uc_quote_shipping_type_options();
     $header = array($this->t('Package ID'), $this->t('Products'), $this->t('Shipping type'), $this->t('Package type'), $this->t('Shipment ID'), $this->t('Tracking number'), $this->t('Labels'), $this->t('Actions'));
     $rows = array();
     $result = db_query('SELECT package_id FROM {uc_packages} WHERE order_id = :id', [':id' => $uc_order->id()]);
     while ($package_id = $result->fetchField()) {
         $package = Package::load($package_id);
         $row = array();
         // Package ID.
         $row[] = array('data' => array('#plain_text' => $package->package_id));
         $product_list = array();
         $result2 = db_query('SELECT op.order_product_id, pp.qty, op.title, op.model FROM {uc_packaged_products} pp LEFT JOIN {uc_order_products} op ON op.order_product_id = pp.order_product_id WHERE pp.package_id = :id', [':id' => $package->package_id]);
         foreach ($result2 as $product) {
             $product_list[] = $product->qty . ' x ' . $product->model;
         }
         // Products.
         $row[] = array('data' => array('#theme' => 'item_list', '#items' => $product_list));
         // Shipping type.
         $row[] = isset($shipping_type_options[$package->shipping_type]) ? $shipping_type_options[$package->shipping_type] : strtr($package->shipping_type, '_', ' ');
         // Package type.
         $row[] = array('data' => array('#plain_text' => $package->pkg_type));
         // Shipment ID.
         $row[] = isset($package->sid) ? Link::createFromRoute($package->sid, 'uc_fulfillment.view_shipment', ['uc_order' => $uc_order->id(), 'shipment_id' => $package->sid])->toString() : '';
         // Tracking number.
         $row[] = isset($package->tracking_number) ? array('data' => array('#plain_text' => $package->tracking_number)) : '';
         if ($package->label_image && ($image = file_load($package->label_image))) {
             $package->label_image = $image;
         } else {
             unset($package->label_image);
         }
         // Shipping label.
         if (isset($package->sid) && isset($package->label_image)) {
             $method = db_query('SELECT shipping_method FROM {uc_shipments} WHERE sid = :sid', [':sid' => $package->sid])->fetchField();
             $row[] = Link::fromTextAndUrl("image goes here", Url::fromUri('base:admin/store/orders/' . $uc_order->id() . '/shipments/labels/' . $method . '/' . $package->label_image->uri, ['uc_order' => $uc_order->id(), 'method' => $method, 'image_uri' => $package->label_image->uri]))->toString();
         } else {
             $row[] = '';
         }
         // Operations.
         $ops = array('#type' => 'operations', '#links' => array('edit' => array('title' => $this->t('Edit'), 'url' => Url::fromRoute('uc_fulfillment.edit_package', ['uc_order' => $uc_order->id(), 'package_id' => $package->package_id])), 'ship' => array('title' => $this->t('Ship'), 'url' => Url::fromRoute('uc_fulfillment.new_shipment', ['uc_order' => $uc_order->id()], ['query' => ['pkgs' => $package->package_id]])), 'delete' => array('title' => $this->t('Delete'), 'url' => Url::fromRoute('uc_fulfillment.delete_package', ['uc_order' => $uc_order->id(), 'package_id' => $package->package_id]))));
         if ($package->sid) {
             $ops['#links']['cancel'] = array('title' => $this->t('Cancel'), 'url' => Url::fromRoute('uc_fulfillment.cancel_package', ['uc_order' => $uc_order->id(), 'package_id' => $package->package_id]));
         }
         $row[] = array('data' => $ops);
         $rows[] = $row;
     }
     if (empty($rows)) {
         drupal_set_message($this->t("This order's products have not been organized into packages."), 'warning');
         return $this->redirect('uc_fulfillment.new_package', ['uc_order' => $uc_order->id()]);
     }
     $build['packages'] = array('#theme' => 'table', '#header' => $header, '#rows' => $rows);
     return $build;
 }
 /**
  * {@inheritdoc}
  */
 public function buildRow(EntityInterface $entity)
 {
     /* @var $entity \Drupal\search_api_page\SearchApiPageInterface */
     $row['label'] = $entity->label();
     $path = $entity->getPath();
     if (!empty($path)) {
         $row['path'] = Link::fromTextAndUrl($entity->getPath(), Url::fromRoute('search_api_page.' . \Drupal::languageManager()->getDefaultLanguage()->getId() . '.' . $entity->id()));
     } else {
         $row['path'] = '';
     }
     return $row + parent::buildRow($entity);
 }
示例#7
0
 /**
  * Text, if the user answered wrong.
  *
  * @param \Drupal\node\NodeInterface $node
  *   The node the client form belongs to.
  * @return array
  */
 public function sorry(NodeInterface $node)
 {
     $config = $this->config('field_quiz.settings');
     $text = $config->get('field_quiz.test_answer_wrong');
     $elements[] = array('#type' => 'html_tag', '#tag' => 'p', '#attributes' => array('style' => 'color: red'), '#value' => $this->t($text));
     $url = Url::fromRoute('entity.node.canonical', array('node' => $node->id()));
     $project_link = Link::fromTextAndUrl(t('Please try again.'), $url);
     $project_link = $project_link->toRenderable();
     // If you need some attributes.
     $project_link['#attributes'] = array('class' => array('button', 'button-action', 'button--primary', 'button--small'));
     $elements[] = array('#type' => 'html_tag', '#tag' => 'p', '#attributes' => array(), '#value' => render($project_link));
     return $elements;
 }
示例#8
0
 /**
  * {@inheritdoc}
  */
 public function settingsForm(array $form, FormStateInterface $form_state)
 {
     $image_styles = image_style_options(FALSE);
     $description_link = Link::fromTextAndUrl($this->t('Configure Image Styles'), Url::fromRoute('entity.image_style.collection'));
     $element['image_style'] = ['#title' => t('Image style'), '#type' => 'select', '#default_value' => $this->getSetting('image_style'), '#empty_option' => t('None (original image)'), '#options' => $image_styles, '#description' => $description_link->toRenderable() + ['#access' => $this->currentUser->hasPermission('administer image styles')]];
     $link_types = array('content' => t('Content'), 'file' => t('File'));
     $element['image_link'] = array('#title' => t('Link image to'), '#type' => 'select', '#default_value' => $this->getSetting('image_link'), '#empty_option' => t('Nothing'), '#options' => $link_types);
     $element['items'] = array('#type' => 'number', '#title' => $this->t('Items'), '#description' => $this->t('Maximum amount of items displayed at a time with the widest browser width.'), '#default_value' => $this->getSetting('items'));
     $element['itemsDesktop'] = array('#type' => 'textfield', '#title' => $this->t('Items Desktop'), '#description' => $this->t('This allows you to preset the number of slides visible with a particular browser width. The format is [x,y] whereby x=browser width and y=number of slides displayed. For example [1199,4] means that if(window<=1199){ show 4 slides per page}'), '#default_value' => $this->getSetting('itemsDesktop'));
     $element['itemsDesktopSmall'] = array('#type' => 'textfield', '#title' => $this->t('Items Desktop Small'), '#description' => $this->t('Example: [979,3]'), '#default_value' => $this->getSetting('itemsDesktopSmall'));
     $element['itemsTablet'] = array('#type' => 'textfield', '#title' => $this->t('Items Tablet'), '#description' => $this->t('Example: [768,2]'), '#default_value' => $this->getSetting('itemsTablet'));
     $element['itemsMobile'] = array('#type' => 'textfield', '#title' => $this->t('Items Mobile'), '#description' => $this->t('Example: [479,1]'), '#default_value' => $this->getSetting('itemsMobile'));
     $element['singleItem'] = array('#type' => 'checkbox', '#title' => $this->t('Single Item'), '#default_value' => $this->getSetting('singleItem'), '#description' => $this->t('Display only one item.'));
     //itemsScaleUp
     $element['itemsScaleUp'] = array('#type' => 'checkbox', '#title' => $this->t('Items ScaleUp'), '#default_value' => $this->getSetting('itemsScaleUp'), '#description' => $this->t('Option to not stretch items when it is less than the supplied items.'));
     //slideSpeed
     $element['slideSpeed'] = array('#type' => 'number', '#title' => $this->t('Slide Speed'), '#default_value' => $this->getSetting('slideSpeed'), '#description' => $this->t('Slide speed in milliseconds.'));
     //paginationSpeed
     $element['paginationSpeed'] = array('#type' => 'number', '#title' => $this->t('Pagination Speed'), '#default_value' => $this->getSetting('paginationSpeed'), '#description' => $this->t('Pagination speed in milliseconds.'));
     //rewindSpeed
     $element['rewindSpeed'] = array('#type' => 'number', '#title' => $this->t('Rewind Speed'), '#default_value' => $this->getSetting('rewindSpeed'), '#description' => $this->t('Rewind speed in milliseconds.'));
     //autoPlay
     $element['autoPlay'] = array('#type' => 'checkbox', '#title' => $this->t('AutoPlay'), '#default_value' => $this->getSetting('autoPlay'));
     //stopOnHover
     $element['stopOnHover'] = array('#type' => 'checkbox', '#title' => $this->t('Stop On Hover'), '#default_value' => $this->getSetting('stopOnHover'), '#description' => $this->t('Stop autoplay on mouse hover.'));
     //navigation
     $element['navigation'] = array('#type' => 'checkbox', '#title' => $this->t('Navigation'), '#default_value' => $this->getSetting('navigation'), '#description' => $this->t('Display "next" and "prev" buttons.'));
     //prevText
     $element['prevText'] = array('#type' => 'textfield', '#title' => $this->t('Prev Text'), '#default_value' => $this->getSetting('prevText'), '#description' => $this->t('Text for navigation prev button'));
     //nextText
     $element['nextText'] = array('#type' => 'textfield', '#title' => $this->t('Next Text'), '#default_value' => $this->getSetting('nextText'), '#description' => $this->t('Text for navigation next button'));
     //rewindNav
     $element['rewindNav'] = array('#type' => 'checkbox', '#title' => $this->t('Rewind Nav'), '#default_value' => $this->getSetting('rewindNav'), '#description' => $this->t('Slide to first item.'));
     //scrollPerPage
     $element['scrollPerPage'] = array('#type' => 'checkbox', '#title' => $this->t('Scroll Per Page'), '#default_value' => $this->getSetting('scrollPerPage'), '#description' => $this->t('Scroll per page not per item. This affect next/prev buttons and mouse/touch dragging.'));
     //pagination
     $element['pagination'] = array('#type' => 'checkbox', '#title' => $this->t('pagination'), '#default_value' => $this->getSetting('pagination'), '#description' => $this->t('Show pagination.'));
     //paginationNumbers
     $element['paginationNumbers'] = array('#type' => 'checkbox', '#title' => $this->t('Pagination Numbers'), '#default_value' => $this->getSetting('paginationNumbers'), '#description' => $this->t('Show numbers inside pagination buttons.'));
     //responsive
     $element['responsive'] = array('#type' => 'checkbox', '#title' => $this->t('Responsive'), '#default_value' => $this->getSetting('responsive'), '#description' => $this->t('Uncheck to use Owl Carousel on desktop-only.'));
     //responsiveRefreshRate
     $element['responsiveRefreshRate'] = array('#type' => 'number', '#title' => $this->t('Responsive Refresh Rate'), '#default_value' => $this->getSetting('responsiveRefreshRate'), '#description' => $this->t('Check window width changes every 200ms for responsive actions.'));
     //mouseDrag
     $element['mouseDrag'] = array('#type' => 'checkbox', '#title' => $this->t('Mouse Drag'), '#default_value' => $this->getSetting('mouseDrag'), '#description' => $this->t('Turn off/on mouse events.'));
     //touchDrag
     $element['touchDrag'] = array('#type' => 'checkbox', '#title' => $this->t('Touch Drag'), '#default_value' => $this->getSetting('touchDrag'), '#description' => $this->t('Turn off/on touch events.'));
     //transitionStyle
     $element['transitionStyle'] = array('#type' => 'select', '#options' => array('fade' => $this->t('Fade'), 'backSlide' => $this->t('Back Slide'), 'goDown' => $this->t('Go Down'), 'scaleUp' => $this->t('ScaleUp')), '#title' => $this->t('Transition Style'), '#default_value' => $this->getSetting('transitionStyle'), '#description' => $this->t('Add CSS3 transition style. Works only with one item on screen.'));
     return $element + parent::settingsForm($form, $form_state);
 }
示例#9
0
 /**
  * {@inheritdoc}
  */
 public function build()
 {
     $build = [];
     //$path_alias = \Drupal::service('path.alias_manager')->getAliasByPath('');
     //dpm("ALIAS = " . $path_alias);
     //$url = Url::fromRoute('contact.site_page');
     // @todo set internal paths in config
     $url = Url::fromUri('internal:/artists');
     $link = Link::fromTextAndUrl(t('Meet the Chalkers<span>Learn more about us</span>'), $url);
     $link = $link->toRenderable();
     $link['#attributes'] = array('class' => array('internal'));
     $linkMarkup = render($link);
     $output = ['#theme' => 'chalk_display_meet', '#meet_link' => $linkMarkup, '#video' => '', '#attached' => array('library' => array('chalk_display/chalk_display'))];
     $build['chalk_meet_block']['#markup'] = render($output);
     return $build;
 }
 /**
  * {@inheritdoc}
  */
 public function build(RouteMatchInterface $route_match)
 {
     $breadcrumb = new Breadcrumb();
     $node = $route_match->getParameter('node');
     // Homepage link.
     $links[] = Link::createFromRoute($this->t('Home'), '<front>');
     // First assigned tag.
     if (!empty($node->field_tags[0]->target_id)) {
         $tid = $node->field_tags[0]->target_id;
         $term_name = Term::load($tid)->get('name')->value;
         $links[] = Link::createFromRoute($term_name, 'entity.taxonomy_term.canonical', ['taxonomy_term' => $tid]);
     }
     // The node itself.
     $links[] = Link::fromTextAndUrl($node->getTitle(), Url::fromRoute('<current>'));
     $breadcrumb->addCacheContexts(['route']);
     return $breadcrumb->setLinks($links);
 }
示例#11
0
 /**
  * {@inheritdoc}
  */
 public function build()
 {
     $build = [];
     // @todo set internal paths in config
     // @todo refactoring needed
     $contactUrl = Url::fromUri('internal:/get-involved');
     $contactLink = Link::fromTextAndUrl(t('Get involved !'), $contactUrl);
     $contactLink = $contactLink->toRenderable();
     $contactLink['#attributes'] = array('class' => array('contact-link', 'internal'));
     $brochureUrl = Url::fromUri('internal:/sites/default/files/brochures/chalk-brochure-2016.pdf');
     $brochureLink = Link::fromTextAndUrl(t('Get our brochure [pdf]'), $brochureUrl);
     $brochureLink = $brochureLink->toRenderable();
     $brochureLink['#attributes'] = array('class' => array('brochure-link', 'internal'));
     $output = ['#theme' => 'chalk_display_footer', '#contact' => $this->contactMarkup(), '#contact_link' => render($contactLink), '#brochure_link' => render($brochureLink), '#social_links' => render($this->socialLinksList()), '#credits' => $this->creditsMarkup()];
     $build['chalk_footer_block']['#markup'] = render($output);
     return $build;
 }
示例#12
0
 /**
  * {@inheritdoc}
  */
 public function fieldSettingsForm(array $form, FormStateInterface $form_state)
 {
     $element = array();
     $field_settings = $this->getSettings();
     $embridge_settings = \Drupal::config('embridge.settings');
     /** @var EmbridgeCatalog[] $entities */
     $entities = EmbridgeCatalog::loadMultiple();
     $options = [];
     foreach ($entities as $entity) {
         $options[$entity->id()] = $entity->label();
     }
     $element['catalog_id'] = array('#type' => 'select', '#title' => t('Catalog'), '#default_value' => $field_settings['catalog_id'], '#options' => $options, '#description' => t("Select the Catalog to source media from for this field."), '#required' => TRUE, '#weight' => 6);
     $libraries_admin = Link::fromTextAndUrl('libraries admin', Url::fromUri($embridge_settings->get('uri') . '/' . $field_settings['catalog_id'] . '/views/modules/library/index.html'));
     $element['library_id'] = array('#type' => 'textfield', '#title' => t('Library'), '#default_value' => $field_settings['library_id'], '#description' => t("Limit uploads via this field to a specific library. This will also provide a default library on the asset search advanced filter. To identify the library ID, select the library on the @libraries_admin page and note the ID.", ['@libraries_admin' => $libraries_admin->toString()]), '#required' => FALSE, '#size' => 10, '#weight' => 6);
     $element['allow_search'] = array('#type' => 'checkbox', '#title' => t('Allow search'), '#default_value' => $field_settings['allow_search'], '#description' => t("Check this to allow users to search EMDB for existing assets, requires <em>search embridge assets</em> permission."), '#weight' => 6);
     return $element + parent::fieldSettingsForm($form, $form_state);
 }
 /**
  * {@inheritdoc}
  */
 public function preprocessVariables(Variables $variables, $hook, array $info)
 {
     $options = [];
     $file = $variables['file'] instanceof File ? $variables['file'] : File::load($variables['file']->fid);
     $url = file_create_url($file->getFileUri());
     $file_size = $file->getSize();
     $mime_type = $file->getMimeType();
     // Set options as per anchor format described at
     // http://microformats.org/wiki/file-format-examples
     $options['attributes']['type'] = "{$mime_type}; length={$file_size}";
     // Use the description as the link text if available.
     if (empty($variables['description'])) {
         $link_text = $file->getFilename();
     } else {
         $link_text = $variables['description'];
         $options['attributes']['title'] = $file->getFilename();
     }
     // Retrieve the generic mime type from core (mislabeled as "icon_class").
     $generic_mime_type = file_icon_class($mime_type);
     // Map the generic mime types to an icon and state.
     $mime_map = ['application-x-executable' => ['label' => t('binary file'), 'icon' => 'console'], 'audio' => ['label' => t('audio file'), 'icon' => 'headphones'], 'image' => ['label' => t('image'), 'icon' => 'picture'], 'package-x-generic' => ['label' => t('archive'), 'icon' => 'compressed'], 'text' => ['label' => t('document'), 'icon' => 'file'], 'video' => ['label' => t('video'), 'icon' => 'film']];
     // Retrieve the mime map array.
     $mime = isset($mime_map[$generic_mime_type]) ? $mime_map[$generic_mime_type] : ['label' => t('file'), 'icon' => 'file', 'state' => 'primary'];
     // Classes to add to the file field for icons.
     //    $variables->addClass([
     //      'file',
     //      // Add a specific class for each and every mime type.
     //      'file--mime-' . strtr($mime_type, ['/' => '-', '.' => '-']),
     //      // Add a more general class for groups of well known mime types.
     //      'file--' . $generic_mime_type,
     //    ]);
     // Set the icon for the mime type.
     $icon = Materialize::material_icons_font($mime['icon']);
     $variables->icon = Element::create($icon)->addClass('text-primary')->getArray();
     $options['attributes']['title'] = t('Open @mime in new window', ['@mime' => $mime['label']]);
     if ($this->theme->getSetting('tooltip_enabled')) {
         $options['attributes']['data-toggle'] = 'tooltip';
         $options['attributes']['data-placement'] = 'bottom';
     }
     $variables['link'] = Link::fromTextAndUrl($link_text, Url::fromUri($url, $options));
     // Add the file size as a variable.
     $variables->file_size = format_size($file_size);
     // Preprocess attributes.
     $this->preprocessAttributes($variables, $hook, $info);
 }
示例#14
0
 /**
  * {@inheritdoc}
  */
 public function form(array $form, FormStateInterface $form_state)
 {
     $form = parent::form($form, $form_state);
     $task_item = $this->entity;
     $form['#title'] = $task_item->label();
     $job_item = $task_item->getJobItem();
     $job = $job_item->getJob();
     $form['info'] = array('#type' => 'container', '#attributes' => array('class' => array('tmgmt-local-task-info', 'clearfix')), '#weight' => 0);
     $url = $job_item->getSourceUrl();
     $form['info']['source'] = array('#type' => 'item', '#title' => t('Source'), '#markup' => $url ? Link::fromTextAndUrl($job_item->getSourceLabel(), $url)->toString() : $job_item->getSourceLabel(), '#prefix' => '<div class="tmgmt-ui-source tmgmt-ui-info-item">', '#suffix' => '</div>');
     $form['info']['sourcetype'] = array('#type' => 'item', '#title' => t('Source type'), '#markup' => $job_item->getSourceType(), '#prefix' => '<div class="tmgmt-ui-source-type tmgmt-ui-info-item">', '#suffix' => '</div>');
     $form['info']['source_language'] = array('#type' => 'item', '#title' => t('Source language'), '#markup' => $job_item->getJob()->getSourceLanguage()->getName(), '#prefix' => '<div class="tmgmt-ui-source-language tmgmt-ui-info-item">', '#suffix' => '</div>');
     $form['info']['target_language'] = array('#type' => 'item', '#title' => t('Target language'), '#markup' => $job_item->getJob()->getTargetLanguage()->getName(), '#prefix' => '<div class="tmgmt-ui-target-language tmgmt-ui-info-item">', '#suffix' => '</div>');
     $form['info']['changed'] = array('#type' => 'item', '#title' => t('Last change'), '#value' => $task_item->getChangedTime(), '#markup' => \Drupal::service('date.formatter')->format($task_item->getChangedTime()), '#prefix' => '<div class="tmgmt-ui-changed tmgmt-ui-info-item">', '#suffix' => '</div>');
     $statuses = LocalTaskItem::getStatuses();
     $form['info']['status'] = array('#type' => 'item', '#title' => t('Status'), '#markup' => $statuses[$task_item->getStatus()], '#prefix' => '<div class="tmgmt-ui-task-item-status tmgmt-ui-info-item">', '#suffix' => '</div>', '#value' => $task_item->getStatus());
     $task = $task_item->getTask();
     $url = $task->toUrl();
     $form['info']['task'] = array('#type' => 'item', '#title' => t('Task'), '#markup' => Link::fromTextAndUrl($task->label(), $url)->toString(), '#prefix' => '<div class="tmgmt-ui-task tmgmt-ui-info-item">', '#suffix' => '</div>');
     if ($job->getSetting('job_comment')) {
         $form['job_comment'] = array('#type' => 'item', '#title' => t('Job comment'), '#markup' => Xss::filter($job->getSetting('job_comment')));
     }
     $form['translation'] = array('#type' => 'container');
     // Build the translation form.
     $data = $task_item->getData();
     // Need to keep the first hierarchy. So flatten must take place inside
     // of the foreach loop.
     $zebra = 'even';
     foreach (Element::children($data) as $key) {
         $flattened = \Drupal::service('tmgmt.data')->flatten($data[$key], $key);
         $form['translation'][$key] = $this->formElement($flattened, $task_item, $zebra);
     }
     $form['footer'] = tmgmt_color_local_review_legend();
     $form['#attached']['library'][] = 'tmgmt/admin';
     return $form;
 }
示例#15
0
文件: DnaBlock.php 项目: Nesta/ddv8
 /**
  * Builds and returns the node information.
  *
  * @param bool $debug_mode
  *   The level of detail to include.
  *
  * @return array
  */
 public static function buildNodeInfo($debug_mode)
 {
     global $user;
     $visible_nodes = self::visibleNodes();
     if (count($visible_nodes) == 0) {
         return array();
     } else {
         $single_nid = reset($visible_nodes);
     }
     // Find out whether our DnaUser block is active or not.
     //dpm($blocks = \Drupal::entityTypeManager()->getStorage('block')->load());
     $user_block_active = FALSE;
     //foreach ($blocks as $block) {
     //  if ($block->get('plugin') == 'devel_dna_user_block') {
     //    $user_block_active = TRUE;
     //  }
     //}
     // Include rows where nid == 0.
     $nids = array_merge(array(0 => 0), $visible_nodes);
     $query = \Drupal::database()->select('node_access', 'na');
     $query->fields('na')->condition('na.nid', $nids, 'IN');
     $query->orderBy('na.nid')->orderBy('na.realm')->orderBy('na.gid');
     $nodes = Node::loadMultiple($nids);
     if (!$debug_mode) {
         $headers = array('node', 'realm', 'gid', 'view', 'update', 'delete', 'explained');
         $rows = array();
         foreach ($query->execute() as $row) {
             $explained = \Drupal::moduleHandler()->invokeAll('node_access_explain', [$row]);
             $node_title = self::get_node_title($nodes[$row->nid]);
             $title_attribute = \Drupal::request()->getRequestUri();
             if (Unicode::strlen($node_title) > 20) {
                 $title_attribute = $title_attribute . ': ' . $node_title;
                 $node_title = Unicode::substr($node_title, 0, 18) . '...';
             }
             $rows[] = array(empty($row->nid) ? '0' : Link::fromTextAndUrl($node_title, Url::fromUri(\Drupal::request()->getUri(), ['fragment' => 'node-' . $row->nid, 'attributes' => ['title' => $title_attribute]])), $row->realm, $row->gid, $row->grant_view, $row->grant_update, $row->grant_delete, implode('<br />', $explained));
         }
         $output[] = array('#theme' => 'table', '#header' => $headers, '#rows' => $rows, '#attributes' => array('style' => 'text-align: left'));
     } else {
         $tr = 't';
         $variables = array('!na' => '{node_access}');
         $states = array('default' => array(t('default'), 'ok', t('Default record supplied by core in the absence of any other non-empty records; in !na.', $variables)), 'ok' => array(t('ok'), 'ok', t('Highest priority record; in !na.', $variables)), 'removed' => array(t('removed'), '', t('Was removed in @func; not in !na.', $variables + array('@func' => 'hook_node_access_records_alter()'))), 'static' => array(t('static'), 'ok', t('Non-standard record in !na.', $variables)), 'unexpected' => array(t('unexpected'), 'warning', t('The 0/all/0/... record applies to all nodes and all users -- usually it should not be present in !na if any node access module is active!')), 'ignored' => array(t('ignored'), 'warning', t('Lower priority record; not in !na and thus ignored.', $variables)), 'empty' => array(t('empty'), 'warning', t('Does not grant any access, but could block lower priority records; not in !na.', $variables)), 'wrong' => array(t('wrong'), 'error', t('Is rightfully in !na but at least one access flag is wrong!', $variables)), 'missing' => array(t('missing'), 'error', t("Should be in !na but isn't!", $variables)), 'removed!' => array(t('removed!'), 'error', t('Was removed in @func; should NOT be in !na!', $variables + array('@func' => 'hook_node_access_records_alter()'))), 'illegitimate' => array(t('illegitimate'), 'error', t('Should NOT be in !na because of lower priority!', $variables)), 'alien' => array(t('alien'), 'error', t('Should NOT be in !na because of unknown origin!', $variables)));
         $active_states = array('default', 'ok', 'static', 'unexpected', 'wrong', 'illegitimate', 'alien');
         $headers = array(t('node'), t('prio'), t('status'), t('realm'), t('gid'), t('view'), t('update'), t('delete'), t('explained'));
         $headers = self::format_row($headers);
         $active_records = array();
         foreach ($query->execute() as $active_record) {
             $active_records[$active_record->nid][$active_record->realm][$active_record->gid] = $active_record;
         }
         $all_records = $grants_data = $checked_grants = $grants = array();
         foreach (array('view', 'update', 'delete') as $op) {
             $grants[$op] = self::simulate_module_invoke_all('node_grants', $user, $op);
             // Call all hook_node_grants_alter() implementations.
             $grants_data[$op] = self::simulate_node_grants_alter($grants[$op], $user, $op);
         }
         foreach ($nids as $nid) {
             $top_priority = -99999;
             $acquired_records_nid = array();
             if ($node = Node::load($nid)) {
                 // Check node_access_acquire_grants().
                 $records = self::simulate_module_invoke_all('node_access_records', $node);
                 // Check drupal_alter('node_access_records').
                 $data = self::simulate_node_access_records_alter($records, $node);
                 if (!empty($data)) {
                     foreach ($data as $data_by_realm) {
                         foreach ($data_by_realm as $data_by_realm_gid) {
                             if (isset($data_by_realm_gid['current'])) {
                                 $record = $data_by_realm_gid['current'];
                             } elseif (isset($data_by_realm_gid['original'])) {
                                 $record = $data_by_realm_gid['original'];
                                 $record['#removed'] = 1;
                             } else {
                                 continue;
                             }
                             $priority = intval(isset($record['priority']) ? $record['priority'] : 0);
                             $top_priority = isset($top_priority) ? max($top_priority, $priority) : $priority;
                             $record['priority'] = isset($record['priority']) ? $priority : '&ndash;&nbsp;';
                             $record['history'] = $data_by_realm_gid;
                             $acquired_records_nid[$priority][$record['realm']][$record['gid']] = $record + array('#title' => self::get_node_title($node), '#module' => isset($record['#module']) ? $record['#module'] : '');
                         }
                     }
                     krsort($acquired_records_nid);
                 }
                 //dpm($acquired_records_nid, "acquired_records_nid =");
                 // Check node_access_grants().
                 if ($node->id()) {
                     foreach (array('view', 'update', 'delete') as $op) {
                         $checked_grants[$nid][$op] = array_merge(array('all' => array(0)), $grants[$op]);
                     }
                 }
             }
             // Check for records in the node_access table that aren't returned by
             // node_access_acquire_grants().
             if (isset($active_records[$nid])) {
                 foreach ($active_records[$nid] as $realm => $active_records_realm) {
                     foreach ($active_records_realm as $gid => $active_record) {
                         $found = FALSE;
                         $count_nonempty_records = 0;
                         foreach ($acquired_records_nid as $priority => $acquired_records_nid_priority) {
                             if (isset($acquired_records_nid_priority[$realm][$gid])) {
                                 $found = TRUE;
                             }
                         }
                         // Take the highest priority only.
                         // TODO This has changed in D8!
                         if ($acquired_records_nid_priority = reset($acquired_records_nid)) {
                             foreach ($acquired_records_nid_priority as $acquired_records_nid_priority_realm) {
                                 foreach ($acquired_records_nid_priority_realm as $acquired_records_nid_priority_realm_gid) {
                                     $count_nonempty_records += !empty($acquired_records_nid_priority_realm_gid['grant_view']) || !empty($acquired_records_nid_priority_realm_gid['grant_update']) || !empty($acquired_records_nid_priority_realm_gid['grant_delete']);
                                 }
                             }
                         }
                         $fixed_record = (array) $active_record;
                         if ($count_nonempty_records == 0 && $realm == 'all' && $gid == 0) {
                             $fixed_record += array('priority' => '&ndash;', 'state' => 'default');
                         } elseif (!$found) {
                             $acknowledged = self::simulate_module_invoke_all('node_access_acknowledge', $fixed_record);
                             if (empty($acknowledged)) {
                                 // No module acknowledged this record, mark it as alien.
                                 $fixed_record += array('priority' => '?', 'state' => 'alien');
                             } else {
                                 // At least one module acknowledged the record,
                                 // attribute it to the first one.
                                 $fixed_record += array('priority' => '&ndash;', 'state' => 'static', '#module' => reset(array_keys($acknowledged)));
                             }
                         } else {
                             continue;
                         }
                         $fixed_record += array('nid' => $nid, '#title' => self::get_node_title($node));
                         $all_records[] = $fixed_record;
                     }
                 }
             }
             // Order records and evaluate their status.
             foreach ($acquired_records_nid as $priority => $acquired_records_priority) {
                 ksort($acquired_records_priority);
                 foreach ($acquired_records_priority as $realm => $acquired_records_realm) {
                     ksort($acquired_records_realm);
                     foreach ($acquired_records_realm as $gid => $acquired_record) {
                         // TODO: Handle priority.
                         //if ($priority == $top_priority) {
                         if (empty($acquired_record['grant_view']) && empty($acquired_record['grant_update']) && empty($acquired_record['grant_delete'])) {
                             $acquired_record['state'] = 'empty';
                         } else {
                             if (isset($active_records[$nid][$realm][$gid])) {
                                 $acquired_record['state'] = isset($acquired_record['#removed']) ? 'removed!' : 'ok';
                             } else {
                                 $acquired_record['state'] = isset($acquired_record['#removed']) ? 'removed' : 'missing';
                             }
                             if ($acquired_record['state'] == 'ok') {
                                 foreach (array('view', 'update', 'delete') as $op) {
                                     $active_record = (array) $active_records[$nid][$realm][$gid];
                                     if (empty($acquired_record["grant_{$op}"]) != empty($active_record["grant_{$op}"])) {
                                         $acquired_record["grant_{$op}!"] = $active_record["grant_{$op}"];
                                     }
                                 }
                             }
                         }
                         //}
                         //else {
                         //  $acquired_record['state'] = (isset($active_records[$nid][$realm][$gid]) ? 'illegitimate' : 'ignored');
                         //}
                         $all_records[] = $acquired_record + array('nid' => $nid);
                     }
                 }
             }
         }
         // Fill in the table rows.
         $rows = array();
         $error_count = 0;
         foreach ($all_records as $record) {
             $row = new \stdClass();
             $row->nid = $record['nid'];
             $row->title = $record['#title'];
             $row->priority = $record['priority'];
             $row->state = array('data' => $states[$record['state']][0], 'title' => $states[$record['state']][2]);
             $row->realm = $record['realm'];
             $row->gid = $record['gid'];
             $row->grant_view = $record['grant_view'];
             $row->grant_update = $record['grant_update'];
             $row->grant_delete = $record['grant_delete'];
             $row->explained = implode('<br />', \Drupal::moduleHandler()->invokeAll('node_access_explain', $row));
             unset($row->title);
             if ($row->nid == 0 && $row->gid == 0 && $row->realm == 'all' && count($all_records) > 1) {
                 $row->state = array('data' => $states['unexpected'][0], 'title' => $states['unexpected'][2]);
                 $class = $states['unexpected'][1];
             } else {
                 $class = $states[$record['state']][1];
             }
             $row = (array) $row;
             foreach (array('view', 'update', 'delete') as $op) {
                 $row["grant_{$op}"] = array('data' => $row["grant_{$op}"]);
                 if ((isset($checked_grants[$record['nid']][$op][$record['realm']]) && in_array($record['gid'], $checked_grants[$record['nid']][$op][$record['realm']]) || $row['nid'] == 0 && $row['gid'] == 0 && $row['realm'] == 'all') && !empty($row["grant_{$op}"]['data']) && in_array($record['state'], $active_states)) {
                     $row["grant_{$op}"]['data'] .= '&prime;';
                     $row["grant_{$op}"]['title'] = t('This entry grants access to this node to this user.');
                 }
                 if (isset($record["grant_{$op}!"])) {
                     $row["grant_{$op}"]['data'] = $record["grant_{$op}!"] . '&gt;' . (!$row["grant_{$op}"]['data'] ? 0 : $row["grant_{$op}"]['data']);
                     $row["grant_{$op}"]['class'][] = 'error';
                     if ($class == 'ok') {
                         $row['state'] = array('data' => $states['wrong'][0], 'title' => $states['wrong'][2]);
                         $class = $states['wrong'][1];
                     }
                 }
             }
             $error_count += $class == 'error';
             $row['nid'] = array('data' => '<a href="#node-' . $record['nid'] . '">' . $row['nid'] . '</a>', 'title' => $record['#title']);
             if (empty($record['#module']) || strpos($record['realm'], $record['#module']) === 0) {
                 $row['realm'] = $record['realm'];
             } else {
                 $row['realm'] = array('data' => '(' . $record['#module'] . '::) ' . $record['realm'], 'title' => t("The '@module' module fails to adhere to the best practice of naming its realm(s) after itself.", array('@module' => $record['#module'])));
             }
             // Prepend information from the D7 hook_node_access_records_alter().
             $next_style = array();
             if (isset($record['history'])) {
                 $history = $record['history'];
                 if (($num_changes = count($history['changes']) - empty($history['current'])) > 0) {
                     $first_row = TRUE;
                     while (isset($history['original']) || $num_changes--) {
                         if (isset($history['original'])) {
                             $this_record = $history['original'];
                             $this_action = '[ Original by ' . $this_record['#module'] . ':';
                             unset($history['original']);
                         } else {
                             $change = $history['changes'][0];
                             $this_record = $change['record'];
                             $this_action = ($first_row ? '[ ' : '') . $change['op'] . ':';
                             array_shift($history['changes']);
                         }
                         $rows[] = array('data' => array('data' => array('data' => $this_action, 'style' => array('padding-bottom: 0;'))), 'style' => array_merge($first_row ? array() : array('border-top-style: dashed;', 'border-top-width: 1px;'), array('border-bottom-style: none;')));
                         $next_style = array('border-top-style: none;');
                         if (count($history['changes'])) {
                             $g = $this_record;
                             $rows[] = array('data' => array('v', $g['priority'], '', $g['realm'], $g['gid'], $g['grant_view'], $g['grant_update'], $g['grant_delete'], 'v'), 'style' => array('border-top-style: none;', 'border-bottom-style: dashed;'));
                             $next_style = array('border-top-style: dashed;');
                         }
                         $first_row = FALSE;
                     }
                 }
             }
             // Fix up the main row cells with the proper class (needed for Bartik).
             foreach ($row as $key => $value) {
                 if (!is_array($value)) {
                     $row[$key] = array('data' => $value);
                 }
                 $row[$key]['class'] = array($class);
             }
             // Add the main row.
             $will_append = empty($history['current']) && !empty($history['changes']);
             $rows[] = array('data' => array_values($row), 'class' => array($class), 'style' => array_merge($next_style, $will_append ? array('border-bottom-style: none;') : array()));
             // Append information from the D7 hook_node_access_records_alter().
             if ($will_append) {
                 $last_change = end($history['changes']);
                 $rows[] = array('data' => array('data' => array('data' => $last_change['op'] . ' ]', 'style' => array('padding-top: 0;'))), 'style' => array('border-top-style: none;'));
             }
         }
         foreach ($rows as $i => $row) {
             $rows[$i] = self::format_row($row);
         }
         $output[] = array('#theme' => 'table', '#header' => $headers, '#rows' => $rows, '#attributes' => array('class' => array('system-status-report'), 'style' => 'text-align: left;'));
         $output[] = array('#theme' => 'form_element', '#description' => t('(Some of the table elements provide additional information if you hover your mouse over them.)'));
         if ($error_count > 0) {
             $variables['!Rebuild_permissions'] = '<a href="' . url('admin/reports/status/rebuild') . '">' . $tr('Rebuild permissions') . '</a>';
             $output[] = array('#prefix' => "\n<span class=\"error\">", '#markup' => t("You have errors in your !na table! You may be able to fix these for now by running !Rebuild_permissions, but this is likely to destroy the evidence and make it impossible to identify the underlying issues. If you don't fix those, the errors will probably come back again. <br /> DON'T do this just yet if you intend to ask for help with this situation.", $variables), '#suffix' => "</span><br />\n");
         }
         // Explain whether access is granted or denied, and why
         // (using code from node_access()).
         $tr = 't';
         array_shift($nids);
         // Remove the 0.
         $accounts = array();
         $variables += array('!username' => '<em class="placeholder">' . $user->getDisplayName() . '</em>', '%uid' => $user->id());
         if (\Drupal::currentUser()->hasPermission('bypass node access')) {
             $variables['%bypass_node_access'] = $tr('bypass node access');
             $output[] = array('#markup' => t('!username has the %bypass_node_access permission and thus full access to all nodes.', $variables), '#suffix' => '<br />&nbsp;');
         } else {
             $variables['!list'] = '<div style="margin-left: 2em">' . self::get_grant_list($grants_data['view']) . '</div>';
             $variables['%access'] = 'view';
             $output[] = array('#prefix' => "\n<div style='text-align: left' title='" . t('These are the grants returned by hook_node_grants() for this user.') . "'>", '#markup' => t('!username (user %uid) can use these grants (if they are present above) for %access access: !list', $variables), '#suffix' => "</div>\n");
             $accounts[] = $user;
         }
         if (isset($single_nid) && !$user_block_active) {
             // Only for single nodes.
             if (\Drupal::currentUser()->isAuthenticated()) {
                 $accounts[] = User::load(0);
                 // Anonymous, too.
             }
             foreach ($accounts as $account) {
                 $nid_items = array();
                 foreach ($nids as $nid) {
                     $op_items = array();
                     foreach (array('create', 'view', 'update', 'delete') as $op) {
                         $explain = self::explainAccess($op, Node::load($nid), $account);
                         $op_items[] = "<div style='width: 5em; display: inline-block'>" . t('%op:', array('%op' => $op)) . ' </div>' . $explain[2];
                     }
                     $nid_items[] = array('#theme' => 'item_list', '#items' => $op_items, '#type' => 'ul', '#prefix' => t('to node !nid:', array('!nid' => l($nid, 'node/' . $nid))) . "\n<div style='margin-left: 2em'>", '#suffix' => '</div>');
                 }
                 if (count($nid_items) == 1) {
                     $account_items = $nid_items[0];
                 } else {
                     $account_items = array('#theme' => 'item_list', '#items' => $nid_items, '#type' => 'ul', '#prefix' => "\n<div style='margin-left: 2em'>", '#suffix' => '</div>');
                 }
                 $variables['!username'] = '******' . theme('username', array('account' => $account)) . '</em>';
                 $output[] = array('#prefix' => "\n<div style='text-align: left'>", '#type' => 'item', 'lead-in' => array('#markup' => t("!username has the following access", $variables) . ' '), 'items' => $account_items, '#suffix' => "\n</div>\n");
             }
         }
     }
     return $output;
 }
示例#16
0
 /**
  * The controller for the meteor.backlink route.
  *
  * @return array
  *   The render array for the Meteor backlink.
  */
 public function backlink()
 {
     $server_uri = Url::fromUri($this->meteorSettings->get('meteor_server'));
     $ret = Link::fromTextAndUrl("Go to Meteor", $server_uri)->toRenderable();
     return $ret;
 }
示例#17
0
 /**
  * {@inheritdoc}
  */
 public function settingsForm(array $form, FormStateInterface $form_state)
 {
     $image_styles = image_style_options(FALSE);
     $description_link = Link::fromTextAndUrl($this->t('Configure Image Styles'), Url::fromRoute('entity.image_style.collection'));
     $element['image_style'] = ['#title' => t('Image style'), '#type' => 'select', '#default_value' => $this->getSetting('image_style'), '#empty_option' => t('None (original image)'), '#options' => $image_styles, '#description' => $description_link->toRenderable() + ['#access' => $this->currentUser->hasPermission('administer image styles')]];
     $link_types = array('content' => t('Content'), 'file' => t('File'));
     $element['image_link'] = array('#title' => t('Link image to'), '#type' => 'select', '#default_value' => $this->getSetting('image_link'), '#empty_option' => t('Nothing'), '#options' => $link_types);
     return $element;
 }
示例#18
0
 /**
  * Validate the correct version for thumbnail options.
  */
 public function validateMinimumVersion22(array &$element, FormStateInterface $form_state)
 {
     $lib = libraries_detect('flexslider');
     if (!isset($lib['version'])) {
         drupal_set_message(t('Unable to detect FlexSlider library version. Some options may not function properly. Please review the README.md file for installation instructions.'), 'warning');
     } else {
         $version = $lib['version'];
         $required = "2.2";
         if ($element['#value'] && !version_compare($version, $required, '>=')) {
             $form_state->setError($element, t('To use %name you must install FlexSlider version !required or higher.', array('%name' => $element['#title'], '!required' => \Drupal\Core\Link::fromTextAndUrl($required, \Drupal\Core\Url::fromUri('https://github.com/woothemes/FlexSlider/tree/version/2.2')))));
         }
     }
 }
示例#19
0
 /**
  * Overrides Drupal\Core\Entity\EntityFormController::save().
  *
  * Saves the entity. This is called after submit() has built the entity from
  * the form values. Do not override submit() as save() is the preferred
  * method for entity form controllers.
  *
  * @param array $form
  *   An associative array containing the structure of the form.
  * @param \Drupal\Core\Form\FormStateInterface $form_state
  *   An associative array containing the current state of the form.
  *
  * @return int
  *   Either SAVED_NEW or SAVED_UPDATED, depending on the operation performed.
  */
 public function save(array $form, FormStateInterface $form_state)
 {
     // EntityForm provides us with the entity we're working on.
     /** @var FlagMapping $mapping */
     $mapping = $this->getEntity();
     // Drupal already populated the form values in the entity object. Each
     // form field was saved as a public variable in the entity class. PHP
     // allows Drupal to do this even if the method is not defined ahead of
     // time.
     $status = $mapping->save();
     // Grab the URL of the new entity. We'll use it in the message.
     $url = $mapping->urlInfo();
     // Create an edit link.
     $edit_link = Link::fromTextAndUrl($this->t('Edit'), $url);
     if ($status == SAVED_UPDATED) {
         // If we edited an existing entity...
         drupal_set_message($this->t('Mapping %label has been updated.', array('%label' => $mapping->label())));
         $this->logger('contact')->notice('Mapping %label has been updated.', ['%label' => $mapping->label(), 'link' => $edit_link]);
     } else {
         // If we created a new entity...
         drupal_set_message($this->t('Mapping %label has been added.', array('%label' => $mapping->label())));
         $this->logger('contact')->notice('Mapping %label has been added.', ['%label' => $mapping->label(), 'link' => $edit_link]);
     }
     // Redirect the user back to the listing route after the save operation.
     $form_state->setRedirect('entity.flag_mapping.list');
     return $status;
 }
示例#20
0
文件: Cycle.php 项目: badelas/afroweb
 /**
  * {@inheritdoc}
  */
 public function buildConfigurationForm(array $form, FormStateInterface $form_state)
 {
     $cycle = \Drupal::service('library.discovery')->getLibraryByName('views_slideshow_cycle', 'jquery_cycle');
     if (!isset($cycle['js'][0]['data']) || !file_exists($cycle['js'][0]['data'])) {
         $form['views_slideshow_cycle']['no_cycle_js'] = array('#markup' => '<div style="color: red">' . t('You need to install the jQuery cycle plugin. Create a directory in libraries (which should be in your Drupal root folder, if not create the same) called jquery.cycle, and then copy jquery.cycle.all.js into it. You can find the plugin at @url.', array('@url' => Link::fromTextAndUrl('http://malsup.com/jquery/cycle', Url::FromUri('http://malsup.com/jquery/cycle'), array('attributes' => array('target' => '_blank'))))) . '</div>');
     }
     // Transition.
     $form['views_slideshow_cycle']['transition'] = array('#markup' => '<h2>' . t('Transition') . '</h2>');
     $effects = array('none' => 'none', 'blindX' => 'blindX', 'blindY' => 'blindY', 'blindZ' => 'blindZ', 'cover' => 'cover', 'curtainX' => 'curtainX', 'curtainY' => 'curtainY', 'fade' => 'fade', 'fadeZoom' => 'fadeZoom', 'growX' => 'growX', 'growY' => 'growY', 'scrollUp' => 'scrollUp', 'scrollDown' => 'scrollDown', 'scrollLeft' => 'scrollLeft', 'scrollRight' => 'scrollRight', 'scrollHorz' => 'scrollHorz', 'scrollVert' => 'scrollVert', 'shuffle' => 'shuffle', 'slideX' => 'slideX', 'slideY' => 'slideY', 'toss' => 'toss', 'turnUp' => 'turnUp', 'turnDown' => 'turnDown', 'turnLeft' => 'turnLeft', 'turnRight' => 'turnRight', 'uncover' => 'uncover', 'wipe' => 'wipe', 'zoom' => 'zoom');
     $form['views_slideshow_cycle']['effect'] = array('#type' => 'select', '#title' => t('Effect'), '#options' => $effects, '#default_value' => $this->getConfiguration()['effect'], '#description' => t('The transition effect that will be used to change between images. Not all options below may be relevant depending on the effect. <a href="http://jquery.malsup.com/cycle/browser.html" target="_black">Follow this link to see examples of each effect.</a>'));
     // Transition advanced options.
     $form['views_slideshow_cycle']['transition_advanced'] = array('#type' => 'checkbox', '#title' => t('View Transition Advanced Options'), '#default_value' => $this->getConfiguration()['transition_advanced']);
     // Need to wrap this so it indents correctly.
     $form['views_slideshow_cycle']['transition_advanced_wrapper'] = array('#markup' => '<div class="vs-dependent">');
     $form['views_slideshow_cycle']['timeout'] = array('#type' => 'textfield', '#title' => t('Timer delay'), '#default_value' => $this->getConfiguration()['timeout'], '#description' => t('Amount of time in milliseconds between transitions. Set the value to 0 to not rotate the slideshow automatically.'), '#states' => array('visible' => array(':input[name="style_options[views_slideshow_cycle][transition_advanced]"]' => array('checked' => TRUE))));
     $form['views_slideshow_cycle']['speed'] = array('#type' => 'textfield', '#title' => t('Speed'), '#default_value' => $this->getConfiguration()['speed'], '#description' => t('Time in milliseconds that each transition lasts. Numeric only!'), '#states' => array('visible' => array(':input[name="style_options[views_slideshow_cycle][transition_advanced]"]' => array('checked' => TRUE))));
     $form['views_slideshow_cycle']['delay'] = array('#type' => 'textfield', '#title' => t('Initial slide delay offset'), '#default_value' => $this->getConfiguration()['delay'], '#description' => t('Amount of time in milliseconds for the first slide to transition. This number will be added to Timer delay to create the initial delay.  For example if Timer delay is 4000 and Initial delay is 2000 then the first slide will change at 6000ms (6 seconds).  If Initial delay is -2000 then the first slide will change at 2000ms (2 seconds).'), '#states' => array('visible' => array(':input[name="style_options[views_slideshow_cycle][transition_advanced]"]' => array('checked' => TRUE))));
     $form['views_slideshow_cycle']['sync'] = array('#type' => 'checkbox', '#title' => t('Sync'), '#default_value' => $this->getConfiguration()['sync'], '#description' => t('The sync option controls whether the slide transitions occur simultaneously. The default is selected which means that the current slide transitions out as the next slide transitions in. By unselecting this option you can get some interesting twists on your transitions.'), '#states' => array('visible' => array(':input[name="style_options[views_slideshow_cycle][transition_advanced]"]' => array('checked' => TRUE))));
     $form['views_slideshow_cycle']['random'] = array('#type' => 'checkbox', '#title' => t('Random'), '#description' => t('This option controls the order items are displayed. The default setting, unselected, uses the views ordering. Selected will cause the images to display in a random order.'), '#default_value' => $this->getConfiguration()['random'], '#states' => array('visible' => array(':input[name="style_options[views_slideshow_cycle][transition_advanced]"]' => array('checked' => TRUE))));
     $form['views_slideshow_cycle']['transition_advanced_wrapper_close'] = array('#markup' => '</div>');
     // Action.
     $form['views_slideshow_cycle']['action'] = array('#markup' => '<h2>' . t('Action') . '</h2>');
     $form['views_slideshow_cycle']['pause'] = array('#type' => 'checkbox', '#title' => t('Pause on hover'), '#default_value' => $this->getConfiguration()['pause'], '#description' => t('Pause when hovering on the slideshow image.'));
     $form['views_slideshow_cycle']['pause_on_click'] = array('#type' => 'checkbox', '#title' => t('Pause On Click'), '#default_value' => $this->getConfiguration()['pause_on_click'], '#description' => t('Pause when the slide is clicked.'));
     // Action Advanced Options.
     $form['views_slideshow_cycle']['action_advanced'] = array('#type' => 'checkbox', '#title' => t('View Action Advanced Options'), '#default_value' => $this->getConfiguration()['action_advanced']);
     // Need to wrap this so it indents correctly.
     $form['views_slideshow_cycle']['action_advanced_wrapper'] = array('#markup' => '<div class="vs-dependent">');
     $form['views_slideshow_cycle']['start_paused'] = array('#type' => 'checkbox', '#title' => t('Start Slideshow Paused'), '#default_value' => $this->getConfiguration()['start_paused'], '#description' => t('Start the slideshow in the paused state.'), '#states' => array('visible' => array(':input[name="style_options[views_slideshow_cycle][action_advanced]"]' => array('checked' => TRUE))));
     $form['views_slideshow_cycle']['remember_slide'] = array('#type' => 'checkbox', '#title' => t('Start On Last Slide Viewed'), '#default_value' => $this->getConfiguration()['remember_slide'], '#description' => t('When the user leaves a page with a slideshow and comes back start them on the last slide viewed.'), '#states' => array('visible' => array(':input[name="style_options[views_slideshow_cycle][action_advanced]"]' => array('checked' => TRUE))));
     $form['views_slideshow_cycle']['remember_slide_days'] = array('#type' => 'textfield', '#title' => t('Length of Time to Remember Last Slide'), '#default_value' => $this->getConfiguration()['remember_slide_days'], '#description' => t('The number of days to have the site remember the last slide. Default is 1'), '#prefix' => '<div class="vs-dependent">', '#suffix' => '</div>', '#size' => 4, '#states' => array('visible' => array(':input[name="style_options[views_slideshow_cycle][action_advanced]"]' => array('checked' => TRUE), ':input[name="style_options[views_slideshow_cycle][remember_slide]"]' => array('checked' => TRUE))));
     // @todo Check if there is a better way to detect optional libraries.
     $pause = \Drupal::service('library.discovery')->getLibraryByName('views_slideshow_cycle', 'jquery_pause');
     if (isset($pause['js'][0]['data']) && file_exists($pause['js'][0]['data'])) {
         $form['views_slideshow_cycle']['pause_in_middle'] = array('#type' => 'checkbox', '#title' => t('Pause The Slideshow In The Middle of the Transition'), '#default_value' => $this->getConfiguration()['pause_in_middle'], '#description' => t('When pausing the slideshow allow it to pause in the middle of tranistioning and not finish the transition until unpaused.'), '#states' => array('visible' => array(':input[name="style_options[views_slideshow_cycle][transition_advanced]"]' => array('checked' => TRUE))));
     }
     $form['views_slideshow_cycle']['pause_when_hidden'] = array('#type' => 'checkbox', '#title' => t('Pause When the Slideshow is Not Visible'), '#default_value' => $this->getConfiguration()['pause_when_hidden'], '#description' => t('When the slideshow is scrolled out of view or when a window is resized that hides the slideshow, this will pause the slideshow.'), '#states' => array('visible' => array(':input[name="style_options[views_slideshow_cycle][action_advanced]"]' => array('checked' => TRUE))));
     $form['views_slideshow_cycle']['pause_when_hidden_type'] = array('#type' => 'select', '#title' => t('How to Calculate Amount of Slide that Needs to be Shown'), '#options' => array('full' => t('Entire slide'), 'vertical' => t('Set amount of vertical'), 'horizontal' => t('Set amount of horizontal'), 'area' => t('Set total area of the slide')), '#default_value' => $this->getConfiguration()['pause_when_hidden_type'], '#description' => t('Choose how to calculate how much of the slide has to be shown. Entire Slide: All the slide has to be shown. Vertical: Set amount of height that has to be shown. Horizontal: Set amount of width that has to be shown. Area: Set total area that has to be shown.'), '#prefix' => '<div class="vs-dependent">', '#suffix' => '</div>', '#states' => array('visible' => array(':input[name="style_options[views_slideshow_cycle][action_advanced]"]' => array('checked' => TRUE), ':input[name="style_options[views_slideshow_cycle][pause_when_hidden]"]' => array('checked' => TRUE))));
     $form['views_slideshow_cycle']['amount_allowed_visible'] = array('#type' => 'textfield', '#title' => t('Amount of Slide Needed to be Shown'), '#default_value' => $this->getConfiguration()['amount_allowed_visible'], '#description' => t("The amount of the slide that needs to be shown to have it rotate. You can set the value in percentage (ex: 50%) or in pixels (ex: 250). The slidehsow will not rotate until it's height/width/total area, depending on the calculation method you have chosen above, is less than the value you have entered in this field."), '#size' => 4);
     $form['views_slideshow_cycle']['#attached']['library'][] = 'views_slideshow_cycle/formoptions';
     $form['views_slideshow_cycle']['nowrap'] = array('#type' => 'checkbox', '#title' => t('End slideshow after last slide'), '#default_value' => $this->getConfiguration()['nowrap'], '#description' => t('If selected the slideshow will end when it gets to the last slide.'), '#states' => array('visible' => array(':input[name="style_options[views_slideshow_cycle][action_advanced]"]' => array('checked' => TRUE))));
     $form['views_slideshow_cycle']['fixed_height'] = array('#type' => 'checkbox', '#title' => t('Make the slide window height fit the largest slide'), '#default_value' => $this->getConfiguration()['fixed_height'], '#description' => t('If unselected then if the slides are different sizes the height of the slide area will change as the slides change.'), '#states' => array('visible' => array(':input[name="style_options[views_slideshow_cycle][action_advanced]"]' => array('checked' => TRUE))));
     $form['views_slideshow_cycle']['items_per_slide'] = array('#type' => 'textfield', '#title' => t('Items per slide'), '#default_value' => $this->getConfiguration()['items_per_slide'], '#description' => t('The number of items per slide'), '#size' => 4, '#states' => array('visible' => array(':input[name="style_options[views_slideshow_cycle][action_advanced]"]' => array('checked' => TRUE))));
     $form['views_slideshow_cycle']['wait_for_image_load'] = array('#type' => 'checkbox', '#title' => t('Wait for all the slide images to load'), '#default_value' => $this->getConfiguration()['wait_for_image_load'], '#description' => t('If selected the slideshow will not start unless all the slide images are loaded.  This will fix some issues on IE7/IE8/Chrome/Opera.'), '#states' => array('visible' => array(':input[name="style_options[views_slideshow_cycle][action_advanced]"]' => array('checked' => TRUE))));
     $form['views_slideshow_cycle']['wait_for_image_load_timeout'] = array('#type' => 'textfield', '#title' => t('Timeout'), '#default_value' => $this->getConfiguration()['wait_for_image_load_timeout'], '#description' => t('How long should it wait until it starts the slideshow anyway. Time is in milliseconds.'), '#prefix' => '<div class="vs-dependent">', '#suffix' => '</div>', '#states' => array('visible' => array(':input[name="style_options[views_slideshow_cycle][action_advanced]"]' => array('checked' => TRUE), ':input[name="style_options[views_slideshow_cycle][wait_for_image_load]"]' => array('checked' => TRUE))));
     // Need to wrap this so it indents correctly.
     $form['views_slideshow_cycle']['action_advanced_wrapper_close'] = array('#markup' => '</div>');
     // Internet Explorer Tweaks.
     $form['views_slideshow_cycle']['ie_tweaks'] = array('#markup' => '<h2>' . t('Internet Explorer Tweaks') . '</h2>');
     $form['views_slideshow_cycle']['cleartype'] = array('#type' => 'checkbox', '#title' => t('ClearType'), '#default_value' => $this->getConfiguration()['cleartype'], '#description' => t('Select if clearType corrections should be applied (for IE).  Some background issues could be fixed by unselecting this option.'));
     $form['views_slideshow_cycle']['cleartypenobg'] = array('#type' => 'checkbox', '#title' => t('ClearType Background'), '#default_value' => $this->getConfiguration()['cleartypenobg'], '#description' => t('Select to disable extra cleartype fixing.  Unselect to force background color setting on slides)'));
     // Advanced Options.
     $form['views_slideshow_cycle']['advanced_options_header'] = array('#markup' => '<h2>' . t('jQuery Cycle Custom Options') . '</h2>');
     // @todo Check if there is a better way to detect optional libraries.
     $json2 = \Drupal::service('library.discovery')->getLibraryByName('views_slideshow_cycle', 'json2');
     if (!isset($json2['js'][0]['data']) || !file_exists($json2['js'][0]['data'])) {
         // @todo Check if there is a better way to create this target _blank link.
         $form['views_slideshow_cycle']['no_json_js'] = array('#markup' => '<div>' . t('To use the advanced options you need to download json2.js. You can do this by clicking the download button at <a href="https://github.com/douglascrockford/JSON-js" target="_black">https://github.com/douglascrockford/JSON-js</a> and extract json2.js to libraries/json2') . '</div>');
     } else {
         // @todo Check if there is a better way to create this target _blank link.
         $form['views_slideshow_cycle']['advanced_options_info'] = array('#markup' => '<p>' . t('You can find a list of all the available options at <a href="http://malsup.com/jquery/cycle/options.html" target="_blank">http://malsup.com/jquery/cycle/options.html</a>. If one of the options you add uses a function, example fxFn, then you need to only enter what goes inside the function call. The variables that are in the documentation on the jquery cycle site will be available to you.') . '</p>');
         // All the jquery cycle options according to
         // http://malsup.com/jquery/cycle/options.html
         $cycle_options = array(0 => 'Select One', 'activePagerClass' => 'activePagerClass', 'after' => 'after', 'allowPagerClickBubble' => 'allowPagerClickBubble', 'animIn' => 'animIn', 'animOut' => 'animOut', 'autostop' => 'autostop', 'autostopCount' => 'autostopCount', 'backwards' => 'backwards', 'before' => 'before', 'bounce' => 'bounce', 'cleartype' => 'cleartype', 'cleartypeNoBg' => 'cleartypeNoBg', 'containerResize' => 'containerResize', 'continuous' => 'continuous', 'cssAfter' => 'cssAfter', 'cssBefore' => 'cssBefore', 'delay' => 'delay', 'easeIn' => 'easeIn', 'easeOut' => 'easeOut', 'easing' => 'easing', 'end' => 'end', 'fastOnEvent' => 'fastOnEvent', 'fit' => 'fit', 'fx' => 'fx', 'fxFn' => 'fxFn', 'height' => 'height', 'manualTrump' => 'manualTrump', 'metaAttr' => 'metaAttr', 'next' => 'next', 'nowrap' => 'nowrap', 'onPagerEvent' => 'onPagerEvent', 'onPrevNextEvent' => 'onPrevNextEvent', 'pager' => 'pager', 'pagerAnchorBuilder' => 'pagerAnchorBuilder', 'pagerEvent' => 'pagerEvent', 'pause' => 'pause', 'paused' => 'paused', 'pauseOnPagerHover' => 'pauseOnPagerHover', 'prev' => 'prev', 'prevNextEvent' => 'prevNextEvent', 'random' => 'random', 'randomizeEffects' => 'randomizeEffects', 'requeueOnImageNotLoaded' => 'requeueOnImageNotLoaded', 'requeueTimeout' => 'requeueTimeout', 'resumed' => 'resumed', 'rev' => 'rev', 'shuffle' => 'shuffle', 'slideExpr' => 'slideExpr', 'slideResize' => 'slideResize', 'speed' => 'speed', 'speedIn' => 'speedIn', 'speedOut' => 'speedOut', 'startingSlide' => 'startingSlide', 'sync' => 'sync', 'timeout' => 'timeout', 'timeoutFn' => 'timeoutFn', 'updateActivePagerLink' => 'updateActivePagerLink', 'width' => 'width');
         $form['views_slideshow_cycle']['advanced_options_choices'] = array('#type' => 'select', '#title' => t('Advanced Options'), '#options' => $cycle_options);
         $form['views_slideshow_cycle']['advanced_options_entry'] = array('#type' => 'textarea', '#title' => t('Advanced Option Value'), '#description' => t('It is important that you click the Update link when you make any changes to the options or those changes will not be saved when you save the form.'));
         $form['views_slideshow_cycle']['advanced_options'] = array('#type' => 'textarea', '#default_value' => $this->getConfiguration()['advanced_options']);
         // @todo: Review how to create this table.
         $form['views_slideshow_cycle']['advanced_options_table'] = array('#markup' => '<table style="width: 400px; margin-left: 10px;" id="edit-style-options-views-slideshow-cycle-advanced-options-table"></table>');
     }
     return $form;
 }
示例#21
0
 /**
  * Makes a rendable array containing the page with quiz status.
  *
  * @param \Drupal\quiz\QuizInterface $quiz
  * @return array
  */
 public function userDisplayQuiz(QuizInterface $quiz)
 {
     $statuses = $quiz->getStatuses($this->currentUser());
     $build = array();
     $renderer = \Drupal::service('renderer');
     $config = \Drupal::config('system.site');
     $link = '';
     $questions = $quiz->getQuestionCount();
     $percent = $quiz->get('percent')->value;
     $timeLimit = $quiz->get('time')->value;
     if ($timeLimit == 0 || $timeLimit == NULL) {
         $timeLimit = 0;
     }
     $description = $quiz->get('description')->value;
     $attemptLimit = $quiz->get('attempts')->value;
     $attemptTimes = count($statuses);
     $attempts = array();
     // The quiz has been attempted at least once
     if (!empty($statuses)) {
         $status = array_pop($statuses);
         $statuses[] = $status;
         // If the quiz was attempted and finished
         if ($status->isFinished() && ($attemptLimit == 0 || $attemptLimit > $attemptTimes)) {
             $url = Url::fromRoute('entity.quiz.take_quiz', ['quiz' => $quiz->id()]);
             $href = Link::fromTextAndUrl('Retake Quiz', $url)->toRenderable();
             $link = $href;
         } elseif ($attemptLimit == 0 || $attemptLimit > $attemptTimes) {
             $url = Url::fromRoute('entity.quiz.take_quiz', ['quiz' => $quiz->id()]);
             $href = Link::fromTextAndUrl('Continue Quiz', $url)->toRenderable();
             $link = $href;
         }
         /* @var $status \Drupal\quiz\Entity\UserQuizStatus */
         $c = 0;
         $attempts['#prefix'] = "<div id='tabs'>";
         $attempts['#suffix'] = "</div>";
         $attempts['tabs']['#prefix'] = "<ul class='tabs'>";
         $attempts['tabs']['#suffix'] = "</ul>";
         $attempts['attempts']['#prefix'] = "<div class='attempts'>";
         $attempts['attempts']['#suffix'] = "</div>";
         foreach ($statuses as $status) {
             // Only generate reports for finished quizzes
             if ($status->isFinished()) {
                 $score = $status->getScore();
                 $maxScore = $status->getMaxScore();
                 $percent = $status->getPercent();
                 $timeTaken = $status->getFinished() - $status->getStarted();
                 $attempted = $finished = count($statuses);
                 $attempt['status']['time']['#markup'] = $this->t('Time taken: @time', ['@time' => gmdate("H:i:s", $timeTaken)]);
                 $attempt['status']['time']['#suffix'] = '<br>';
                 $attempt['status']['score']['#markup'] = $this->t('You scored @score out of @max points', ['@score' => $score, '@max' => $maxScore]);
                 $attempt['status']['score']['#suffix'] = '<br>';
                 if ($score / $maxScore >= $percent / 100) {
                     $attempt['status']['pass']['#markup'] = $this->t('You passed this quiz with @percents%!', ['@percents' => round($score / $maxScore, 2) * 100]);
                 } else {
                     $attempt['status']['pass']['#markup'] = $this->t('You failed this quiz with @percents%.', ['@percents' => round($score / $maxScore, 2) * 100]);
                 }
                 $attempt['status']['pass']['#prefix'] = '<br>';
                 $attempt['status']['pass']['#suffix'] = '<br>';
                 $attempt['status']['#prefix'] = '<div>';
                 $attempt['status']['#suffix'] = '</div>';
                 $attempt['table'] = $this->getResultsTable($status);
                 $attempts['tabs']['#weight'] = -1;
                 $attempts['tabs'][++$c]['#markup'] = $this->t("Attempt @id", ['@id' => $c]);
                 $attempts['tabs'][$c]['#prefix'] = "<li><a href='#tabs-" . $c . "'>";
                 $attempts['tabs'][$c]['#suffix'] = '</a></li>';
                 $attempts['attempts'][$c] = $attempt;
                 $attempts['attempts'][$c]['#prefix'] = $this->t("<div id='tabs-@id'>", ['@id' => $c]);
                 $attempts['attempts'][$c]['#suffix'] = "</div>";
             }
         }
     } else {
         $url = Url::fromRoute('entity.quiz.take_quiz', ['quiz' => $quiz->id()]);
         $href = Link::fromTextAndUrl('Take Quiz', $url)->toRenderable();
         $link = $href;
     }
     $build['details']['description']['#markup'] = $this->t('@description', ['@description' => $description]);
     $build['details']['description']['#prefix'] = '<p>';
     $build['details']['description']['#suffix'] = '</p>';
     $build['details']['status']['#prefix'] = '<p>';
     $build['details']['status']['#suffix'] = '</p>';
     $build['details']['status']['questions']['#markup'] = $this->t('Number of questions: @questions', ['@questions' => $questions]);
     $build['details']['status']['questions']['#suffix'] = '<br>';
     $build['details']['status']['percent']['#markup'] = $this->t('Pass rate: @percent%', ['@percent' => $percent]);
     $build['details']['status']['percent']['#suffix'] = '<br>';
     $build['details']['status']['time']['#markup'] = $this->t('Time limit: @time', ['@time' => $timeLimit > 0 ? gmdate("H:i:s", $timeLimit) : 'No']);
     $build['details']['status']['time']['#suffix'] = '<br>';
     $build['details']['status']['allowed']['#markup'] = $this->t('Attempts allowed: @times', ['@times' => $attemptLimit > 0 ? $attemptLimit : 'Unlimited']);
     $build['details']['status']['allowed']['#suffix'] = '<br>';
     $build['details']['status']['attempts']['#markup'] = $this->t('Attempted @times times.', ['@times' => $attemptTimes]);
     $build['details']['link'] = $link;
     $build['details']['link']['#prefix'] = '<p>';
     $build['details']['link']['#suffix'] = '</p>';
     $build['results'] = $attempts;
     $build['results']['#attached']['library'][] = 'quiz/quiz.tabs';
     $build['#cache'] = ['contexts' => ['user']];
     $renderer->addCacheableDependency($build, $config);
     $renderer->addCacheableDependency($build, $this->currentUser());
     return $build;
 }
 /**
  * {@inheritdoc}
  */
 protected function actions(array $form, FormStateInterface $form_state)
 {
     $actions = parent::actions($form, $form_state);
     // Change the submit button text.
     $actions['submit']['#value'] = $this->t('Save');
     $actions['submit']['#suffix'] = Link::fromTextAndUrl($this->t('Cancel'), $this->getCancelUrl())->toString();
     return $actions;
 }
示例#23
0
 /**
  * {@inheritdoc}
  */
 public function buildOptionsForm(&$form, FormStateInterface $form_state)
 {
     parent::buildOptionsForm($form, $form_state);
     // Wrap all the form elements to help style the form.
     $form['views_slideshow_wrapper'] = array('#markup' => '<div id="views-slideshow-form-wrapper">');
     // Skins.
     $form['slideshow_skin_header'] = array('#markup' => '<h2>' . t('Style') . '</h2>');
     /** @var \Drupal\Component\Plugin\PluginManagerInterface */
     $skinManager = \Drupal::service('plugin.manager.views_slideshow.slideshow_skin');
     // Get all skins to create the option list.
     $skins = [];
     foreach ($skinManager->getDefinitions() as $id => $definition) {
         $skins[$id] = $definition['label'];
     }
     asort($skins);
     // Create the drop down box so users can choose an available skin.
     $form['slideshow_skin'] = array('#type' => 'select', '#title' => t('Skin'), '#options' => $skins, '#default_value' => $this->options['slideshow_skin'], '#description' => t('Select the skin to use for this display.  Skins allow for easily swappable layouts of things like next/prev links and thumbnails.  Note that not all skins support all widgets, so a combination of skins and widgets may lead to unpredictable results in layout.'));
     // Slides.
     $form['slides_header'] = array('#markup' => '<h2>' . t('Slides') . '</h2>');
     // Get all slideshow types.
     $typeManager = \Drupal::service('plugin.manager.views_slideshow.slideshow_type');
     $types = $typeManager->getDefinitions();
     if ($types) {
         // Build our slideshow options for the form.
         $slideshow_options = array();
         foreach ($types as $id => $definition) {
             $slideshow_options[$id] = $definition['label'];
         }
         $form['slideshow_type'] = array('#type' => 'select', '#title' => t('Slideshow Type'), '#options' => $slideshow_options, '#default_value' => $this->options['slideshow_type']);
         // @todo: check if default values are properly passed to the buildConfigurationForm().
         foreach ($types as $id => $definition) {
             $configuration = [];
             if (!empty($this->options[$id])) {
                 $configuration = $this->options[$id];
             }
             $instance = $typeManager->createInstance($id, $configuration);
             $form[$id] = array('#type' => 'fieldset', '#title' => t('@module options', array('@module' => $definition['label'])), '#collapsible' => TRUE, '#attributes' => array('class' => array($id)), '#states' => array('visible' => array(':input[name="style_options[slideshow_type]"]' => array('value' => $id))));
             $form = $instance->buildConfigurationForm($form, $form_state);
         }
     } else {
         $form['enable_module'] = array('#markup' => t('There is no Views Slideshow plugin enabled. Go to the @modules and enable a Views Slideshow plugin module. For example Views Slideshow Singleframe.', array('@modules' => Link::fromTextAndUrl(t('Modules Page'), Url::fromRoute('system.modules_list')))));
     }
     // Widgets.
     // @todo: Improve the UX by using Ajax.
     $form['widgets_header'] = array('#markup' => '<h2>' . t('Widgets') . '</h2>');
     // Define the available locations.
     $location = array('top' => t('Top'), 'bottom' => t('Bottom'));
     // Loop through all locations so we can add header for each location.
     foreach ($location as $location_id => $location_name) {
         $form['widgets'][$location_id]['header'] = array('#markup' => '<h3>' . t('@location Widgets', array('@location' => $location_name)) . '</h3>');
     }
     /** @var \Drupal\Component\Plugin\PluginManagerInterface */
     $widgetTypeManager = \Drupal::service('plugin.manager.views_slideshow.widget_type');
     // Get all widgets types that are registered.
     $widgets = $widgetTypeManager->getDefinitions();
     if (!empty($widgets)) {
         // Build our weight values by number of widgets
         $weights = [];
         for ($i = 1; $i <= count($widgets); $i++) {
             $weights[$i] = $i;
         }
         // Loop through our widgets and locations to build our form values for
         // each widget.
         foreach ($widgets as $widget_id => $widget_info) {
             // Determine if this widget type is compatible with any slideshow type.
             $compatible_slideshows = [];
             foreach ($types as $slideshow_id => $slideshow_info) {
                 if ($widgetTypeManager->createInstance($widget_id, [])->checkCompatiblity($slideshow_info)) {
                     $compatible_slideshows[] = $slideshow_id;
                 }
             }
             // Display the widget config form only if the widget type is compatible
             // with at least one slideshow type.
             if (!empty($compatible_slideshows)) {
                 foreach ($location as $location_id => $location_name) {
                     // Use Widget Checkbox.
                     $form['widgets'][$location_id][$widget_id]['enable'] = array('#type' => 'checkbox', '#title' => $widget_info['label'], '#default_value' => $this->options['widgets'][$location_id][$widget_id]['enable'], '#description' => t('Should @name be rendered at the @location of the slides.', array('@name' => $widget_info['label'], '@location' => $location_name)), '#dependency' => array('edit-style-options-slideshow-type' => $compatible_slideshows));
                     // Need to wrap this so it indents correctly.
                     $form['widgets'][$location_id][$widget_id]['wrapper'] = ['#markup' => '<div class="vs-dependent">'];
                     // Widget weight.
                     // We check to see if the default value is greater than the number
                     // of widgets just in case a widget has been removed and the form
                     // hasn't been saved again.
                     $weight = isset($this->options['widgets'][$location_id][$widget_id]['weight']) ? $this->options['widgets'][$location_id][$widget_id]['weight'] : 0;
                     if ($weight > count($widgets)) {
                         $weight = count($widgets);
                     }
                     $form['widgets'][$location_id][$widget_id]['weight'] = ['#type' => 'select', '#title' => t('Weight of the @name', ['@name' => $widget_info['label']]), '#default_value' => $weight, '#options' => $weights, '#description' => t('Determines in what order the @name appears. A lower weight will cause the @name to be above higher weight items.', ['@name' => $widget_info['label']]), '#prefix' => '<div class="vs-dependent">', '#suffix' => '</div>', '#states' => ['visible' => [':input[name="style_options[widgets][' . $location_id . '][' . $widget_id . '][enable]"]' => ['checked' => TRUE]]]];
                     // Build the appropriate array for the states API.
                     $widget_dependency = 'style_options[widgets][' . $location_id . '][' . $widget_id . ']';
                     // Get the current configuration of this widget type.
                     $configuration = [];
                     if (!empty($this->options['widgets'][$location_id][$widget_id])) {
                         $configuration = $this->options['widgets'][$location_id][$widget_id];
                     }
                     $configuration['dependency'] = $widget_dependency;
                     $instance = $widgetTypeManager->createInstance($widget_id, $configuration);
                     // Get the configuration form of this widget type.
                     $form['widgets'][$location_id][$widget_id] = $instance->buildConfigurationForm($form['widgets'][$location_id][$widget_id], $form_state);
                     // Close the vs-dependent wrapper.
                     $form['widgets'][$location_id][$widget_id]['wrapper_close'] = ['#markup' => '</div>'];
                 }
             }
         }
     }
     // Browse locations and remove the header if no widget is available.
     foreach ($location as $location_id => $location_name) {
         // If no widget is available, the only key is "header".
         if (count(array_keys($form['widgets'][$location_id])) == 1) {
             unset($form['widgets'][$location_id]);
         }
     }
     // Remove the widget section header if there is no widget available.
     if (empty($form['widgets'])) {
         unset($form['widgets']);
         unset($form['widgets_header']);
     }
     $form['views_slideshow_wrapper_close'] = ['#markup' => '</div>'];
     // Add a library to style the form.
     $form['#attached']['library'] = ['views_slideshow/form'];
 }
  /**
   * Helper function.
   *
   * Display a link to view display edit page if user has permission.
   *
   * @param string $view_id
   *   A view ID.
   * @param string $display_id
   *   A view display ID.
   * @param string $display_title
   *   The title of the view display.
   *
   * @return string
   *   A link to the view display if user has access.
   *   The display title otherwise.
   */
  public function viewDisplayLink($view_id, $display_id, $display_title) {
    if ($this->moduleHandler->moduleExists('views_ui')) {
      // Prepare link.
      if ($display_title == 'Master') {
        $url = Url::fromRoute('entity.view.edit_form', array('view' => $view_id));
      }
      else {
        $url = Url::fromRoute('entity.view.edit_display_form', array('view' => $view_id, 'display_id' => $display_id));
      }

      // Use the routing system to check access.
      if ($url->renderAccess($url->toRenderArray())) {
        return Link::fromTextAndUrl($display_title, $url);
      }
      else {
        return $display_title;
      }
    }
    else {
      return $display_title;
    }
  }
示例#25
0
  /**
   * Helper function.
   *
   * Display a link to image style edit page if user has permission.
   *
   * If no argument is given, display a link to the image styles list.
   *
   * @param string $image_style_label
   *   The label of the image style.
   * @param string $image_style_name
   *   The name of the image style.
   *
   * @return string
   *   A link to the image style if user has access.
   *   The image style's label otherwise.
   */
  public function displayImageStyleLink($image_style_label = '', $image_style_name = '') {
    // Prepare link.
    if ($image_style_label != '' && $image_style_name != '') {
      $url = Url::fromRoute('entity.image_style.edit_form', array('image_style' => $image_style_name));
      $link_text = $image_style_label;
    }
    else {
      $url = Url::fromRoute('entity.image_style.collection');
      $link_text = $this->t('Image styles (not sortable)');
    }

    // Use the routing system to check access.
    if ($url->renderAccess($url->toRenderArray())) {
      $link = Link::fromTextAndUrl($link_text, $url)->toRenderable();
      return render($link);
    }
    else {
      return $image_style_label;
    }
  }
 /**
  * {@inheritdoc}
  *
  * @param \Drupal\filter\Entity\FilterFormat $filter_format
  *   The filter format for which this dialog corresponds.
  */
 public function buildForm(array $form, FormStateInterface $form_state, FilterFormat $filter_format = NULL)
 {
     // This form is special, in that the default values do not come from the
     // server side, but from the client side, from a text editor. We must cache
     // this data in form state, because when the form is rebuilt, we will be
     // receiving values from the form, instead of the values from the text
     // editor. If we don't cache it, this data will be lost.
     $user_input = $form_state->getUserInput();
     if (isset($user_input['editor_object'])) {
         // By convention, the data that the text editor sends to any dialog is in
         // the 'editor_object' key. And the image dialog for text editors expects
         // that data to be the attributes for an <img> element.
         $image_element = $user_input['editor_object'];
         $form_state->set('image_element', $image_element);
         $form_state->setCached(TRUE);
     } elseif ($form_state->getTemporaryValue('wizard')) {
         $image_element = $form_state->getTemporaryValue('wizard')['image_element'];
     } else {
         // Retrieve the image element's attributes from form state.
         $image_element = $form_state->get('image_element') ?: [];
     }
     // Add libraries and wrap the form in ajax wrappers.
     $form['#tree'] = TRUE;
     $form['#attached']['library'][] = 'editor/drupal.editor.dialog';
     $form['#prefix'] = '<div id="' . self::AJAX_WRAPPER_ID . '">';
     $form['#suffix'] = '</div>';
     /** @var \Drupal\editor\Entity\Editor $editor */
     $editor = $this->entityTypeManager->getStorage('editor')->load($filter_format->id());
     // Construct strings to use in the upload validators.
     $embridge_image_settings = $editor->getSettings()['plugins']['embridgeimage']['embridge_image_upload'];
     $max_filesize = min(Bytes::toInt($embridge_image_settings['max_size']), file_upload_max_size());
     /** @var \Drupal\embridge\EmbridgeAssetEntityInterface $existing_asset */
     $existing_asset = isset($image_element['data-entity-uuid']) ? $this->entityRepository->loadEntityByUuid('embridge_asset_entity', $image_element['data-entity-uuid']) : NULL;
     $asset_id = $existing_asset ? $existing_asset->id() : NULL;
     /** @var \Drupal\embridge\EmbridgeCatalogInterface $catalog */
     $catalog = $this->entityTypeManager->getStorage('embridge_catalog')->load($embridge_image_settings['catalog_id']);
     // Create a preview image.
     $preview = FALSE;
     if (!empty($user_input['_triggering_element_name'])) {
         $triggering_element = $user_input['_triggering_element_name'];
     }
     // If we are editing an existing asset, use that thumbnail.
     if (empty($form_state->getValues()) && $existing_asset) {
         $preview = $this->assetHelper->getAssetConversionUrl($existing_asset, $catalog->getApplicationId(), 'thumb');
     } elseif (isset($triggering_element) && $triggering_element != 'asset_remove_button' && ($uploaded_id = $form_state->getValue(['asset', 0]))) {
         /** @var \Drupal\embridge\EmbridgeAssetEntityInterface $uploaded_asset */
         $uploaded_asset = $this->entityTypeManager->getStorage('embridge_asset_entity')->load($uploaded_id);
         if ($uploaded_asset) {
             $preview = $this->assetHelper->getAssetConversionUrl($uploaded_asset, $catalog->getApplicationId(), 'thumb');
         }
     }
     // Use a stock image for preview.
     if (!$preview) {
         $preview = drupal_get_path('module', 'embridge_ckeditor') . '/images/preview-image.png';
     }
     // TODO: Make this configurable.
     $allowed_extensions = 'gif png jpg jpeg';
     $url_options = ['filter_format' => $filter_format->id(), 'extensions' => $allowed_extensions, 'catalog_id' => $embridge_image_settings['catalog_id']];
     $link_url = Url::fromRoute('embridge_ckeditor.image.wizard', $url_options);
     $link_url->setOptions(['attributes' => ['class' => ['use-ajax', 'button'], 'data-accepts' => 'application/vnd.drupal-modal', 'data-dialog-type' => 'modal', 'data-dialog-options' => Json::encode(['width' => 1000])]]);
     $class = get_class($this);
     $form['asset'] = ['preview' => ['#theme' => 'image', '#uri' => $preview, '#weight' => -100], '#title' => $this->t('Image'), '#type' => 'embridge_asset', '#catalog_id' => $embridge_image_settings['catalog_id'], '#library_id' => $embridge_image_settings['library_id'], '#upload_location' => 'public://' . $embridge_image_settings['directory'], '#default_value' => $asset_id ? [$asset_id] : NULL, '#upload_validators' => ['validateFileExtensions' => [$allowed_extensions], 'validateFileSize' => [$max_filesize]], '#pre_render' => [[$class, 'preRenderAssetElement']], '#allow_search' => FALSE, '#required' => TRUE, 'search_link' => Link::fromTextAndUrl('Search asset library', $link_url)->toRenderable()];
     $form['asset']['search_link']['#weight'] = 100;
     $form['attributes'] = ['#type' => 'container', '#tree' => TRUE, '#attributes' => ['class' => ['image-attributes']]];
     $form['attributes']['src'] = ['#type' => 'value'];
     $alt = isset($image_element['alt']) ? $image_element['alt'] : '';
     $form['attributes']['alt'] = ['#title' => $this->t('Alternative text'), '#description' => $this->t('The alt text describes the image for non-sighted users. <br/>The alt text can remain empty only if the image conveys no meaning (is decorative only).'), '#type' => 'textfield', '#default_value' => $alt, '#maxlength' => 2048];
     $conversion = isset($image_element['data-conversion']) ? $image_element['data-conversion'] : '';
     $conversions_array = $catalog->getConversionsArray();
     $form['attributes']['data-conversion'] = ['#title' => $this->t('Image size'), '#description' => $this->t('Choose the image size conversion to display.'), '#type' => 'select', '#default_value' => $conversion, '#options' => array_combine($conversions_array, $conversions_array)];
     // When Drupal core's filter_align is being used, the text editor may
     // offer the ability to change the alignment.
     if ($filter_format->filters('filter_align')->status) {
         $data_align = !empty($image_element['data-align']) ? $image_element['data-align'] : '';
         $form['attributes']['data-align'] = ['#title' => $this->t('Align'), '#description' => $this->t('How the image will align within the content.'), '#type' => 'select', '#options' => ['none' => $this->t('None'), 'left' => $this->t('Left'), 'center' => $this->t('Center'), 'right' => $this->t('Right')], '#default_value' => $data_align];
     }
     $form['actions'] = ['#type' => 'actions'];
     $form['actions']['save_modal'] = ['#type' => 'submit', '#value' => $this->t('Save'), '#submit' => [], '#ajax' => ['callback' => [$this, 'ajaxSave'], 'event' => 'click'], '#attributes' => ['class' => ['button--primary']]];
     return $form;
 }
示例#27
0
 /**
  * Recursive helper function for buildOverviewForm().
  *
  * @param \Drupal\Core\Menu\MenuLinkTreeElement[] $tree
  *   The tree retrieved by \Drupal\Core\Menu\MenuLinkTreeInterface::load().
  * @param int $delta
  *   The default number of menu items used in the menu weight selector is 50.
  *
  * @return array
  *   The overview tree form.
  */
 protected function buildOverviewTreeForm($tree, $delta)
 {
     $form =& $this->overviewTreeForm;
     $tree_access_cacheability = new CacheableMetadata();
     foreach ($tree as $element) {
         $tree_access_cacheability = $tree_access_cacheability->merge(CacheableMetadata::createFromObject($element->access));
         // Only render accessible links.
         if (!$element->access->isAllowed()) {
             continue;
         }
         /** @var \Drupal\Core\Menu\MenuLinkInterface $link */
         $link = $element->link;
         if ($link) {
             $id = 'menu_plugin_id:' . $link->getPluginId();
             $form[$id]['#item'] = $element;
             $form[$id]['#attributes'] = $link->isEnabled() ? array('class' => array('menu-enabled')) : array('class' => array('menu-disabled'));
             $form[$id]['title'] = Link::fromTextAndUrl($link->getTitle(), $link->getUrlObject())->toRenderable();
             if (!$link->isEnabled()) {
                 $form[$id]['title']['#suffix'] = ' (' . $this->t('disabled') . ')';
             } elseif (($url = $link->getUrlObject()) && $url->isRouted() && $url->getRouteName() == 'user.page') {
                 $form[$id]['title']['#suffix'] = ' (' . $this->t('logged in users only') . ')';
             }
             $form[$id]['enabled'] = array('#type' => 'checkbox', '#title' => $this->t('Enable @title menu link', array('@title' => $link->getTitle())), '#title_display' => 'invisible', '#default_value' => $link->isEnabled());
             $form[$id]['weight'] = array('#type' => 'weight', '#delta' => $delta, '#default_value' => $link->getWeight(), '#title' => $this->t('Weight for @title', array('@title' => $link->getTitle())), '#title_display' => 'invisible');
             $form[$id]['id'] = array('#type' => 'hidden', '#value' => $link->getPluginId());
             $form[$id]['parent'] = array('#type' => 'hidden', '#default_value' => $link->getParent());
             // Build a list of operations.
             $operations = array();
             $operations['edit'] = array('title' => $this->t('Edit'));
             // Allow for a custom edit link per plugin.
             $edit_route = $link->getEditRoute();
             if ($edit_route) {
                 $operations['edit']['url'] = $edit_route;
                 // Bring the user back to the menu overview.
                 $operations['edit']['query'] = $this->getDestinationArray();
             } else {
                 // Fall back to the standard edit link.
                 $operations['edit'] += array('url' => Url::fromRoute('menu_ui.link_edit', ['menu_link_plugin' => $link->getPluginId()]));
             }
             // Links can either be reset or deleted, not both.
             if ($link->isResettable()) {
                 $operations['reset'] = array('title' => $this->t('Reset'), 'url' => Url::fromRoute('menu_ui.link_reset', ['menu_link_plugin' => $link->getPluginId()]));
             } elseif ($delete_link = $link->getDeleteRoute()) {
                 $operations['delete']['url'] = $delete_link;
                 $operations['delete']['query'] = $this->getDestinationArray();
                 $operations['delete']['title'] = $this->t('Delete');
             }
             if ($link->isTranslatable()) {
                 $operations['translate'] = array('title' => $this->t('Translate'), 'url' => $link->getTranslateRoute());
             }
             $form[$id]['operations'] = array('#type' => 'operations', '#links' => $operations);
         }
         if ($element->subtree) {
             $this->buildOverviewTreeForm($element->subtree, $delta);
         }
     }
     $tree_access_cacheability->merge(CacheableMetadata::createFromRenderArray($form))->applyTo($form);
     return $form;
 }
 /**
  * {@inheritdoc}
  */
 public function listTopics()
 {
     /** @var \Drupal\tour\TourInterface[] $tours */
     $tours = $this->entityTypeManager->getStorage('tour')->loadMultiple();
     // Sort in the manner defined by Tour.
     uasort($tours, ['Drupal\\tour\\Entity\\Tour', 'sort']);
     // Make a link to each tour, using the first of its routes that can
     // be linked to by this user, if any.
     $topics = [];
     foreach ($tours as $tour) {
         $title = $tour->label();
         $id = $tour->id();
         $routes = $tour->getRoutes();
         $made_link = FALSE;
         foreach ($routes as $route) {
             // Some tours are for routes with parameters. For instance, there is
             // currently a tour in the Language module for the language edit page,
             // which appears on all pages with URLs like:
             // /admin/config/regional/language/edit/LANGCODE.
             // There is no way to make a link to the page that displays the tour,
             // because it is a set of pages. The easiest way to detect this is to
             // use a try/catch exception -- try to make a link, and it will error
             // out with a missing parameter exception if the route leads to a set
             // of pages instead of a single page.
             try {
                 $params = isset($route['route_params']) ? $route['route_params'] : [];
                 $url = Url::fromRoute($route['route_name'], $params);
                 // Skip this route if the current user cannot access it.
                 if (!$url->access()) {
                     continue;
                 }
                 // Generate the link HTML directly, using toString(), to catch
                 // missing parameter exceptions now instead of at render time.
                 $topics[$id] = Link::fromTextAndUrl($title, $url)->toString();
                 // If the line above didn't generate an exception, we have a good
                 // link that the user can access.
                 $made_link = TRUE;
                 break;
             } catch (\Exception $e) {
                 // Exceptions are normally due to routes that need parameters. If
                 // there is an exception, just try the next route and see if we can
                 // find one that will work for us.
             }
         }
         if (!$made_link) {
             // None of the routes worked to make a link, so at least display the
             // tour title.
             $topics[$id] = $title;
         }
     }
     return $topics;
 }
 /**
  * Displays counts of success/failures on the migration upgrade complete page.
  *
  * @param array $results
  *   An array of result data built during the batch.
  */
 protected static function displayResults($results)
 {
     $successes = $results['successes'];
     $failures = $results['failures'];
     // If we had any successes log that for the user.
     if ($successes > 0) {
         if ($results['operation'] == 'import') {
             drupal_set_message(new PluralTranslatableMarkup($successes, 'Completed 1 upgrade task successfully', 'Completed @count upgrade tasks successfully'));
         }
     }
     // If we had failures, log them and show the migration failed.
     if ($failures > 0) {
         if ($results['operation'] == 'import') {
             drupal_set_message(new PluralTranslatableMarkup($failures, '1 upgrade failed', '@count upgrades failed'));
             drupal_set_message(new TranslatableMarkup('Upgrade process not completed'), 'error');
         }
     } else {
         if ($results['operation'] == 'import') {
             // Everything went off without a hitch. We may not have had successes
             // but we didn't have failures so this is fine.
             drupal_set_message(new TranslatableMarkup('Congratulations, you upgraded Drupal!'));
         }
     }
     if (\Drupal::moduleHandler()->moduleExists('dblog')) {
         $url = Url::fromRoute('migrate_drupal_ui.log');
         drupal_set_message(Link::fromTextAndUrl(new TranslatableMarkup('Review the detailed upgrade log'), $url), $failures ? 'error' : 'status');
     }
 }
 /**
  * Displays the details of a package.
  *
  * @param $package
  *   The package object.
  *
  * @return array
  *   A render array.
  */
 public function viewPackage($package)
 {
     $shipment = Shipment::load($package->sid);
     $build = array('#type' => 'container', '#attributes' => array('class' => array('order-pane', 'pos-left')));
     $build['title'] = array('#type' => 'container', '#markup' => $this->t('Package %id:', ['%id' => $package->package_id]), '#attributes' => array('class' => array('order-pane-title')));
     $rows = array();
     $rows[] = array($this->t('Contents:'), Xss::filterAdmin($package->description));
     if ($shipment) {
         $methods = \Drupal::moduleHandler()->invokeAll('uc_fulfillment_method');
         if (isset($methods[$shipment->shipping_method])) {
             $pkg_type = $methods[$shipment->shipping_method]['ship']['pkg_types'][$package->pkg_type];
         }
     }
     $rows[] = array($this->t('Package type:'), isset($pkg_type) ? $pkg_type : SafeMarkup::checkPlain($package->pkg_type));
     if ($package->length && $package->width && $package->height) {
         $rows[] = array($this->t('Dimensions:'), $this->t('@l x @w x @h', ['@l' => uc_length_format($package->length), '@w' => uc_length_format($package->width), '@h' => uc_length_format($package->height)]));
     }
     $rows[] = array($this->t('Insured value:'), array('data' => array('#theme' => 'uc_price', '#price' => $package->value)));
     if ($package->tracking_number) {
         $rows[] = array($this->t('Tracking number:'), SafeMarkup::checkPlain($package->tracking_number));
     }
     if ($shipment && isset($package->label_image) && file_exists($package->label_image->uri)) {
         $rows[] = array($this->t('Label:'), Link::fromTextAndUrl($this->t('Click to view.'), Url::fromUri('admin/store/orders/' . $package->order_id . '/shipments/labels/' . $shipment->shipping_method . '/' . $package->label_image->uri))->toString());
     } else {
         $rows[] = array($this->t('Label:'), $this->t('n/a'));
     }
     $build['package'] = array('#theme' => 'table', '#rows' => $rows, 'attributes' => array('style' => 'width:auto;'));
     return $build;
 }