/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $filter_values = $this->translateFilterValues(); $langcode = $filter_values['langcode']; $this->languageManager->reset(); $languages = $this->languageManager->getLanguages(); $langname = isset($langcode) ? $languages[$langcode]->getName() : "- None -"; $form['#attached']['library'][] = 'locale/drupal.locale.admin'; $form['langcode'] = array('#type' => 'value', '#value' => $filter_values['langcode']); $form['strings'] = array('#type' => 'table', '#tree' => TRUE, '#language' => $langname, '#header' => [$this->t('Source string'), $this->t('Translation for @language', ['@language' => $langname])], '#empty' => $this->t('No strings available.'), '#attributes' => ['class' => ['locale-translate-edit-table']]); if (isset($langcode)) { $strings = $this->translateFilterLoadStrings(); $plural_formulas = $this->state->get('locale.translation.plurals') ?: array(); foreach ($strings as $string) { // Cast into source string, will do for our purposes. $source = new SourceString($string); // Split source to work with plural values. $source_array = $source->getPlurals(); $translation_array = $string->getPlurals(); if (count($source_array) == 1) { // Add original string value and mark as non-plural. $plural = FALSE; $form['strings'][$string->lid]['original'] = array('#type' => 'item', '#title' => $this->t('Source string (@language)', array('@language' => $this->t('Built-in English'))), '#title_display' => 'invisible', '#markup' => '<span lang="en">' . String::checkPlain($source_array[0]) . '</span>'); } else { // Add original string value and mark as plural. $plural = TRUE; $original_singular = ['#type' => 'item', '#title' => $this->t('Singular form'), '#markup' => '<span lang="en">' . String::checkPlain($source_array[0]) . '</span>', '#prefix' => '<span class="visually-hidden">' . $this->t('Source string (@language)', array('@language' => $this->t('Built-in English'))) . '</span>']; $original_plural = ['#type' => 'item', '#title' => $this->t('Plural form'), '#markup' => '<span lang="en">' . String::checkPlain($source_array[1]) . '</span>']; $form['strings'][$string->lid]['original'] = [$original_singular, ['#markup' => '<br>'], $original_plural]; } if (!empty($string->context)) { $form['strings'][$string->lid]['original'][] = ['#type' => 'inline_template', '#template' => '<br><small>{{ context_title }}: <span lang="en">{{ context }}</span></small>', '#context' => ['context_title' => $this->t('In Context'), 'context' => $string->context]]; } // Approximate the number of rows to use in the default textarea. $rows = min(ceil(str_word_count($source_array[0]) / 12), 10); if (!$plural) { $form['strings'][$string->lid]['translations'][0] = array('#type' => 'textarea', '#title' => $this->t('Translated string (@language)', array('@language' => $langname)), '#title_display' => 'invisible', '#rows' => $rows, '#default_value' => $translation_array[0], '#attributes' => array('lang' => $langcode)); } else { // Dealing with plural strings. if (isset($plural_formulas[$langcode]['plurals']) && $plural_formulas[$langcode]['plurals'] > 2) { // Add a textarea for each plural variant. for ($i = 0; $i < $plural_formulas[$langcode]['plurals']; $i++) { $form['strings'][$string->lid]['translations'][$i] = array('#type' => 'textarea', '#title' => $i == 0 ? $this->t('Singular form') : $this->formatPlural($i, 'First plural form', '@count. plural form'), '#rows' => $rows, '#default_value' => isset($translation_array[$i]) ? $translation_array[$i] : '', '#attributes' => array('lang' => $langcode), '#prefix' => $i == 0 ? '<span class="visually-hidden">' . $this->t('Translated string (@language)', array('@language' => $langname)) . '</span>' : ''); } } else { // Fallback for unknown number of plurals. $form['strings'][$string->lid]['translations'][0] = array('#type' => 'textarea', '#title' => $this->t('Singular form'), '#rows' => $rows, '#default_value' => $translation_array[0], '#attributes' => array('lang' => $langcode), '#prefix' => '<span class="visually-hidden">' . $this->t('Translated string (@language)', array('@language' => $langname)) . '</span>'); $form['strings'][$string->lid]['translations'][1] = array('#type' => 'textarea', '#title' => $this->t('Plural form'), '#rows' => $rows, '#default_value' => isset($translation_array[1]) ? $translation_array[1] : '', '#attributes' => array('lang' => $langcode)); } } } if (count(Element::children($form['strings']))) { $form['actions'] = array('#type' => 'actions'); $form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Save translations')); } } $form['pager']['#type'] = 'pager'; return $form; }
/** * Returns a string representation of the attribute. * * While __toString only returns the value in a string form, render() * contains the name of the attribute as well. * * @return string * The string representation of the attribute. */ public function render() { $value = (string) $this; if (isset($this->value) && static::RENDER_EMPTY_ATTRIBUTE || !empty($value)) { return String::checkPlain($this->name) . '="' . $value . '"'; } }
/** * */ public function submitForm(array &$form, FormStateInterface $form_state) { ini_set('max_execution_time', $this->max_execution); $count = $this->deleteAllUsers(); drupal_set_message($this->t('All users have been deleted. Number of users deleted: !count.', array('!count' => String::checkPlain($count)))); $form_state->setRedirect('user.admin_account'); }
/** * Assert that a trail exists in the internal browser. * * @param array $trail * An associative array whose keys are expected breadcrumb link paths and * whose values are expected breadcrumb link texts (not sanitized). */ protected function assertBreadcrumbParts($trail) { // Compare paths with actual breadcrumb. $parts = $this->getBreadcrumbParts(); $pass = TRUE; // There may be more than one breadcrumb on the page. If $trail is empty // this test would go into an infinite loop, so we need to check that too. while ($trail && !empty($parts)) { foreach ($trail as $path => $title) { // If the path is empty, generate the path from the <front> route. If // the path does not start with a leading, then run it through // Url::fromUri('base:')->toString() to get correct the base // prepended. if ($path == '') { $url = Url::fromRoute('<front>')->toString(); } elseif ($path[0] != '/') { $url = Url::fromUri('base:' . $path)->toString(); } else { $url = $path; } $part = array_shift($parts); $pass = $pass && $part['href'] === $url && $part['text'] === String::checkPlain($title); } } // No parts must be left, or an expected "Home" will always pass. $pass = $pass && empty($parts); $this->assertTrue($pass, format_string('Breadcrumb %parts found on @path.', array('%parts' => implode(' » ', $trail), '@path' => $this->getUrl()))); }
/** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items) { $elements = array(); $output_as_link = $this->getSetting('link'); foreach ($this->getEntitiesToView($items) as $delta => $entity) { $label = $entity->label(); // If the link is to be displayed and the entity has a uri, display a // link. if ($output_as_link && !$entity->isNew()) { try { $uri = $entity->urlInfo(); } catch (UndefinedLinkTemplateException $e) { // This exception is thrown by \Drupal\Core\Entity\Entity::urlInfo() // and it means that the entity type doesn't have a link template nor // a valid "uri_callback", so don't bother trying to output a link for // the rest of the referenced entities. $output_as_link = FALSE; } } if ($output_as_link && isset($uri) && !$entity->isNew()) { $elements[$delta] = ['#type' => 'link', '#title' => $label, '#url' => $uri, '#options' => $uri->getOptions()]; if (!empty($items[$delta]->_attributes)) { $elements[$delta]['#options'] += array('attributes' => array()); $elements[$delta]['#options']['attributes'] += $items[$delta]->_attributes; // Unset field item attributes since they have been included in the // formatter output and shouldn't be rendered in the field template. unset($items[$delta]->_attributes); } } else { $elements[$delta] = array('#markup' => String::checkPlain($label)); } $elements[$delta]['#cache']['tags'] = $entity->getCacheTags(); } return $elements; }
/** * {@inheritdoc} */ public function form(array $form, FormStateInterface $form_state) { $form = parent::form($form, $form_state); $type = $this->entity; if ($this->operation == 'add') { $form['#title'] = String::checkPlain($this->t('Add content type')); } elseif ($this->operation == 'edit') { $form['#title'] = $this->t('Edit %label content type', array('%label' => $type->label())); } $node_settings = $type->getModuleSettings('node'); // Prepare node options to be used for 'checkboxes' form element. $keys = array_keys(array_filter($node_settings['options'])); $node_settings['options'] = array_combine($keys, $keys); $form['name'] = array('#title' => t('Name'), '#type' => 'textfield', '#default_value' => $type->name, '#description' => t('The human-readable name of this content type. This text will be displayed as part of the list on the <em>Add content</em> page. It is recommended that this name begin with a capital letter and contain only letters, numbers, and spaces. This name must be unique.'), '#required' => TRUE, '#size' => 30); $form['type'] = array('#type' => 'machine_name', '#default_value' => $type->id(), '#maxlength' => EntityTypeInterface::BUNDLE_MAX_LENGTH, '#disabled' => $type->isLocked(), '#machine_name' => array('exists' => 'node_type_load', 'source' => array('name')), '#description' => t('A unique machine-readable name for this content type. It must only contain lowercase letters, numbers, and underscores. This name will be used for constructing the URL of the %node-add page, in which underscores will be converted into hyphens.', array('%node-add' => t('Add content')))); $form['description'] = array('#title' => t('Description'), '#type' => 'textarea', '#default_value' => $type->description, '#description' => t('Describe this content type. The text will be displayed on the <em>Add content</em> page.')); $form['additional_settings'] = array('#type' => 'vertical_tabs', '#attached' => array('library' => array('node/drupal.content_types'))); $form['submission'] = array('#type' => 'details', '#title' => t('Submission form settings'), '#group' => 'additional_settings', '#open' => TRUE); $form['submission']['title_label'] = array('#title' => t('Title field label'), '#type' => 'textfield', '#default_value' => $type->title_label, '#required' => TRUE); $form['submission']['preview'] = array('#type' => 'radios', '#title' => t('Preview before submitting'), '#parents' => array('settings', 'node', 'preview'), '#default_value' => $node_settings['preview'], '#options' => array(DRUPAL_DISABLED => t('Disabled'), DRUPAL_OPTIONAL => t('Optional'), DRUPAL_REQUIRED => t('Required'))); $form['submission']['help'] = array('#type' => 'textarea', '#title' => t('Explanation or submission guidelines'), '#default_value' => $type->help, '#description' => t('This text will be displayed at the top of the page when creating or editing content of this type.')); $form['workflow'] = array('#type' => 'details', '#title' => t('Publishing options'), '#group' => 'additional_settings'); $form['workflow']['options'] = array('#type' => 'checkboxes', '#title' => t('Default options'), '#parents' => array('settings', 'node', 'options'), '#default_value' => $node_settings['options'], '#options' => array('status' => t('Published'), 'promote' => t('Promoted to front page'), 'sticky' => t('Sticky at top of lists'), 'revision' => t('Create new revision')), '#description' => t('Users with the <em>Administer content</em> permission will be able to override these options.')); if ($this->moduleHandler->moduleExists('language')) { $form['language'] = array('#type' => 'details', '#title' => t('Language settings'), '#group' => 'additional_settings'); $language_configuration = language_get_default_configuration('node', $type->id()); $form['language']['language_configuration'] = array('#type' => 'language_configuration', '#entity_information' => array('entity_type' => 'node', 'bundle' => $type->id()), '#default_value' => $language_configuration); } $form['display'] = array('#type' => 'details', '#title' => t('Display settings'), '#group' => 'additional_settings'); $form['display']['submitted'] = array('#type' => 'checkbox', '#title' => t('Display author and date information.'), '#parents' => array('settings', 'node', 'submitted'), '#default_value' => $node_settings['submitted'], '#description' => t('Author username and publish date will be displayed.')); return $form; }
/** * Tests tablesort_init(). */ function testTableSortInit() { // Test simple table headers. $headers = array('foo', 'bar', 'baz'); // Reset $requesr->query to prevent parameters from Simpletest and Batch API // ending up in $ts['query']. $expected_ts = array('name' => 'foo', 'sql' => '', 'sort' => 'asc', 'query' => array()); $request = Request::createFromGlobals(); $request->query->replace(array()); \Drupal::getContainer()->get('request_stack')->push($request); $ts = tablesort_init($headers); $this->verbose(strtr('$ts: <pre>!ts</pre>', array('!ts' => String::checkPlain(var_export($ts, TRUE))))); $this->assertEqual($ts, $expected_ts, 'Simple table headers sorted correctly.'); // Test with simple table headers plus $_GET parameters that should _not_ // override the default. $request = Request::createFromGlobals(); $request->query->replace(array('order' => 'bar')); \Drupal::getContainer()->get('request_stack')->push($request); $ts = tablesort_init($headers); $this->verbose(strtr('$ts: <pre>!ts</pre>', array('!ts' => String::checkPlain(var_export($ts, TRUE))))); $this->assertEqual($ts, $expected_ts, 'Simple table headers plus non-overriding $_GET parameters sorted correctly.'); // Test with simple table headers plus $_GET parameters that _should_ // override the default. $request = Request::createFromGlobals(); $request->query->replace(array('sort' => 'DESC', 'alpha' => 'beta')); \Drupal::getContainer()->get('request_stack')->push($request); $expected_ts['sort'] = 'desc'; $expected_ts['query'] = array('alpha' => 'beta'); $ts = tablesort_init($headers); $this->verbose(strtr('$ts: <pre>!ts</pre>', array('!ts' => String::checkPlain(var_export($ts, TRUE))))); $this->assertEqual($ts, $expected_ts, 'Simple table headers plus $_GET parameters sorted correctly.'); // Test complex table headers. $headers = array('foo', array('data' => '1', 'field' => 'one', 'sort' => 'asc', 'colspan' => 1), array('data' => '2', 'field' => 'two', 'sort' => 'desc')); // Reset $_GET from previous assertion. $request = Request::createFromGlobals(); $request->query->replace(array('order' => '2')); \Drupal::getContainer()->get('request_stack')->push($request); $ts = tablesort_init($headers); $expected_ts = array('name' => '2', 'sql' => 'two', 'sort' => 'desc', 'query' => array()); $this->verbose(strtr('$ts: <pre>!ts</pre>', array('!ts' => String::checkPlain(var_export($ts, TRUE))))); $this->assertEqual($ts, $expected_ts, 'Complex table headers sorted correctly.'); // Test complex table headers plus $_GET parameters that should _not_ // override the default. $request = Request::createFromGlobals(); $request->query->replace(array('order' => 'bar')); \Drupal::getContainer()->get('request_stack')->push($request); $ts = tablesort_init($headers); $expected_ts = array('name' => '1', 'sql' => 'one', 'sort' => 'asc', 'query' => array()); $this->verbose(strtr('$ts: <pre>!ts</pre>', array('!ts' => String::checkPlain(var_export($ts, TRUE))))); $this->assertEqual($ts, $expected_ts, 'Complex table headers plus non-overriding $_GET parameters sorted correctly.'); // Test complex table headers plus $_GET parameters that _should_ // override the default. $request = Request::createFromGlobals(); $request->query->replace(array('order' => '1', 'sort' => 'ASC', 'alpha' => 'beta')); \Drupal::getContainer()->get('request_stack')->push($request); $expected_ts = array('name' => '1', 'sql' => 'one', 'sort' => 'asc', 'query' => array('alpha' => 'beta')); $ts = tablesort_init($headers); $this->verbose(strtr('$ts: <pre>!ts</pre>', array('!ts' => String::checkPlain(var_export($ts, TRUE))))); $this->assertEqual($ts, $expected_ts, 'Complex table headers plus $_GET parameters sorted correctly.'); }
/** * {@inheritdoc} */ public function viewMultiple(array $entities = array(), $view_mode = 'full', $langcode = NULL) { // @todo Remove when https://www.drupal.org/node/2453059 lands. $default_cache_contexts = ['languages', 'theme']; /** @var \Drupal\block\BlockInterface[] $entities */ $build = array(); foreach ($entities as $entity) { $entity_id = $entity->id(); $plugin = $entity->getPlugin(); $plugin_id = $plugin->getPluginId(); $base_id = $plugin->getBaseId(); $derivative_id = $plugin->getDerivativeId(); $configuration = $plugin->getConfiguration(); // Create the render array for the block as a whole. // @see template_preprocess_block(). $build[$entity_id] = array('#theme' => 'block', '#attributes' => array(), '#contextual_links' => array('block' => array('route_parameters' => array('block' => $entity->id()))), '#weight' => $entity->getWeight(), '#configuration' => $configuration, '#plugin_id' => $plugin_id, '#base_plugin_id' => $base_id, '#derivative_plugin_id' => $derivative_id, '#id' => $entity->id(), '#cache' => ['contexts' => Cache::mergeContexts($default_cache_contexts, $plugin->getCacheContexts()), 'tags' => Cache::mergeTags($this->getCacheTags(), $entity->getCacheTags(), $plugin->getCacheTags()), 'max-age' => $plugin->getCacheMaxAge()], '#block' => $entity); $build[$entity_id]['#configuration']['label'] = String::checkPlain($configuration['label']); if ($plugin->isCacheable()) { $build[$entity_id]['#pre_render'][] = array($this, 'buildBlock'); // Generic cache keys, with the block plugin's custom keys appended. $default_cache_keys = array('entity_view', 'block', $entity->id()); $build[$entity_id]['#cache']['keys'] = array_merge($default_cache_keys, $plugin->getCacheKeys()); } else { $build[$entity_id] = $this->buildBlock($build[$entity_id]); } // Don't run in ::buildBlock() to ensure cache keys can be altered. If an // alter hook wants to modify the block contents, it can append another // #pre_render hook. $this->moduleHandler()->alter(array('block_view', "block_view_{$base_id}"), $build[$entity_id], $plugin); } return $build; }
public function preRender(&$values) { $uids = array(); $this->items = array(); foreach ($values as $result) { $uids[] = $this->getValue($result); } if ($uids) { $roles = user_roles(); $result = $this->database->query('SELECT u.uid, u.rid FROM {users_roles} u WHERE u.uid IN (:uids) AND u.rid IN (:rids)', array(':uids' => $uids, ':rids' => array_keys($roles))); foreach ($result as $role) { $this->items[$role->uid][$role->rid]['role'] = String::checkPlain($roles[$role->rid]->label()); $this->items[$role->uid][$role->rid]['rid'] = $role->rid; } // Sort the roles for each user by role weight. $ordered_roles = array_flip(array_keys($roles)); foreach ($this->items as &$user_roles) { // Create an array of rids that the user has in the role weight order. $sorted_keys = array_intersect_key($ordered_roles, $user_roles); // Merge with the unsorted array of role information which has the // effect of sorting it. $user_roles = array_merge($sorted_keys, $user_roles); } } }
/** * Log 404 errors. * * @param \Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent $event * The event to process. */ public function on404(GetResponseForExceptionEvent $event) { $request = $event->getRequest(); // @todo Remove dependency on the internal _system_path attribute: // https://www.drupal.org/node/2293523. $this->logger->get('page not found')->warning(String::checkPlain($request->attributes->get('_system_path'))); }
/** * Test configuration and subsequent form() and build() method calls. * * This test is attempting to test the existing block plugin api and all * functionality that is expected to remain consistent. The arrays that are * used for comparison can change, but only to include elements that are * contained within BlockBase or the plugin being tested. Likely these * comparison arrays should get smaller, not larger, as more form/build * elements are moved into a more suitably responsible class. * * Instantiation of the plugin is the primary element being tested here. The * subsequent method calls are just attempting to cause a failure if a * dependency outside of the plugin configuration is required. */ public function testBlockInterface() { $manager = $this->container->get('plugin.manager.block'); $configuration = array('label' => 'Custom Display Message'); $expected_configuration = array('id' => 'test_block_instantiation', 'label' => 'Custom Display Message', 'provider' => 'block_test', 'label_display' => BlockInterface::BLOCK_LABEL_VISIBLE, 'cache' => array('max_age' => 0, 'contexts' => array()), 'display_message' => 'no message set'); // Initial configuration of the block at construction time. /** @var $display_block \Drupal\Core\Block\BlockPluginInterface */ $display_block = $manager->createInstance('test_block_instantiation', $configuration); $this->assertIdentical($display_block->getConfiguration(), $expected_configuration, 'The block was configured correctly.'); // Updating an element of the configuration. $display_block->setConfigurationValue('display_message', 'My custom display message.'); $expected_configuration['display_message'] = 'My custom display message.'; $this->assertIdentical($display_block->getConfiguration(), $expected_configuration, 'The block configuration was updated correctly.'); $definition = $display_block->getPluginDefinition(); $period = array(0, 60, 180, 300, 600, 900, 1800, 2700, 3600, 10800, 21600, 32400, 43200, 86400); $period = array_map(array(\Drupal::service('date.formatter'), 'formatInterval'), array_combine($period, $period)); $period[0] = '<' . t('no caching') . '>'; $period[\Drupal\Core\Cache\Cache::PERMANENT] = t('Forever'); $contexts = \Drupal::service("cache_contexts")->getLabels(); unset($contexts['theme']); unset($contexts['languages']); $expected_form = array('provider' => array('#type' => 'value', '#value' => 'block_test'), 'admin_label' => array('#type' => 'item', '#title' => t('Block description'), '#markup' => String::checkPlain($definition['admin_label'])), 'label' => array('#type' => 'textfield', '#title' => 'Title', '#maxlength' => 255, '#default_value' => 'Custom Display Message', '#required' => TRUE), 'label_display' => array('#type' => 'checkbox', '#title' => 'Display title', '#default_value' => TRUE, '#return_value' => 'visible'), 'cache' => array('#type' => 'details', '#title' => t('Cache settings'), 'max_age' => array('#type' => 'select', '#title' => t('Maximum age'), '#description' => t('The maximum time this block may be cached.'), '#default_value' => 0, '#options' => $period), 'contexts' => array('#type' => 'checkboxes', '#title' => t('Vary by context'), '#description' => t('The contexts this cached block must be varied by. <em>All</em> blocks are varied by language and theme.'), '#default_value' => array(), '#options' => $contexts, '#states' => array('disabled' => array(':input[name="settings[cache][max_age]"]' => array('value' => (string) 0))))), 'display_message' => array('#type' => 'textfield', '#title' => t('Display message'), '#default_value' => 'My custom display message.')); $form_state = new FormState(); // Ensure there are no form elements that do not belong to the plugin. $actual_form = $display_block->buildConfigurationForm(array(), $form_state); // Remove the visibility sections, as that just tests condition plugins. unset($actual_form['visibility'], $actual_form['visibility_tabs']); $this->assertIdentical($actual_form, $expected_form, 'Only the expected form elements were present.'); $expected_build = array('#children' => 'My custom display message.'); // Ensure the build array is proper. $this->assertIdentical($display_block->build(), $expected_build, 'The plugin returned the appropriate build array.'); // Ensure the machine name suggestion is correct. In truth, this is actually // testing BlockBase's implementation, not the interface itself. $this->assertIdentical($display_block->getMachineNameSuggestion(), 'displaymessage', 'The plugin returned the expected machine name suggestion.'); }
/** * {@inheritdoc} */ public function generateFieldMetadata(FieldItemListInterface $items, $view_mode) { $entity = $items->getEntity(); $field_name = $items->getFieldDefinition()->getName(); // Early-return if user does not have access. $access = $this->accessChecker->accessEditEntityField($entity, $field_name); if (!$access) { return array('access' => FALSE); } // Early-return if no editor is available. $formatter_id = EntityViewDisplay::collectRenderDisplay($entity, $view_mode)->getRenderer($field_name)->getPluginId(); $editor_id = $this->editorSelector->getEditor($formatter_id, $items); if (!isset($editor_id)) { return array('access' => FALSE); } // Gather metadata, allow the editor to add additional metadata of its own. $label = $items->getFieldDefinition()->getLabel(); $editor = $this->editorManager->createInstance($editor_id); $metadata = array('label' => String::checkPlain($label), 'access' => TRUE, 'editor' => $editor_id, 'aria' => t('Entity @type @id, field @field', array('@type' => $entity->getEntityTypeId(), '@id' => $entity->id(), '@field' => $label))); $custom_metadata = $editor->getMetadata($items); if (count($custom_metadata)) { $metadata['custom'] = $custom_metadata; } return $metadata; }
/** * Tests the title_query method. * * @see \Drupal\user\Plugin\views\argument\RolesRid::title_query() */ public function testTitleQuery() { $role1 = new Role(array('id' => 'test_rid_1', 'label' => 'test rid 1'), 'user_role'); $role2 = new Role(array('id' => 'test_rid_2', 'label' => 'test <strong>rid 2</strong>'), 'user_role'); // Creates a stub entity storage; $role_storage = $this->getMockForAbstractClass('Drupal\\Core\\Entity\\EntityStorageInterface'); $role_storage->expects($this->any())->method('loadMultiple')->will($this->returnValueMap(array(array(array(), array()), array(array('test_rid_1'), array('test_rid_1' => $role1)), array(array('test_rid_1', 'test_rid_2'), array('test_rid_1' => $role1, 'test_rid_2' => $role2))))); $entity_type = $this->getMock('Drupal\\Core\\Entity\\EntityTypeInterface'); $entity_type->expects($this->any())->method('getKey')->with('label')->will($this->returnValue('label')); $entity_manager = $this->getMock('Drupal\\Core\\Entity\\EntityManagerInterface'); $entity_manager->expects($this->any())->method('getDefinition')->with($this->equalTo('user_role'))->will($this->returnValue($entity_type)); $entity_manager->expects($this->once())->method('getStorage')->with($this->equalTo('user_role'))->will($this->returnValue($role_storage)); // @todo \Drupal\Core\Entity\Entity::entityType() uses a global call to // entity_get_info(), which in turn wraps \Drupal::entityManager(). Set // the entity manager until this is fixed. $container = new ContainerBuilder(); $container->set('entity.manager', $entity_manager); \Drupal::setContainer($container); $roles_rid_argument = new RolesRid(array(), 'user__roles_rid', array(), $entity_manager); $roles_rid_argument->value = array(); $titles = $roles_rid_argument->title_query(); $this->assertEquals(array(), $titles); $roles_rid_argument->value = array('test_rid_1'); $titles = $roles_rid_argument->title_query(); $this->assertEquals(array('test rid 1'), $titles); $roles_rid_argument->value = array('test_rid_1', 'test_rid_2'); $titles = $roles_rid_argument->title_query(); $this->assertEquals(array('test rid 1', String::checkPlain('test <strong>rid 2</strong>')), $titles); }
/** * Overrides \Drupal\tour\Plugin\tour\tour\TipPluginInterface::getOutput(). */ public function getOutput() { $image = array('#theme' => 'image', '#uri' => $this->get('url'), '#alt' => $this->get('alt')); $output = '<h2 class="tour-tip-label" id="tour-tip-' . $this->get('ariaId') . '-label">' . String::checkPlain($this->get('label')) . '</h2>'; $output .= '<p class="tour-tip-image" id="tour-tip-' . $this->get('ariaId') . '-contents">' . drupal_render($image) . '</p>'; return array('#markup' => $output); }
/** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items) { $elements = array(); foreach ($items as $delta => $item) { if (!$item->access) { // User doesn't have access to the referenced entity. continue; } /** @var $referenced_entity \Drupal\Core\Entity\EntityInterface */ if ($referenced_entity = $item->entity) { $label = $referenced_entity->label(); // If the link is to be displayed and the entity has a uri, display a // link. if ($this->getSetting('link') && ($uri = $referenced_entity->urlInfo())) { $elements[$delta] = array('#type' => 'link', '#title' => $label) + $uri->toRenderArray(); if (!empty($item->_attributes)) { $elements[$delta]['#options'] += array('attributes' => array()); $elements[$delta]['#options']['attributes'] += $item->_attributes; // Unset field item attributes since they have been included in the // formatter output and shouldn't be rendered in the field template. unset($item->_attributes); } } else { $elements[$delta] = array('#markup' => String::checkPlain($label)); } $elements[$delta]['#cache']['tags'] = $referenced_entity->getCacheTag(); } } return $elements; }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state, UserInterface $user = NULL) { $account = $this->currentUser(); $this->user = $user; // Prepare the list of shortcut sets. $options = array_map(function (ShortcutSet $set) { return String::checkPlain($set->label()); }, $this->shortcutSetStorage->loadMultiple()); $current_set = shortcut_current_displayed_set($this->user); // Only administrators can add shortcut sets. $add_access = $account->hasPermission('administer shortcuts'); if ($add_access) { $options['new'] = $this->t('New set'); } $account_is_user = $this->user->id() == $account->id(); if (count($options) > 1) { $form['set'] = array('#type' => 'radios', '#title' => $account_is_user ? $this->t('Choose a set of shortcuts to use') : $this->t('Choose a set of shortcuts for this user'), '#options' => $options, '#default_value' => $current_set->id()); $form['label'] = array('#type' => 'textfield', '#title' => $this->t('Label'), '#description' => $this->t('The new set is created by copying items from your default shortcut set.'), '#access' => $add_access, '#states' => array('visible' => array(':input[name="set"]' => array('value' => 'new')))); $form['id'] = array('#type' => 'machine_name', '#machine_name' => array('exists' => array($this, 'exists'), 'replace_pattern' => '[^a-z0-9-]+', 'replace' => '-'), '#maxlength' => 23, '#states' => array('required' => array(':input[name="set"]' => array('value' => 'new'))), '#required' => FALSE); if (!$account_is_user) { $default_set = $this->shortcutSetStorage->getDefaultSet($this->user); $form['new']['#description'] = $this->t('The new set is created by copying items from the %default set.', array('%default' => $default_set->label())); } $form['actions'] = array('#type' => 'actions'); $form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Change set')); } else { // There is only 1 option, so output a message in the $form array. $form['info'] = array('#markup' => '<p>' . $this->t('You are currently using the %set-name shortcut set.', array('%set-name' => $current_set->label())) . '</p>'); } return $form; }
/** * Creates a node, then tests the tokens generated from it. */ function testNodeTokenReplacement() { $url_options = array('absolute' => TRUE, 'language' => $this->interfaceLanguage); // Create a user and a node. $account = $this->createUser(); /* @var $node \Drupal\node\NodeInterface */ $node = entity_create('node', array('type' => 'article', 'tnid' => 0, 'uid' => $account->id(), 'title' => '<blink>Blinking Text</blink>', 'body' => array(array('value' => $this->randomName(32), 'summary' => $this->randomName(16), 'format' => 'plain_text')))); $node->save(); // Generate and test sanitized tokens. $tests = array(); $tests['[node:nid]'] = $node->id(); $tests['[node:vid]'] = $node->getRevisionId(); $tests['[node:type]'] = 'article'; $tests['[node:type-name]'] = 'Article'; $tests['[node:title]'] = String::checkPlain($node->getTitle()); $tests['[node:body]'] = $node->body->processed; $tests['[node:summary]'] = $node->body->summary_processed; $tests['[node:langcode]'] = String::checkPlain($node->language()->id); $tests['[node:url]'] = url('node/' . $node->id(), $url_options); $tests['[node:edit-url]'] = url('node/' . $node->id() . '/edit', $url_options); $tests['[node:author]'] = String::checkPlain($account->getUsername()); $tests['[node:author:uid]'] = $node->getOwnerId(); $tests['[node:author:name]'] = String::checkPlain($account->getUsername()); $tests['[node:created:since]'] = \Drupal::service('date')->formatInterval(REQUEST_TIME - $node->getCreatedTime(), 2, $this->interfaceLanguage->id); $tests['[node:changed:since]'] = \Drupal::service('date')->formatInterval(REQUEST_TIME - $node->getChangedTime(), 2, $this->interfaceLanguage->id); // Test to make sure that we generated something for each token. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated.'); foreach ($tests as $input => $expected) { $output = $this->tokenService->replace($input, array('node' => $node), array('langcode' => $this->interfaceLanguage->id)); $this->assertEqual($output, $expected, format_string('Sanitized node token %token replaced.', array('%token' => $input))); } // Generate and test unsanitized tokens. $tests['[node:title]'] = $node->getTitle(); $tests['[node:body]'] = $node->body->value; $tests['[node:summary]'] = $node->body->summary; $tests['[node:langcode]'] = $node->language()->id; $tests['[node:author:name]'] = $account->getUsername(); foreach ($tests as $input => $expected) { $output = $this->tokenService->replace($input, array('node' => $node), array('langcode' => $this->interfaceLanguage->id, 'sanitize' => FALSE)); $this->assertEqual($output, $expected, format_string('Unsanitized node token %token replaced.', array('%token' => $input))); } // Repeat for a node without a summary. $node = entity_create('node', array('type' => 'article', 'uid' => $account->id(), 'title' => '<blink>Blinking Text</blink>', 'body' => array(array('value' => $this->randomName(32), 'format' => 'plain_text')))); $node->save(); // Generate and test sanitized token - use full body as expected value. $tests = array(); $tests['[node:summary]'] = $node->body->processed; // Test to make sure that we generated something for each token. $this->assertFalse(in_array(0, array_map('strlen', $tests)), 'No empty tokens generated for node without a summary.'); foreach ($tests as $input => $expected) { $output = $this->tokenService->replace($input, array('node' => $node), array('language' => $this->interfaceLanguage)); $this->assertEqual($output, $expected, format_string('Sanitized node token %token replaced for node without a summary.', array('%token' => $input))); } // Generate and test unsanitized tokens. $tests['[node:summary]'] = $node->body->value; foreach ($tests as $input => $expected) { $output = $this->tokenService->replace($input, array('node' => $node), array('language' => $this->interfaceLanguage, 'sanitize' => FALSE)); $this->assertEqual($output, $expected, format_string('Unsanitized node token %token replaced for node without a summary.', array('%token' => $input))); } }
/** * Perform a single batch operation. * * Callback for batch_set(). * * @param $MULTIPLE_PARAMS * Additional parameters specific to the batch. These are specified in the * array passed to batch_set(). * @param $context * The batch context array, passed by reference. This contains the following * properties: * - 'finished': A float number between 0 and 1 informing the processing * engine of the completion level for the operation. 1 (or no value * explicitly set) means the operation is finished: the operation will not * be called again, and execution passes to the next operation or the * callback_batch_finished() implementation. Any other value causes this * operation to be called again; however it should be noted that the value * set here does not persist between executions of this callback: each time * it is set to 1 by default by the batch system. * - 'sandbox': This may be used by operations to persist data between * successive calls to the current operation. Any values set in * $context['sandbox'] will be there the next time this function is called * for the current operation. For example, an operation may wish to store a * pointer in a file or an offset for a large query. The 'sandbox' array key * is not initially set when this callback is first called, which makes it * useful for determining whether it is the first call of the callback or * not: * @code * if (empty($context['sandbox'])) { * // Perform set-up steps here. * } * @endcode * The values in the sandbox are stored and updated in the database between * http requests until the batch finishes processing. This avoids problems * if the user navigates away from the page before the batch finishes. * - 'message': A text message displayed in the progress page. * - 'results': The array of results gathered so far by the batch processing. * This array is highly useful for passing data between operations. After * all operations have finished, this is passed to callback_batch_finished() * where results may be referenced to display information to the end-user, * such as how many total items were processed. */ function callback_batch_operation($MULTIPLE_PARAMS, &$context) { $node_storage = $this->container->get('entity.manager')->getStorage('node'); if (!isset($context['sandbox']['progress'])) { $context['sandbox']['progress'] = 0; $context['sandbox']['current_node'] = 0; $context['sandbox']['max'] = db_query('SELECT COUNT(DISTINCT nid) FROM {node}')->fetchField(); } // For this example, we decide that we can safely process // 5 nodes at a time without a timeout. $limit = 5; // With each pass through the callback, retrieve the next group of nids. $result = db_query_range("SELECT nid FROM {node} WHERE nid > %d ORDER BY nid ASC", $context['sandbox']['current_node'], 0, $limit); while ($row = db_fetch_array($result)) { // Here we actually perform our processing on the current node. $node_storage->resetCache(array($row['nid'])); $node = $node_storage->load($row['nid']); $node->value1 = $options1; $node->value2 = $options2; node_save($node); // Store some result for post-processing in the finished callback. $context['results'][] = String::checkPlain($node->title); // Update our progress information. $context['sandbox']['progress']++; $context['sandbox']['current_node'] = $node->nid; $context['message'] = t('Now processing %node', array('%node' => $node->title)); } // Inform the batch engine that we are not finished, // and provide an estimation of the completion level we reached. if ($context['sandbox']['progress'] != $context['sandbox']['max']) { $context['finished'] = $context['sandbox']['progress'] / $context['sandbox']['max']; } }
/** * Overrides Drupal\Core\Entity\EntityForm::form(). * * @param array $form * A nested array form elements comprising the form. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. * @param \Drupal\responsive_image\ResponsiveImageMappingInterface $responsive_image_mapping * The entity being edited. * * @return array * The array containing the complete form. */ public function form(array $form, FormStateInterface $form_state) { if ($this->operation == 'duplicate') { $form['#title'] = $this->t('<em>Duplicate responsive image mapping</em> @label', array('@label' => $this->entity->label())); $this->entity = $this->entity->createDuplicate(); } if ($this->operation == 'edit') { $form['#title'] = $this->t('<em>Edit responsive image mapping</em> @label', array('@label' => $this->entity->label())); } /** @var \Drupal\responsive_image\ResponsiveImageMappingInterface $responsive_image_mapping */ $responsive_image_mapping = $this->entity; $form['label'] = array('#type' => 'textfield', '#title' => $this->t('Label'), '#maxlength' => 255, '#default_value' => $responsive_image_mapping->label(), '#description' => $this->t("Example: 'Hero image' or 'Author image'."), '#required' => TRUE); $form['id'] = array('#type' => 'machine_name', '#default_value' => $responsive_image_mapping->id(), '#machine_name' => array('exists' => '\\Drupal\\responsive_image\\Entity\\ResponsiveImageMapping::load', 'source' => array('label')), '#disabled' => (bool) $responsive_image_mapping->id() && $this->operation != 'duplicate'); if ((bool) $responsive_image_mapping->id() && $this->operation != 'duplicate') { $description = $this->t('Select a breakpoint group from the enabled themes.') . ' ' . $this->t("Warning: if you change the breakpoint group you lose all your selected mappings."); } else { $description = $this->t('Select a breakpoint group from the enabled themes.'); } $form['breakpointGroup'] = array('#type' => 'select', '#title' => $this->t('Breakpoint group'), '#default_value' => $responsive_image_mapping->getBreakpointGroup() != '' ? $responsive_image_mapping->getBreakpointGroup()->id() : '', '#options' => breakpoint_group_select_options(), '#required' => TRUE, '#description' => $description); $image_styles = image_style_options(TRUE); $image_styles[RESPONSIVE_IMAGE_EMPTY_IMAGE] = $this->t('- empty image -'); foreach ($responsive_image_mapping->getMappings() as $breakpoint_id => $mapping) { foreach ($mapping as $multiplier => $image_style) { $breakpoint = $responsive_image_mapping->getBreakpointGroup()->getBreakpointById($breakpoint_id); $label = $multiplier . ' ' . $breakpoint->name . ' [' . $breakpoint->mediaQuery . ']'; $form['mappings'][$breakpoint_id][$multiplier] = array('#type' => 'select', '#title' => String::checkPlain($label), '#options' => $image_styles, '#default_value' => $image_style, '#description' => $this->t('Select an image style for this breakpoint.')); } } $form['#tree'] = TRUE; return parent::form($form, $form_state, $responsive_image_mapping); }
/** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items) { $elements = array(); // Terms without target_id do not exist yet, theme such terms as just their // name. foreach ($items as $delta => $item) { if (!$item->target_id) { $elements[$delta] = array('#markup' => String::checkPlain($item->entity->label())); } else { /** @var $term \Drupal\taxonomy\TermInterface */ $term = $item->entity; $elements[$delta] = array('#type' => 'link', '#title' => $term->getName(), '#url' => $term->urlInfo()); if (!empty($item->_attributes)) { $options = $elements[$delta]['#url']->getOptions(); $options += ['attributes' => []]; $options['attributes'] += $item->_attributes; $elements[$delta]['#url']->setOptions($options); // Unset field item attributes since they have been included in the // formatter output and should not be rendered in the field template. unset($item->_attributes); } $elements[$delta]['#cache']['tags'] = $item->entity->getCacheTags(); } } return $elements; }
/** * {@inheritdoc} */ public function preRender(&$element) { $element_attributes = new \Drupal\Core\Template\Attribute(); if ($this->getSetting('attributes')) { // This regex split the attributes string so that we can pass that // later to drupal_attributes(). preg_match_all('/([^\\s=]+)="([^"]+)"/', $this->getSetting('attributes'), $matches); // Put the attribute and the value together. foreach ($matches[1] as $key => $attribute) { $element_attributes[$attribute] = $matches[2][$key]; } } // Add the classes to the attributes array. if ($this->getSetting('classes')) { if (!isset($element_attributes['class'])) { $element_attributes['class'] = array(); } $element_attributes['class'][] = $this->getSetting('classes'); } $element['#prefix'] = '<' . $this->getSetting('element') . $element_attributes . '>'; if ($this->getSetting('show_label')) { $element['#prefix'] .= '<' . $this->getSetting('label_element') . '><span>'; $element['#prefix'] .= String::checkPlain(\Drupal::translation()->translate($group->label)); $element['#prefix'] .= '</span></' . $this->getSetting('label_element') . '>'; } $element['#suffix'] = '</' . $this->getSetting('element') . '>'; }
/** * Form element #after_build callback: output the old form build-id. */ function form_test_storage_page_cache_old_build_id($form) { if (isset($form['#build_id_old'])) { $form['test_build_id_old']['#markup'] = String::checkPlain($form['#build_id_old']); } return $form; }
/** * {@inheritdoc} */ public function viewMultiple(array $entities = array(), $view_mode = 'full', $langcode = NULL) { /** @var \Drupal\block\BlockInterface[] $entities */ $build = array(); foreach ($entities as $entity) { $entity_id = $entity->id(); $plugin = $entity->getPlugin(); $plugin_id = $plugin->getPluginId(); $base_id = $plugin->getBaseId(); $derivative_id = $plugin->getDerivativeId(); $configuration = $plugin->getConfiguration(); // Create the render array for the block as a whole. // @see template_preprocess_block(). $build[$entity_id] = array('#theme' => 'block', '#attributes' => array(), '#contextual_links' => array('block' => array('route_parameters' => array('block' => $entity->id()))), '#weight' => $entity->get('weight'), '#configuration' => $configuration, '#plugin_id' => $plugin_id, '#base_plugin_id' => $base_id, '#derivative_plugin_id' => $derivative_id, '#id' => $entity->id(), '#block' => $entity); $build[$entity_id]['#configuration']['label'] = String::checkPlain($configuration['label']); // Set cache tags; these always need to be set, whether the block is // cacheable or not, so that the page cache is correctly informed. $build[$entity_id]['#cache']['tags'] = Cache::mergeTags($this->getCacheTag(), $entity->getCacheTag(), $plugin->getCacheTags()); if ($plugin->isCacheable()) { $build[$entity_id]['#pre_render'][] = array($this, 'buildBlock'); // Generic cache keys, with the block plugin's custom keys appended // (usually cache context keys like 'cache_context.user.roles'). $default_cache_keys = array('entity_view', 'block', $entity->id(), $this->languageManager->getCurrentLanguage()->getId(), 'cache_context.theme'); $max_age = $plugin->getCacheMaxAge(); $build[$entity_id]['#cache'] += array('keys' => array_merge($default_cache_keys, $plugin->getCacheKeys()), 'expire' => $max_age === Cache::PERMANENT ? Cache::PERMANENT : REQUEST_TIME + $max_age); } else { $build[$entity_id] = $this->buildBlock($build[$entity_id]); } // Don't run in ::buildBlock() to ensure cache keys can be altered. If an // alter hook wants to modify the block contents, it can append another // #pre_render hook. $this->moduleHandler()->alter(array('block_view', "block_view_{$base_id}"), $build[$entity_id], $plugin); } return $build; }
/** * Assert sorting by field and property. */ public function testSort() { // Add text field to entity, to sort by. entity_create('field_storage_config', array('field_name' => 'field_text', 'entity_type' => 'node', 'type' => 'text', 'entity_types' => array('node')))->save(); entity_create('field_config', array('label' => 'Text Field', 'field_name' => 'field_text', 'entity_type' => 'node', 'bundle' => 'article', 'settings' => array(), 'required' => FALSE))->save(); // Build a set of test data. $node_values = array('published1' => array('type' => 'article', 'status' => 1, 'title' => 'Node published1 (<&>)', 'uid' => 1, 'field_text' => array(array('value' => 1))), 'published2' => array('type' => 'article', 'status' => 1, 'title' => 'Node published2 (<&>)', 'uid' => 1, 'field_text' => array(array('value' => 2)))); $nodes = array(); $node_labels = array(); foreach ($node_values as $key => $values) { $node = Node::create($values); $node->save(); $nodes[$key] = $node; $node_labels[$key] = String::checkPlain($node->label()); } $selection_options = array('target_type' => 'node', 'handler' => 'default', 'handler_settings' => array('target_bundles' => array(), 'sort' => array('field' => 'field_text.value', 'direction' => 'DESC'))); $handler = $this->container->get('plugin.manager.entity_reference_selection')->getInstance($selection_options); // Not only assert the result, but make sure the keys are sorted as // expected. $result = $handler->getReferenceableEntities(); $expected_result = array($nodes['published2']->id() => $node_labels['published2'], $nodes['published1']->id() => $node_labels['published1']); $this->assertIdentical($result['article'], $expected_result, 'Query sorted by field returned expected values.'); // Assert sort by base field. $selection_options['handler_settings']['sort'] = array('field' => 'nid', 'direction' => 'ASC'); $handler = $this->container->get('plugin.manager.entity_reference_selection')->getInstance($selection_options); $result = $handler->getReferenceableEntities(); $expected_result = array($nodes['published1']->id() => $node_labels['published1'], $nodes['published2']->id() => $node_labels['published2']); $this->assertIdentical($result['article'], $expected_result, 'Query sorted by property returned expected values.'); }
/** * Override the behavior of title(). Get the name of the vocabulary. */ function title() { $vocabulary = entity_load('taxonomy_vocabulary', $this->argument); if ($vocabulary) { return String::checkPlain($vocabulary->label()); } return $this->t('No vocabulary'); }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state, $arg = NULL) { $form['element'] = array('#markup' => 'The FormTestArgumentsObject::buildForm() method was used for this form.'); $form['bananas'] = array('#type' => 'textfield', '#default_value' => String::checkPlain($arg), '#title' => $this->t('Bananas')); $form['actions']['#type'] = 'actions'; $form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Save')); return $form; }
/** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items) { $elements = array(); foreach ($items as $delta => $item) { $elements[$delta] = array('#markup' => String::checkPlain($item->entity->label())); } return $elements; }
/** * Override the behavior of title(). Get the name of the vocabulary. */ function title() { $vocabulary = $this->vocabularyStorage->load($this->argument); if ($vocabulary) { return String::checkPlain($vocabulary->label()); } return $this->t('No vocabulary'); }
/** * {@inheritdoc} */ public function buildForm(array $form, array &$form_state, $pid = NULL) { $form = parent::buildForm($form, $form_state, $pid); $form['#title'] = String::checkPlain($this->path['alias']); $form['pid'] = array('#type' => 'hidden', '#value' => $this->path['pid']); $form['actions']['delete'] = array('#type' => 'submit', '#value' => $this->t('Delete'), '#submit' => array(array($this, 'deleteSubmit'))); return $form; }
/** * {@inheritdoc} */ public function buildRow(EntityInterface $medium_editor) { $row['label'] = $medium_editor->label(); $row['description'] = String::checkPlain($medium_editor->get('description')); $row['toolbar'] = String::checkPlain(implode(', ', $medium_editor->getToolbar())); $row['delay'] = String::checkPlain($medium_editor->get('delay')); return $row + parent::buildRow($medium_editor); }