/** * {@inheritdoc} */ public function preRender(&$element, $rendering_object) { $element += array('#prefix' => '<div class=" ' . implode(' ', $this->getClasses()) . '">', '#suffix' => '</div>', '#tree' => TRUE, '#parents' => array($this->group->group_name), '#default_tab' => ''); if ($this->getSetting('id')) { $element['#id'] = Html::getId($this->getSetting('id')); } // By default tabs don't have titles but you can override it in the theme. if ($this->getLabel()) { $element['#title'] = SafeMarkup::checkPlain($this->getLabel()); } $form_state = new \Drupal\Core\Form\FormState(); if ($this->getSetting('direction') == 'vertical') { $element += array('#type' => 'vertical_tabs', '#theme_wrappers' => array('vertical_tabs')); $complete_form = array(); $element = \Drupal\Core\Render\Element\VerticalTabs::processVerticalTabs($element, $form_state, $complete_form); } else { $element += array('#type' => 'horizontal_tabs', '#theme_wrappers' => array('horizontal_tabs')); $on_form = $this->context == 'form'; $element = \Drupal\field_group\Element\HorizontalTabs::processHorizontalTabs($element, $form_state, $on_form); } // Make sure the group has 1 child. This is needed to succeed at form_pre_render_vertical_tabs(). // Skipping this would force us to move all child groups to this array, making it an un-nestable. $element['group']['#groups'][$this->group->group_name] = array(0 => array()); $element['group']['#groups'][$this->group->group_name]['#group_exists'] = TRUE; // Search for a tab that was marked as open. First one wins. foreach (\Drupal\Core\Render\Element::children($element) as $tab_name) { if (!empty($element[$tab_name]['#open'])) { $element[$this->group->group_name . '__active_tab']['#default_value'] = $tab_name; break; } } }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { module_load_include('inc', 'pathauto'); $config = $this->config('pathauto.settings'); $form = array(); $form['verbose'] = array('#type' => 'checkbox', '#title' => t('Verbose'), '#default_value' => $config->get('verbose'), '#description' => t('Display alias changes (except during bulk updates).')); $form['separator'] = array('#type' => 'textfield', '#title' => t('Separator'), '#size' => 1, '#maxlength' => 1, '#default_value' => $config->get('separator'), '#description' => t('Character used to separate words in titles. This will replace any spaces and punctuation characters. Using a space or + character can cause unexpected results.')); $form['case'] = array('#type' => 'radios', '#title' => t('Character case'), '#default_value' => $config->get('case'), '#options' => array(self::CASE_LEAVE_ASIS => t('Leave case the same as source token values.'), self::CASE_LOWER => t('Change to lower case'))); $max_length = \Drupal::service('pathauto.alias_storage_helper')->getAliasSchemaMaxlength(); $form['max_length'] = array('#type' => 'number', '#title' => t('Maximum alias length'), '#size' => 3, '#maxlength' => 3, '#default_value' => $config->get('max_length'), '#min' => 1, '#max' => $max_length, '#description' => t('Maximum length of aliases to generate. 100 is the recommended length. @max is the maximum possible length. See <a href="@pathauto-help">Pathauto help</a> for details.', array('@pathauto-help' => $this->getUrlGenerator()->generateFromPath('admin/help/pathauto'), '@max' => $max_length))); $form['max_component_length'] = array('#type' => 'number', '#title' => t('Maximum component length'), '#size' => 3, '#maxlength' => 3, '#default_value' => $config->get('max_component_length'), '#min' => 1, '#max' => $max_length, '#description' => t('Maximum text length of any component in the alias (e.g., [title]). 100 is the recommended length. @max is the maximum possible length. See <a href="@pathauto-help">Pathauto help</a> for details.', array('@pathauto-help' => $this->getUrlGenerator()->generateFromPath('admin/help/pathauto'), '@max' => $max_length))); $description = t('What should Pathauto do when updating an existing content item which already has an alias?'); if (\Drupal::moduleHandler()->moduleExists('redirect')) { $description .= ' ' . t('The <a href="!url">Redirect module settings</a> affect whether a redirect is created when an alias is deleted.', array('!url' => \Drupal::url('redirect.settings'))); } else { $description .= ' ' . t('Considering installing the <a href="!url">Redirect module</a> to get redirects when your aliases change.', array('!url' => 'http://drupal.org/project/redirect')); } $form['update_action'] = array('#type' => 'radios', '#title' => t('Update action'), '#default_value' => $config->get('update_action'), '#options' => array(PathautoManagerInterface::UPDATE_ACTION_NO_NEW => t('Do nothing. Leave the old alias intact.'), PathautoManagerInterface::UPDATE_ACTION_LEAVE => t('Create a new alias. Leave the existing alias functioning.'), PathautoManagerInterface::UPDATE_ACTION_DELETE => t('Create a new alias. Delete the old alias.')), '#description' => $description); $form['transliterate'] = array('#type' => 'checkbox', '#title' => t('Transliterate prior to creating alias'), '#default_value' => $config->get('transliterate'), '#description' => t('When a pattern includes certain characters (such as those with accents) should Pathauto attempt to transliterate them into the US-ASCII alphabet? Transliteration is handled by the Transliteration module.')); $form['reduce_ascii'] = array('#type' => 'checkbox', '#title' => t('Reduce strings to letters and numbers'), '#default_value' => $config->get('reduce_ascii'), '#description' => t('Filters the new alias to only letters and numbers found in the ASCII-96 set.')); $form['ignore_words'] = array('#type' => 'textarea', '#title' => t('Strings to Remove'), '#default_value' => $config->get('ignore_words'), '#description' => t('Words to strip out of the URL alias, separated by commas. Do not use this to remove punctuation.'), '#wysiwyg' => FALSE); $form['punctuation'] = array('#type' => 'fieldset', '#title' => t('Punctuation'), '#collapsible' => TRUE, '#collapsed' => TRUE, '#tree' => TRUE); $punctuation = \Drupal::service('pathauto.manager')->getPunctuationCharacters(); foreach ($punctuation as $name => $details) { $details['default'] = PathautoManagerInterface::PUNCTUATION_REMOVE; if ($details['value'] == $config->get('separator')) { $details['default'] = PathautoManagerInterface::PUNCTUATION_REPLACE; } $form['punctuation']['punctuation' . $name] = array('#type' => 'select', '#title' => $details['name'] . ' (<code>' . SafeMarkup::checkPlain($details['value']) . '</code>)', '#default_value' => $details['default'], '#options' => array(PathautoManagerInterface::PUNCTUATION_REMOVE => t('Remove'), PathautoManagerInterface::PUNCTUATION_REPLACE => t('Replace by separator'), PathautoManagerInterface::PUNCTUATION_DO_NOTHING => t('No action (do not replace)'))); } return parent::buildForm($form, $form_state); }
/** * Lists the feed items belonging to a feed. */ public function listItems(FeedInterface $feeds_feed, Request $request) { $processor = $feeds_feed->getType()->getProcessor(); $header = ['title' => $this->t('Label'), 'imported' => $this->t('Imported'), 'guid' => ['data' => $this->t('GUID'), 'class' => [RESPONSIVE_PRIORITY_LOW]], 'url' => ['data' => $this->t('URL'), 'class' => [RESPONSIVE_PRIORITY_LOW]]]; $build = []; $build['table'] = ['#type' => 'table', '#header' => $header, '#rows' => [], '#empty' => $this->t('There are no items yet.')]; // @todo Allow processors to create their own entity listings. if (!$processor instanceof EntityProcessorInterface) { return $build; } $entity_ids = \Drupal::entityQuery($processor->entityType())->condition('feeds_item.target_id', $feeds_feed->id())->pager(50)->sort('feeds_item.imported', 'DESC')->execute(); $storage = $this->entityManager()->getStorage($processor->entityType()); foreach ($storage->loadMultiple($entity_ids) as $entity) { $ago = \Drupal::service('date.formatter')->formatInterval(REQUEST_TIME - $entity->get('feeds_item')->imported); $row = []; // Entity link. $row[] = ['data' => $entity->link(Unicode::truncate($entity->label(), 75, TRUE, TRUE)), 'title' => $entity->label()]; // Imported ago. $row[] = $this->t('@time ago', ['@time' => $ago]); // Item GUID. $row[] = ['data' => SafeMarkup::checkPlain(Unicode::truncate($entity->get('feeds_item')->guid, 30, FALSE, TRUE)), 'title' => $entity->get('feeds_item')->guid]; // Item URL. $row[] = ['data' => SafeMarkup::checkPlain(Unicode::truncate($entity->get('feeds_item')->url, 30, FALSE, TRUE)), 'title' => $entity->get('feeds_item')->url]; $build['table']['#rows'][] = $row; } $build['pager'] = ['#type' => 'pager']; $build['#title'] = $this->t('%title items', ['%title' => $feeds_feed->label()]); return $build; }
/** * {@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'] .= SafeMarkup::checkPlain($this->t($group->label)); $element['#prefix'] .= '</span></' . $this->getSetting('label_element') . '>'; } $element['#suffix'] = '</' . $this->getSetting('element') . '>'; }
/** * 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' => Cache::PERMANENT), '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'); $expected_form = array('provider' => array('#type' => 'value', '#value' => 'block_test'), 'admin_label' => array('#type' => 'item', '#title' => t('Block description'), '#markup' => SafeMarkup::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' => Cache::PERMANENT, '#options' => $period)), '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 buildForm(array $form, FormStateInterface $form_state, $attributes = NULL) { $form['attributes']['#tree'] = TRUE; foreach ($attributes as $aid => $attribute) { $base_attr = uc_attribute_load($aid); if ($base_attr->options) { $form['attributes'][$aid]['options'] = array('#type' => 'table', '#header' => array($this->t('Options'), $this->t('Default'), $this->t('Cost'), $this->t('Price'), $this->t('Weight'), $this->t('List position')), '#caption' => '<h2>' . SafeMarkup::checkPlain($attribute->name) . '</h2>', '#empty' => $this->t('This attribute does not have any options.'), '#tabledrag' => array(array('action' => 'order', 'relationship' => 'sibling', 'group' => 'uc-attribute-option-table-ordering'))); $query = db_select('uc_attribute_options', 'ao')->fields('ao', array('aid', 'oid', 'name')); $query->leftJoin($this->optionTable, 'po', "ao.oid = po.oid AND po." . $this->idField . " = :id", array(':id' => $this->idValue)); $query->addField('ao', 'cost', 'default_cost'); $query->addField('ao', 'price', 'default_price'); $query->addField('ao', 'weight', 'default_weight'); $query->addField('ao', 'ordering', 'default_ordering'); $query->fields('po', array('cost', 'price', 'weight', 'ordering'))->addExpression('CASE WHEN po.ordering IS NULL THEN 1 ELSE 0 END', 'null_order'); $query->condition('aid', $aid)->orderBy('null_order')->orderBy('po.ordering')->orderBy('default_ordering')->orderBy('ao.name'); $result = $query->execute(); foreach ($result as $option) { $oid = $option->oid; $form['attributes'][$aid]['options'][$oid]['#attributes']['class'][] = 'draggable'; $form['attributes'][$aid]['options'][$oid]['select'] = array('#type' => 'checkbox', '#title' => SafeMarkup::checkPlain($option->name), '#default_value' => isset($attribute->options[$oid])); $form['attributes'][$aid]['options'][$oid]['default'] = array('#type' => 'radio', '#title' => $this->t('Default'), '#title_display' => 'invisible', '#parents' => array('attributes', $aid, 'default'), '#return_value' => $oid, '#default_value' => $attribute->default_option); $form['attributes'][$aid]['options'][$oid]['cost'] = array('#type' => 'uc_price', '#title' => $this->t('Cost'), '#title_display' => 'invisible', '#default_value' => is_null($option->cost) ? $option->default_cost : $option->cost, '#size' => 6, '#allow_negative' => TRUE); $form['attributes'][$aid]['options'][$oid]['price'] = array('#type' => 'uc_price', '#title' => $this->t('Price'), '#title_display' => 'invisible', '#default_value' => is_null($option->price) ? $option->default_price : $option->price, '#size' => 6, '#allow_negative' => TRUE); $form['attributes'][$aid]['options'][$oid]['weight'] = array('#type' => 'textfield', '#title' => $this->t('Weight'), '#title_display' => 'invisible', '#default_value' => is_null($option->weight) ? $option->default_weight : $option->weight, '#size' => 5); $form['attributes'][$aid]['options'][$oid]['ordering'] = array('#type' => 'weight', '#title' => $this->t('List position'), '#title_display' => 'invisible', '#delta' => 50, '#default_value' => is_null($option->ordering) ? $option->default_ordering : $option->ordering, '#attributes' => array('class' => array('uc-attribute-option-table-ordering'))); } } } $form['actions'] = array('#type' => 'actions'); $form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('Save changes')); 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 SafeMarkup::checkPlain($this->name) . '="' . $value . '"'; } }
/** * {@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 SafeMarkup::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')), 'required' => 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; }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state, ServerInterface $search_api_server = NULL) { $form['#title'] = $this->t('List of configuration files found'); try { // Retrieve the list of available files. $files_list = SearchApiSolrUtility::getServerFiles($search_api_server); if (empty($files_list)) { $form['info']['#markup'] = $this->t('No files found.'); return $form; } $form['files_tabs'] = array('#type' => 'vertical_tabs'); // Generate a fieldset for each file. foreach ($files_list as $file_name => $file_info) { $file_date = format_date(strtotime($file_info['modified'])); $escaped_file_name = SafeMarkup::checkPlain($file_name); $form['files'][$file_name] = array('#type' => 'details', '#title' => $escaped_file_name, '#group' => 'files_tabs'); $data = '<h3>' . $escaped_file_name . '</h3>'; $data .= '<p><em>' . $this->t('Last modified: @time.', array('@time' => $file_date)) . '</em></p>'; if ($file_info['size'] > 0) { $file_data = $search_api_server->getBackend()->getFile($file_name); $data .= '<pre><code>' . SafeMarkup::checkPlain($file_data->getBody()) . '</code></pre>'; } else { $data .= '<p><em>' . $this->t('The file is empty.') . '</em></p>'; } $form['files'][$file_name]['data']['#markup'] = $data; } } catch (SearchApiException $e) { watchdog_exception('search_api_solr', $e, '%type while retrieving config files of Solr server @server: !message in %function (line %line of %file).', array('@server' => $search_api_server->label())); $form['info']['#markup'] = $this->t('An error occured while trying to load the list of files.'); } return $form; }
/** * 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', SafeMarkup::checkPlain('test <strong>rid 2</strong>')), $titles); }
/** * {@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' => SafeMarkup::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; }
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.entity_id as uid, u.roles_target_id as rid FROM {user__roles} u WHERE u.entity_id IN ( :uids[] ) AND u.roles_target_id IN ( :rids[] )', array(':uids[]' => $uids, ':rids[]' => array_keys($roles))); foreach ($result as $role) { $this->items[$role->uid][$role->rid]['role'] = SafeMarkup::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); } } }
/** * 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'][] = SafeMarkup::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']; } }
/** * Tests tablesort_init(). */ function testTableSortInit() { // Test simple table headers. $headers = array('foo', 'bar', 'baz'); // Reset $request->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' => SafeMarkup::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' => SafeMarkup::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' => SafeMarkup::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' => SafeMarkup::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' => SafeMarkup::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' => SafeMarkup::checkPlain(var_export($ts, TRUE))))); $this->assertEqual($ts, $expected_ts, 'Complex table headers plus $_GET parameters sorted correctly.'); }
/** * Test pathauto_cleanstring(). */ public function testCleanString() { $config = $this->config('pathauto.settings'); $tests = array(); $config->set('ignore_words', ', in, is,that, the , this, with, '); $config->set('max_component_length', 35); $config->set('transliterate', TRUE); $config->save(); \Drupal::service('pathauto.manager')->resetCaches(); // Test the 'ignored words' removal. $tests['this'] = 'this'; $tests['this with that'] = 'this-with-that'; $tests['this thing with that thing'] = 'thing-thing'; // Test length truncation and duplicate separator removal. $tests[' - Pathauto is the greatest - module ever in Drupal hiarticle - '] = 'pathauto-greatest-module-ever'; // Test that HTML tags are removed. $tests['This <span class="text">text</span> has <br /><a href="http://example.com"><strong>HTML tags</strong></a>.'] = 'text-has-html-tags'; $tests[(string) SafeMarkup::checkPlain('This <span class="text">text</span> has <br /><a href="http://example.com"><strong>HTML tags</strong></a>.')] = 'text-has-html-tags'; // Transliteration. $tests['ľščťžýáíéňô'] = 'lsctzyaieno'; foreach ($tests as $input => $expected) { $output = \Drupal::service('pathauto.manager')->cleanString($input); $this->assertEqual($output, $expected, t("Drupal::service('pathauto.manager')->cleanString('@input') expected '@expected', actual '@output'", array('@input' => $input, '@expected' => $expected, '@output' => $output))); } }
/** * 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] = SafeMarkup::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.'); }
/** * 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 slash, then run it through // Url::fromUri('base:')->toString() to get the correct 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'] === SafeMarkup::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()))); }
/** * 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->randomMachineName(32), 'summary' => $this->randomMachineName(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]'] = SafeMarkup::checkPlain($node->getTitle()); $tests['[node:body]'] = $node->body->processed; $tests['[node:summary]'] = $node->body->summary_processed; $tests['[node:langcode]'] = SafeMarkup::checkPlain($node->language()->getId()); $tests['[node:url]'] = $node->url('canonical', $url_options); $tests['[node:edit-url]'] = $node->url('edit-form', $url_options); $tests['[node:author]'] = SafeMarkup::checkPlain($account->getUsername()); $tests['[node:author:uid]'] = $node->getOwnerId(); $tests['[node:author:name]'] = SafeMarkup::checkPlain($account->getUsername()); $tests['[node:created:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($node->getCreatedTime(), array('langcode' => $this->interfaceLanguage->getId())); $tests['[node:changed:since]'] = \Drupal::service('date.formatter')->formatTimeDiffSince($node->getChangedTime(), array('langcode' => $this->interfaceLanguage->getId())); // 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->getId())); $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()->getId(); $tests['[node:author:name]'] = $account->getUsername(); foreach ($tests as $input => $expected) { $output = $this->tokenService->replace($input, array('node' => $node), array('langcode' => $this->interfaceLanguage->getId(), '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->randomMachineName(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))); } }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $form['help'] = array('#markup' => t('By default, only the "Free order" payment method is listed here. To see additional payment methods you must <a href="@install">install additional modules</a>. The "Payment Method Pack" module that comes with Ubercart provides "Check" and "COD" payment methods. The "Credit Card" module that comes with Ubercart provides a credit card payment method, although you will need an additional module to provide a payment gateway for your credit card. For more information about payment methods and settings please read the <a href="@doc">Ubercart Documentation</a>.', ['@install' => Url::fromRoute('system.modules_list')->toString(), '@doc' => Url::fromUri('http://www.drupal.org/documentation/modules/ubercart')->toString()])); $form['methods'] = array('#type' => 'table', '#header' => array(t('Payment method'), t('List position'), t('Operations')), '#tabledrag' => array(array('action' => 'order', 'relationship' => 'sibling', 'group' => 'uc-payment-method-weight'))); foreach ($this->paymentMethodManager->getDefinitions() as $id => $method) { $form['methods'][$id]['#attributes']['class'][] = 'draggable'; $form['methods'][$id]['status'] = array('#type' => 'checkbox', '#title' => SafeMarkup::checkPlain($method['name']), '#default_value' => $method['checkout']); $form['methods'][$id]['weight'] = array('#type' => 'weight', '#title' => t('Weight for @title', array('@title' => $method['name'])), '#title_display' => 'invisible', '#default_value' => $method['weight'], '#attributes' => array('class' => array('uc-payment-method-weight'))); if (empty($method['no_gateway'])) { $gateways = _uc_payment_gateway_list($id, TRUE); $options = array(); foreach ($gateways as $gateway_id => $gateway) { $options[$gateway_id] = $gateway['title']; } if ($options) { $form['methods'][$id]['status']['#title'] .= ' (' . t('includes %gateways', array('%gateways' => implode(', ', $options))) . ')'; } } $links = array(); if (!empty($method['settings_form'])) { $links['settings'] = array('title' => t('Settings'), 'url' => Url::fromRoute('uc_payment.method_settings', ['method' => $id])); } // $links['conditions'] = array( // 'title' => t('Conditions'), // 'url' => Url::fromRoute('admin/store/config/payment/manage/uc_payment_method_', ['method' => $id]), // ); $form['methods'][$id]['settings'] = array('#type' => 'operations', '#links' => $links); } return parent::buildForm($form, $form_state); }
/** * {@inheritdoc} */ public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) { /* @var $instance \Drupal\mailchimp_lists\Plugin\Field\FieldType\MailchimpListsSubscription */ $instance = $items[0]; $subscribe_default = $instance->getSubscribe(); $email = NULL; if (!empty($instance->getEntity())) { $email = mailchimp_lists_load_email($instance, $instance->getEntity(), FALSE); if ($email) { $subscribe_default = mailchimp_is_subscribed($instance->getFieldDefinition()->getSetting('mc_list_id'), $email); } } $element += array('#title' => SafeMarkup::checkPlain($element['#title']), '#type' => 'fieldset'); $element['subscribe'] = array('#title' => t('Subscribe'), '#type' => 'checkbox', '#default_value' => $subscribe_default ? TRUE : $this->fieldDefinition->isRequired(), '#required' => $this->fieldDefinition->isRequired(), '#disabled' => $this->fieldDefinition->isRequired()); $form_id = $form_state->getFormObject()->getFormId(); if ($this->fieldDefinition->getSetting('show_interest_groups') || $form_id == 'field_ui_field_edit_form') { $mc_list = mailchimp_get_list($instance->getFieldDefinition()->getSetting('mc_list_id')); $element['interest_groups'] = array('#type' => 'fieldset', '#title' => SafeMarkup::checkPlain($instance->getFieldDefinition()->getSetting('interest_groups_title')), '#weight' => 100, '#states' => array('invisible' => array(':input[name="' . $instance->getFieldDefinition()->getName() . '[0][value][subscribe]"]' => array('checked' => FALSE)))); if ($form_id == 'field_ui_field_edit_form') { $element['interest_groups']['#states']['invisible'] = array(':input[name="field[settings][show_interest_groups]"]' => array('checked' => FALSE)); } $groups_default = $instance->getInterestGroups(); if ($groups_default == NULL) { $groups_default = array(); } if ($mc_list['stats']['group_count']) { $element['interest_groups'] += mailchimp_interest_groups_form_elements($mc_list, $groups_default, $email); } } return array('value' => $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'] = SafeMarkup::checkPlain($form['#build_id_old']); } return $form; }
/** * Tests inline templates. */ public function testInlineTemplate() { /** @var \Drupal\Core\Render\RendererInterface $renderer */ $renderer = $this->container->get('renderer'); /** @var \Drupal\Core\Template\TwigEnvironment $environment */ $environment = \Drupal::service('twig'); $this->assertEqual($environment->renderInline('test-no-context'), 'test-no-context'); $this->assertEqual($environment->renderInline('test-with-context {{ llama }}', array('llama' => 'muuh')), 'test-with-context muuh'); $element = array(); $unsafe_string = '<script>alert(\'Danger! High voltage!\');</script>'; $element['test'] = array('#type' => 'inline_template', '#template' => 'test-with-context <label>{{ unsafe_content }}</label>', '#context' => array('unsafe_content' => $unsafe_string)); $this->assertEqual($renderer->renderRoot($element), 'test-with-context <label>' . SafeMarkup::checkPlain($unsafe_string) . '</label>'); // Enable twig_auto_reload and twig_debug. $settings = Settings::getAll(); $settings['twig_debug'] = TRUE; $settings['twig_auto_reload'] = TRUE; new Settings($settings); $this->container = $this->kernel->rebuildContainer(); \Drupal::setContainer($this->container); $element = array(); $element['test'] = array('#type' => 'inline_template', '#template' => 'test-with-context {{ llama }}', '#context' => array('llama' => 'muuh')); $element_copy = $element; // Render it twice so that twig caching is triggered. $this->assertEqual($renderer->renderRoot($element), 'test-with-context muuh'); $this->assertEqual($renderer->renderRoot($element_copy), 'test-with-context muuh'); }
/** * {@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' => SafeMarkup::checkPlain($label)); } $elements[$delta]['#cache']['tags'] = $entity->getCacheTags(); } return $elements; }
/** * {@inheritdoc} */ 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">' . SafeMarkup::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 buildRow(EntityInterface $entity) { $row['label'] = $this->getLabel($entity); $row['color'] = ['#markup' => SafeMarkup::checkPlain($entity->getColor())]; $row['point_value'] = ['#markup' => SafeMarkup::checkPlain($entity->getPointValue())]; return $row + parent::buildRow($entity); }
/** * {@inheritdoc} */ public function buildRow(EntityInterface $entity) { $row = array(); $row['label']['data'] = array('#type' => 'link', '#title' => SafeMarkup::checkPlain($entity->label()), '#url' => $entity->urlInfo()); $row['type'] = SafeMarkup::checkPlain($entity->get('type')->entity->label()); $row['changed'] = $this->dateFormatter->format($entity->get('changed')->value, 'short'); return $row + parent::buildRow($entity); }
/** * Override the behavior of title(). Get the name of the vocabulary. */ function title() { $vocabulary = $this->vocabularyStorage->load($this->argument); if ($vocabulary) { return SafeMarkup::checkPlain($vocabulary->label()); } return $this->t('No vocabulary'); }
/** * Builds an individual term item for the term item list depending on the formatter. * * @param \Drupal\taxonomy\Entity\Term $term * @return string */ private function buildTermListItem(Term $term, $formatter) { if ($formatter === 'linked') { $link_url = Url::fromRoute('entity.taxonomy_term.canonical', array('taxonomy_term' => $term->id())); return \Drupal::l($term->label(), $link_url); } return SafeMarkup::checkPlain($term->label()); }
/** * Generate the output appropriate for one field item. * * @param \Drupal\Core\Field\FieldItemInterface $item * One field item. * * @return string * The textual output generated. */ protected function viewValue(FieldItemInterface $item) { if ($this->getSetting('sanitized')) { return nl2br(SafeMarkup::checkPlain($item->value)); } else { return nl2br($item->value); } }
/** * {@inheritdoc} */ public function buildRow(EntityInterface $entity) { $row = array(); $row['date']['data'] = $entity->get('activity_date')->view(array('label' => 'hidden')); $row['title']['data'] = array('#type' => 'link', '#title' => SafeMarkup::checkPlain($entity->label()), '#url' => $entity->urlInfo()); $row['type'] = $entity->get('type')->entity->label(); return $row + parent::buildRow($entity); }