/** * {@inheritdoc} */ public function buildRow(EntityInterface $entity) { /* @var $entity \Drupal\commerce_order\Entity\Order */ $orderType = OrderType::load($entity->bundle()); $row = ['order_id' => $entity->id(), 'type' => $orderType->label(), 'customer' => ['data' => ['#theme' => 'username', '#account' => $entity->getOwner()]], 'state' => $entity->getState()->getLabel(), 'created' => $this->dateFormatter->format($entity->getCreatedTime(), 'short')]; return $row + parent::buildRow($entity); }
/** * {@inheritdoc} */ public function getQuestion() { if ($this->entityRevision instanceof TimestampedRevisionInterface) { return t('Are you sure you want to delete the revision from %revision-date?', ['%revision-date' => $this->dateFormatter->format($this->entityRevision->getRevisionCreationTime())]); } else { return t('Are you sure you want to delete to the revision'); } }
/** * {@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); }
/** * {@inheritdoc} */ public function form(array $form, FormStateInterface $form_state) { $form['label'] = array('#type' => 'textfield', '#title' => 'Name', '#maxlength' => 100, '#description' => t('Name of the date format'), '#default_value' => $this->entity->label()); $form['id'] = array('#type' => 'machine_name', '#description' => t('A unique machine-readable name. Can only contain lowercase letters, numbers, and underscores.'), '#disabled' => !$this->entity->isNew(), '#default_value' => $this->entity->id(), '#machine_name' => array('exists' => array($this, 'exists'), 'replace_pattern' => '([^a-z0-9_]+)|(^custom$)', 'error' => $this->t('The machine-readable name must be unique, and can only contain lowercase letters, numbers, and underscores. Additionally, it can not be the reserved word "custom".'))); $form['date_format_pattern'] = array('#type' => 'textfield', '#title' => t('Format string'), '#maxlength' => 100, '#description' => $this->t('A user-defined date format. See the <a href="@url">PHP manual</a> for available options.', array('@url' => 'http://php.net/manual/function.date.php')), '#required' => TRUE, '#attributes' => ['data-drupal-date-formatter' => 'source'], '#field_suffix' => ' <small class="js-hide" data-drupal-date-formatter="preview">' . $this->t('Displayed as %date_format', ['%date_format' => '']) . '</small>'); $form['langcode'] = array('#type' => 'language_select', '#title' => t('Language'), '#languages' => LanguageInterface::STATE_ALL, '#default_value' => $this->entity->language()->getId()); $form['#attached']['drupalSettings']['dateFormats'] = $this->dateFormatter->getSampleDateFormats(); $form['#attached']['library'][] = 'system/drupal.system.date'; return parent::form($form, $form_state); }
/** * @covers ::preRender */ public function testPreRender() { $payment_status_created = mt_rand(); $payment_status = $this->getMock(PaymentStatusInterface::class); $payment_status->expects($this->atLeastOnce())->method('getCreated')->willReturn($payment_status_created); $this->dateFormatter->expects($this->once())->method('format')->with($payment_status_created); $element = array('#payment_statuses' => [$payment_status]); $build = $this->sut->preRender($element); $this->assertSame('table', $build['table']['#type']); }
/** * {@inheritdoc} */ public function buildRow(EntityInterface $entity) { if ($entity->isLocked()) { $row['id'] = $this->t('@entity_id (locked)', array('@entity_id' => $entity->id())); } else { $row['id'] = $entity->id(); } $row['label'] = $this->getLabel($entity); $row['pattern'] = $this->dateFormatter->format(REQUEST_TIME, $entity->id()); return $row + parent::buildRow($entity); }
/** * {@inheritdoc} */ public function buildRow(EntityInterface $entity) { $uri = $entity->urlInfo(); $options = $uri->getOptions(); $uri->setOptions($options); $row['title']['data'] = ['#type' => 'link', '#title' => $entity->label(), '#url' => $uri]; $row['type'] = SafeMarkup::checkPlain($entity->getType()->label()); $row['author']['data'] = ['#theme' => 'username', '#account' => $entity->getOwner()]; $row['status'] = $entity->isActive() ? $this->t('active') : $this->t('not active'); $row['imported'] = $this->dateFormatter->format($entity->getImportedTime(), 'short'); $row['operations']['data'] = $this->buildOperations($entity); return $row + parent::buildRow($entity); }
/** * {@inheritdoc} */ public function viewElements(FieldItemListInterface $items) { $elements = array(); foreach ($items as $delta => $item) { if ($item->value) { $updated = $this->t('@time ago', array('@time' => $this->dateFormatter->formatInterval(REQUEST_TIME - $item->value))); } else { $updated = $this->t('never'); } $elements[$delta] = array('#markup' => $updated); } return $elements; }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $config = $this->config('system.cron'); $form['description'] = array('#markup' => '<p>' . t('Cron takes care of running periodic tasks like checking for updates and indexing content for search.') . '</p>'); $form['run'] = array('#type' => 'submit', '#value' => t('Run cron'), '#submit' => array(array($this, 'submitCron'))); $status = '<p>' . t('Last run: %cron-last ago.', array('%cron-last' => $this->dateFormatter->formatInterval(REQUEST_TIME - $this->state->get('system.cron_last')))) . '</p>'; $form['status'] = array('#markup' => $status); $form['cron_url'] = array('#markup' => '<p>' . t('To run cron from outside the site, go to <a href="!cron">!cron</a>', array('!cron' => url('cron/' . $this->state->get('system.cron_key'), array('absolute' => TRUE)))) . '</p>'); $form['cron'] = array('#title' => t('Cron settings'), '#type' => 'details', '#open' => TRUE); $options = array(3600, 10800, 21600, 43200, 86400, 604800); $form['cron']['cron_safe_threshold'] = array('#type' => 'select', '#title' => t('Run cron every'), '#description' => t('More information about setting up scheduled tasks can be found by <a href="@url">reading the cron tutorial on drupal.org</a>.', array('@url' => url('http://drupal.org/cron'))), '#default_value' => $config->get('threshold.autorun'), '#options' => array(0 => t('Never')) + array_map(array($this->dateFormatter, 'formatInterval'), array_combine($options, $options))); return parent::buildForm($form, $form_state); }
/** * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state) { $form['num'] = array('#type' => 'number', '#title' => $this->t('How many users would you like to generate?'), '#default_value' => $this->getSetting('num'), '#required' => TRUE, '#min' => 0); $form['kill'] = array('#type' => 'checkbox', '#title' => $this->t('Delete all users (except user id 1) before generating new users.'), '#default_value' => $this->getSetting('kill')); $options = user_role_names(TRUE); unset($options[DRUPAL_AUTHENTICATED_RID]); $form['roles'] = array('#type' => 'checkboxes', '#title' => $this->t('Which roles should the users receive?'), '#description' => $this->t('Users always receive the <em>authenticated user</em> role.'), '#options' => $options); $form['pass'] = array('#type' => 'textfield', '#title' => $this->t('Password to be set'), '#default_value' => $this->getSetting('pass'), '#size' => 32, '#description' => $this->t('Leave this field empty if you do not need to set a password')); $options = array(1 => $this->t('Now')); foreach (array(3600, 86400, 604800, 2592000, 31536000) as $interval) { $options[$interval] = $this->dateFormatter->formatInterval($interval, 1) . ' ' . $this->t('ago'); } $form['time_range'] = array('#type' => 'select', '#title' => $this->t('How old should user accounts be?'), '#description' => $this->t('User ages will be distributed randomly from the current time, back to the selected time.'), '#options' => $options, '#default_value' => 604800); return $form; }
/** * @covers ::buildRow * * @dataProvider providerTestBuildRow * * @depends testBuildOperations */ function testBuildRow($payment_currency_exists) { $payment_changed_time = time(); $payment_changed_time_formatted = $this->randomMachineName(); $payment_currency_code = $this->randomMachineName(); $payment_amount = mt_rand(); $payment_amount_formatted = $this->randomMachineName(); $payment_status_definition = array('label' => $this->randomMachineName()); $payment_status = $this->getMock(PaymentStatusInterface::class); $payment_status->expects($this->any())->method('getPluginDefinition')->willReturn($payment_status_definition); $owner = $this->getMock(UserInterface::class); $payment_method_label = $this->randomMachineName(); $payment_method_definition = ['label' => $payment_method_label]; $payment_method = $this->getMock(PaymentMethodInterface::class); $payment_method->expects($this->atLeastOnce())->method('getPluginDefinition')->willReturn($payment_method_definition); $payment = $this->getMock(PaymentInterface::class); $payment->expects($this->any())->method('getAmount')->willReturn($payment_amount); $payment->expects($this->any())->method('getChangedTime')->willReturn($payment_changed_time); $payment->expects($this->any())->method('getCurrencyCode')->willReturn($payment_currency_code); $payment->expects($this->any())->method('getOwner')->willReturn($owner); $payment->expects($this->any())->method('getPaymentMethod')->willReturn($payment_method); $payment->expects($this->any())->method('getPaymentStatus')->willReturn($payment_status); $currency = $this->getMock(CurrencyInterface::class); $currency->expects($this->once())->method('formatAmount')->with($payment_amount)->willReturn($payment_amount_formatted); $map = array(array($payment_currency_code, $payment_currency_exists ? $currency : NULL), array('XXX', $payment_currency_exists ? NULL : $currency)); $this->currencyStorage->expects($this->atLeastOnce())->method('load')->willReturnMap($map); $this->dateFormatter->expects($this->once())->method('format')->with($payment_changed_time)->willReturn($payment_changed_time_formatted); $this->moduleHandler->expects($this->any())->method('invokeAll')->willReturn([]); $build = $this->sut->buildRow($payment); unset($build['data']['operations']['data']['#attached']); $expected_build = array('data' => array('updated' => $payment_changed_time_formatted, 'status' => $payment_status_definition['label'], 'amount' => $payment_amount_formatted, 'payment_method' => $payment_method_label, 'owner' => array('data' => array('#theme' => 'username', '#account' => $owner)), 'operations' => array('data' => array('#type' => 'operations', '#links' => [])))); $this->assertSame($expected_build, $build); }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $index = $this->entity; // Do not allow the form to be cached. See // \Drupal\views_ui\ViewEditForm::form(). $form_state->disableCache(); if ($index instanceof UnsavedConfigurationInterface && $index->hasChanges()) { if ($index->isLocked()) { $form['#disabled'] = TRUE; $username = array('#theme' => 'username', '#account' => $index->getLockOwner($this->entityTypeManager)); $lock_message_substitutions = array('@user' => $this->getRenderer()->render($username), '@age' => $this->dateFormatter->formatTimeDiffSince($index->getLastUpdated()), ':url' => $index->toUrl('break-lock-form')->toString()); $form['locked'] = array('#type' => 'container', '#attributes' => array('class' => array('index-locked', 'messages', 'messages--warning')), '#children' => $this->t('This index is being edited by user @user, and is therefore locked from editing by others. This lock is @age old. Click here to <a href=":url">break this lock</a>.', $lock_message_substitutions), '#weight' => -10); } else { $form['changed'] = array('#type' => 'container', '#attributes' => array('class' => array('index-changed', 'messages', 'messages--warning')), '#children' => $this->t('You have unsaved changes.'), '#weight' => -10); } } // Set an appropriate page title. $form['#title'] = $this->t('Manage fields for search index %label', array('%label' => $index->label())); $form['#tree'] = TRUE; $form['description']['#markup'] = $this->t('<p>The data type of a field determines how it can be used for searching and filtering. The boost is used to give additional weight to certain fields, e.g. titles or tags.</p> <p>Whether detailed field types are supported depends on the type of server this index resides on. In any case, fields of type "Fulltext" will always be fulltext-searchable.</p>'); if ($index->hasValidServer()) { $form['description']['#markup'] .= '<p>' . $this->t('Check the <a href=":server-url">' . "server's</a> backend class description for details.", array(':server-url' => $index->getServerInstance()->toUrl('canonical')->toString())) . '</p>'; } if ($fields = $index->getFieldsByDatasource(NULL)) { $form['_general'] = $this->buildFieldsTable($fields); $form['_general']['#title'] = $this->t('General'); } foreach ($index->getDatasources() as $datasource_id => $datasource) { $fields = $index->getFieldsByDatasource($datasource_id); $form[$datasource_id] = $this->buildFieldsTable($fields); $form[$datasource_id]['#title'] = $datasource->label(); } $form['actions'] = $this->actionsElement($form, $form_state); return $form; }
/** * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state) { $bundles = $this->mediaBundleStorage->loadMultiple(); if (empty($bundles)) { $create_url = $this->urlGenerator->generateFromRoute('media.bundle_add'); $this->setMessage($this->t('You do not have any media bundles that can be generated. <a href="@create-bundle">Go create a new media bundle</a>', ['@create-bundle' => $create_url]), 'error', FALSE); return []; } $options = []; foreach ($bundles as $bundle) { $options[$bundle->id()] = ['bundle' => ['#markup' => $bundle->label()]]; } $form['media_bundles'] = ['#type' => 'tableselect', '#header' => ['bundle' => $this->t('Media bundle')], '#options' => $options]; $form['kill'] = ['#type' => 'checkbox', '#title' => $this->t('<strong>Delete all media</strong> in these bundles before generating new media.'), '#default_value' => $this->getSetting('kill')]; $form['num'] = ['#type' => 'number', '#title' => $this->t('How many media items would you like to generate?'), '#default_value' => $this->getSetting('num'), '#required' => TRUE, '#min' => 0]; $options = [1 => $this->t('Now')]; foreach ([3600, 86400, 604800, 2592000, 31536000] as $interval) { $options[$interval] = $this->dateFormatter->formatInterval($interval, 1) . ' ' . $this->t('ago'); } $form['time_range'] = ['#type' => 'select', '#title' => $this->t('How far back in time should the media be dated?'), '#description' => $this->t('Media creation dates will be distributed randomly from the current time, back to the selected time.'), '#options' => $options, '#default_value' => 604800]; $form['name_length'] = ['#type' => 'number', '#title' => $this->t('Maximum number of words in names'), '#default_value' => $this->getSetting('name_length'), '#required' => TRUE, '#min' => 1, '#max' => 255]; $options = []; // We always need a language. $languages = $this->languageManager->getLanguages(LanguageInterface::STATE_ALL); foreach ($languages as $langcode => $language) { $options[$langcode] = $language->getName(); } $form['add_language'] = ['#type' => 'select', '#title' => $this->t('Set language on media'), '#multiple' => TRUE, '#description' => $this->t('Requires locale.module'), '#options' => $options, '#default_value' => [$this->languageManager->getDefaultLanguage()->getId()]]; $form['#redirect'] = FALSE; return $form; }
/** * Index. * * @return array * Render array with all the entries. */ public function index() { $output = ['#cache' => ['max-age' => 0]]; // This is going to be reused at two places: once for the TableSortExtender, // and once for the table header itself. $header = [['data' => $this->t('Created'), 'field' => 'p.created'], ['data' => $this->t('Changed'), 'field' => 'p.changed'], ['data' => $this->t('Name'), 'field' => 'p.name'], ['data' => $this->t('Phone'), 'field' => 'p.phone'], ['data' => $this->t('Operations'), 'colspan' => '2']]; $query = $this->connection->select('phonebook', 'p')->extend('Drupal\\Core\\Database\\Query\\TableSortExtender')->extend('Drupal\\Core\\Database\\Query\\PagerSelectExtender'); $query->fields('p'); $result = $query->orderByHeader($header)->limit(25)->execute(); $output['table'] = ['#type' => 'table', '#header' => $header, '#empty' => $this->t('No entries found.')]; foreach ($result as $row) { $output['table'][] = [['data' => ['#markup' => $this->date_formatter->format($row->created)]], ['data' => ['#markup' => $this->date_formatter->formatTimeDiffSince($row->changed)]], ['data' => ['#markup' => $row->name]], ['data' => ['#markup' => $row->phone]], ['data' => ['#markup' => $this->l($this->t('edit'), new Url('d8phonebook.edit', ['phonebook' => $row->pbid]))]], ['data' => ['#markup' => $this->l($this->t('delete'), new Url('d8phonebook.delete', ['phonebook' => $row->pbid], ['query' => ['token' => $this->csrf_token_generator->get('phonebook/' . $row->pbid . '/delete')]]))]]]; } $output['pager'] = array('#type' => 'pager'); return $output; }
/** * Displays the aggregator administration page. * * @return array * A render array as expected by drupal_render(). */ public function adminOverview() { $entity_manager = $this->entityManager(); $feeds = $entity_manager->getStorage('aggregator_feed')->loadMultiple(); $header = array($this->t('Title'), $this->t('Items'), $this->t('Last update'), $this->t('Next update'), $this->t('Operations')); $rows = array(); /** @var \Drupal\aggregator\FeedInterface[] $feeds */ foreach ($feeds as $feed) { $row = array(); $row[] = $feed->link(); $row[] = $this->formatPlural($entity_manager->getStorage('aggregator_item')->getItemCount($feed), '1 item', '@count items'); $last_checked = $feed->getLastCheckedTime(); $refresh_rate = $feed->getRefreshRate(); $row[] = $last_checked ? $this->t('@time ago', array('@time' => $this->dateFormatter->formatInterval(REQUEST_TIME - $last_checked))) : $this->t('never'); if (!$last_checked && $refresh_rate) { $next_update = $this->t('imminently'); } elseif ($last_checked && $refresh_rate) { $next_update = $next = $this->t('%time left', array('%time' => $this->dateFormatter->formatInterval($last_checked + $refresh_rate - REQUEST_TIME))); } else { $next_update = $this->t('never'); } $row[] = $next_update; $links['edit'] = ['title' => $this->t('Edit'), 'url' => Url::fromRoute('entity.aggregator_feed.edit_form', ['aggregator_feed' => $feed->id()])]; $links['delete'] = array('title' => $this->t('Delete'), 'url' => Url::fromRoute('entity.aggregator_feed.delete_form', ['aggregator_feed' => $feed->id()])); $links['delete_items'] = array('title' => $this->t('Delete items'), 'url' => Url::fromRoute('aggregator.feed_items_delete', ['aggregator_feed' => $feed->id()])); $links['update'] = array('title' => $this->t('Update items'), 'url' => Url::fromRoute('aggregator.feed_refresh', ['aggregator_feed' => $feed->id()])); $row[] = array('data' => array('#type' => 'operations', '#links' => $links)); $rows[] = $row; } $build['feeds'] = array('#prefix' => '<h3>' . $this->t('Feed overview') . '</h3>', '#type' => 'table', '#header' => $header, '#rows' => $rows, '#empty' => $this->t('No feeds available. <a href="@link">Add feed</a>.', array('@link' => $this->url('aggregator.feed_add')))); return $build; }
/** * Generates the list page. * * @param \Symfony\Component\HttpFoundation\Request $request * * @return array */ public function listAction(Request $request) { $limit = $request->get('limit', 10); $this->profiler->disable(); $ip = $request->query->get('ip'); $method = $request->query->get('method'); $url = $request->query->get('url'); $profiles = $this->profiler->find($ip, $url, $limit, $method, '', ''); $rows = []; if (count($profiles)) { foreach ($profiles as $profile) { $row = []; $row[] = $this->l($profile['token'], new Url('webprofiler.dashboard', ['profile' => $profile['token']])); $row[] = $profile['ip']; $row[] = $profile['method']; $row[] = $profile['url']; $row[] = $this->date->format($profile['time']); $rows[] = $row; } } else { $rows[] = [['data' => $this->t('No profiles found'), 'colspan' => 6]]; } $build = []; $storage_id = $this->config('webprofiler.config')->get('storage'); $storage = $this->storageManager->getStorage($storage_id); $build['resume'] = ['#type' => 'inline_template', '#template' => '<p>{{ message }}</p>', '#context' => ['message' => $this->t('Profiles stored with %storage service.', ['%storage' => $storage['title']])]]; $build['filters'] = $this->formBuilder()->getForm('Drupal\\webprofiler\\Form\\ProfilesFilterForm'); $build['table'] = ['#type' => 'table', '#rows' => $rows, '#header' => [$this->t('Token'), ['data' => $this->t('Ip'), 'class' => [RESPONSIVE_PRIORITY_LOW]], ['data' => $this->t('Method'), 'class' => [RESPONSIVE_PRIORITY_LOW]], $this->t('Url'), ['data' => $this->t('Time'), 'class' => [RESPONSIVE_PRIORITY_MEDIUM]]], '#sticky' => TRUE]; return $build; }
/** * {@inheritdoc} */ public function buildConfigurationForm(array $form, FormStateInterface $form_state) { $processors = $this->configuration['processors']; $info = $this->getPluginDefinition(); $counts = array(3, 5, 10, 15, 20, 25); $items = array_map(function ($count) { return $this->dateFormatter->formatInterval($count, '1 item', '@count items'); }, array_combine($counts, $counts)); $intervals = array(3600, 10800, 21600, 32400, 43200, 86400, 172800, 259200, 604800, 1209600, 2419200, 4838400, 9676800); $period = array_map(array($this->dateFormatter, 'formatInterval'), array_combine($intervals, $intervals)); $period[AGGREGATOR_CLEAR_NEVER] = t('Never'); $form['processors'][$info['id']] = array(); // Only wrap into details if there is a basic configuration. if (isset($form['basic_conf'])) { $form['processors'][$info['id']] = array('#type' => 'details', '#title' => t('Default processor settings'), '#description' => $info['description'], '#open' => in_array($info['id'], $processors)); } $form['processors'][$info['id']]['aggregator_summary_items'] = array('#type' => 'select', '#title' => t('Number of items shown in listing pages'), '#default_value' => $this->configuration['source']['list_max'], '#empty_value' => 0, '#options' => $items); $form['processors'][$info['id']]['aggregator_clear'] = array('#type' => 'select', '#title' => t('Discard items older than'), '#default_value' => $this->configuration['items']['expire'], '#options' => $period, '#description' => t('Requires a correctly configured <a href="@cron">cron maintenance task</a>.', array('@cron' => $this->url('system.status')))); $lengths = array(0, 200, 400, 600, 800, 1000, 1200, 1400, 1600, 1800, 2000); $options = array_map(function ($length) { return $length == 0 ? t('Unlimited') : format_plural($length, '1 character', '@count characters'); }, array_combine($lengths, $lengths)); $form['processors'][$info['id']]['aggregator_teaser_length'] = array('#type' => 'select', '#title' => t('Length of trimmed description'), '#default_value' => $this->configuration['items']['teaser_length'], '#options' => $options, '#description' => t('The maximum number of characters used in the trimmed version of content.')); return $form; }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $index = $this->entity; // Do not allow the form to be cached. See // \Drupal\views_ui\ViewEditForm::form(). $form_state->disableCache(); if ($index instanceof UnsavedConfigurationInterface && $index->hasChanges()) { if ($index->isLocked()) { $form['#disabled'] = TRUE; $username = array('#theme' => 'username', '#account' => $index->getLockOwner($this->entityTypeManager)); $lock_message_substitutions = array('@user' => $this->getRenderer()->render($username), '@age' => $this->dateFormatter->formatTimeDiffSince($index->getLastUpdated()), ':url' => $index->toUrl('break-lock-form')->toString()); $form['locked'] = array('#type' => 'container', '#attributes' => array('class' => array('index-locked', 'messages', 'messages--warning')), '#children' => $this->t('This index is being edited by user @user, and is therefore locked from editing by others. This lock is @age old. Click here to <a href=":url">break this lock</a>.', $lock_message_substitutions), '#weight' => -10); } } $args['%index'] = $index->label(); $form['#title'] = $this->t('Add fields to index %index', $args); $form['properties'] = array('#theme' => 'search_api_form_item_list'); $datasources = array('' => NULL); $datasources += $this->entity->getDatasources(); foreach ($datasources as $datasource) { $form['properties'][] = $this->getDatasourceListItem($datasource); } // Log any unmapped types that were encountered. if ($this->unmappedFields) { $unmapped_types = array(); foreach ($this->unmappedFields as $type => $fields) { $unmapped_types[] = implode(', ', $fields) . ' (' . new FormattableMarkup('type @type', array('@type' => $type)) . ')'; } $vars['@fields'] = implode('; ', $unmapped_types); $vars['%index'] = $this->entity->label(); \Drupal::logger('search_api')->warning('Warning while retrieving available fields for index %index: could not find a type mapping for the following fields: @fields.', $vars); } $form['actions'] = $this->actionsElement($form, $form_state); return $form; }
/** * Implements form #pre_render callback. * * @throws \InvalidArgumentException */ public function preRender(array $element) { if (!isset($element['#payment_statuses']) || !is_array($element['#payment_statuses'])) { throw new \InvalidArgumentException('#payment_statuses must be an array of \\Drupal\\payment\\Plugin\\Payment\\Status\\PaymentStatusInterface instances.'); } $element['table'] = array('#empty' => $this->t('There are no statuses.'), '#header' => array($this->t('Status'), $this->t('Date')), '#type' => 'table'); /** @var \Drupal\payment\Plugin\Payment\Status\PaymentStatusInterface $status */ foreach ($element['#payment_statuses'] as $delta => $payment_status) { if (!$payment_status instanceof PaymentStatusInterface) { $type = is_object($payment_status) ? get_class($payment_status) : gettype($payment_status); throw new \InvalidArgumentException(sprintf('#payment_statuses must be an array of \\Drupal\\payment\\Plugin\\Payment\\Status\\PaymentStatusInterface instances, but the array contained %s.', $type)); } $definition = $payment_status->getPluginDefinition(); $element['table']['status_' . $delta] = array('#attributes' => array('class' => array('payment-status-plugin-' . $payment_status->getPluginId())), 'label' => array('#attributes' => array('class' => array('payment-status-label')), '#markup' => $definition['label']), 'created' => array('#attributes' => array('class' => array('payment-line-item-quantity')), '#markup' => $this->dateFormatter->format($payment_status->getCreated()))); } return $element; }
/** * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state) { $types = $this->nodeTypeStorage->loadMultiple(); if (empty($types)) { $create_url = $this->urlGenerator->generateFromRoute('node.type_add'); $this->setMessage($this->t('You do not have any content types that can be generated. <a href="@create-type">Go create a new content type</a>', array('@create-type' => $create_url)), 'error', FALSE); return; } $options = array(); foreach ($types as $type) { $options[$type->id()] = array('type' => array('#markup' => $type->label())); if ($this->commentManager) { $comment_fields = $this->commentManager->getFields('node'); $map = array($this->t('Hidden'), $this->t('Closed'), $this->t('Open')); $fields = array(); foreach ($comment_fields as $field_name => $info) { // Find all comment fields for the bundle. if (in_array($type->id(), $info['bundles'])) { $instance = FieldConfig::loadByName('node', $type->id(), $field_name); $default_value = $instance->getDefaultValueLiteral(); $default_mode = reset($default_value); $fields[] = SafeMarkup::format('@field: !state', array('@field' => $instance->label(), '!state' => $map[$default_mode['status']])); } } // @todo Refactor display of comment fields. if (!empty($fields)) { $options[$type->id()]['comments'] = array('data' => array('#theme' => 'item_list', '#items' => $fields)); } else { $options[$type->id()]['comments'] = $this->t('No comment fields'); } } } $header = array('type' => $this->t('Content type')); if ($this->commentManager) { $header['comments'] = array('data' => $this->t('Comments'), 'class' => array(RESPONSIVE_PRIORITY_MEDIUM)); } $form['node_types'] = array('#type' => 'tableselect', '#header' => $header, '#options' => $options); $form['kill'] = array('#type' => 'checkbox', '#title' => $this->t('<strong>Delete all content</strong> in these content types before generating new content.'), '#default_value' => $this->getSetting('kill')); $form['num'] = array('#type' => 'number', '#title' => $this->t('How many nodes would you like to generate?'), '#default_value' => $this->getSetting('num'), '#required' => TRUE, '#min' => 0); $options = array(1 => $this->t('Now')); foreach (array(3600, 86400, 604800, 2592000, 31536000) as $interval) { $options[$interval] = $this->dateFormatter->formatInterval($interval, 1) . ' ' . $this->t('ago'); } $form['time_range'] = array('#type' => 'select', '#title' => $this->t('How far back in time should the nodes be dated?'), '#description' => $this->t('Node creation dates will be distributed randomly from the current time, back to the selected time.'), '#options' => $options, '#default_value' => 604800); $form['max_comments'] = array('#type' => $this->moduleHandler->moduleExists('comment') ? 'number' : 'value', '#title' => $this->t('Maximum number of comments per node.'), '#description' => $this->t('You must also enable comments for the content types you are generating. Note that some nodes will randomly receive zero comments. Some will receive the max.'), '#default_value' => $this->getSetting('max_comments'), '#min' => 0, '#access' => $this->moduleHandler->moduleExists('comment')); $form['title_length'] = array('#type' => 'number', '#title' => $this->t('Maximum number of words in titles'), '#default_value' => $this->getSetting('title_length'), '#required' => TRUE, '#min' => 1, '#max' => 255); $form['add_alias'] = array('#type' => 'checkbox', '#disabled' => !$this->moduleHandler->moduleExists('path'), '#description' => $this->t('Requires path.module'), '#title' => $this->t('Add an url alias for each node.'), '#default_value' => FALSE); $form['add_statistics'] = array('#type' => 'checkbox', '#title' => $this->t('Add statistics for each node (node_counter table).'), '#default_value' => TRUE, '#access' => $this->moduleHandler->moduleExists('statistics')); $options = array(); // We always need a language. $languages = $this->languageManager->getLanguages(LanguageInterface::STATE_ALL); foreach ($languages as $langcode => $language) { $options[$langcode] = $language->getName(); } $form['add_language'] = array('#type' => 'select', '#title' => $this->t('Set language on nodes'), '#multiple' => TRUE, '#description' => $this->t('Requires locale.module'), '#options' => $options, '#default_value' => array($this->languageManager->getDefaultLanguage()->getId())); $form['#redirect'] = FALSE; return $form; }
/** * Throws an exception if the current user triggers flood control. * * @throws \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException */ protected function contactFloodControl() { $limit = $this->config('contact.settings')->get('flood.limit'); $interval = $this->config('contact.settings')->get('flood.interval'); if (!$this->flood->isAllowed('contact', $limit, $interval)) { drupal_set_message($this->t('You cannot send more than %limit messages in @interval. Try again later.', array('%limit' => $limit, '@interval' => $this->dateFormatter->formatInterval($interval))), 'error'); throw new AccessDeniedHttpException(); } }
/** * Formats a timestamp. * * @param int $timestamp * A UNIX timestamp to format. * * @return string * The formatted timestamp string using the past or future format setting. */ protected function formatTimestamp($timestamp) { $granularity = $this->getSetting('granularity'); $options = ['granularity' => $granularity]; if ($this->request->server->get('REQUEST_TIME') > $timestamp) { return SafeMarkup::format($this->getSetting('past_format'), ['@interval' => $this->dateFormatter->formatTimeDiffSince($timestamp, $options)]); } else { return SafeMarkup::format($this->getSetting('future_format'), ['@interval' => $this->dateFormatter->formatTimeDiffUntil($timestamp, $options)]); } }
/** * Override parent method, which deals with dates as integers. */ protected function opSimple($field) { $origin = !empty($this->value['type']) && $this->value['type'] == 'offset' ? $this->requestStack->getCurrentRequest()->server->get('REQUEST_TIME') : 0; $value = intval(strtotime($this->value['value'], $origin)); // Convert to ISO. UTC is used since dates are stored in UTC. $value = $this->query->getDateFormat("'" . $this->dateFormatter->format($value, 'custom', DATETIME_DATETIME_STORAGE_FORMAT, DATETIME_STORAGE_TIMEZONE) . "'", $this->dateFormat, TRUE); // This is safe because we are manually scrubbing the value. $field = $this->query->getDateFormat($field, $this->dateFormat, TRUE); $this->query->addWhereExpression($this->options['group'], "{$field} {$this->operator} {$value}"); }
/** * {@inheritdoc} */ public function settingsForm(array $form, FormStateInterface $form_state) { $time = new DrupalDateTime(); $format_types = $this->dateStorage->loadMultiple(); foreach ($format_types as $type => $type_info) { $format = $this->dateFormatter->format($time->format('U'), $type); $options[$type] = $type_info->label() . ' (' . $format . ')'; } $elements['format_type'] = array('#type' => 'select', '#title' => t('Date format'), '#description' => t("Choose a format for displaying the date. Be sure to set a format appropriate for the field, i.e. omitting time for a field that only has a date."), '#options' => $options, '#default_value' => $this->getSetting('format_type')); return $elements; }
/** * Form constructor for the comment overview administration form. * * @param array $form * An associative array containing the structure of the form. * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. * @param string $type * The type of the overview form ('approval' or 'new'). * * @return array * The form structure. */ public function buildForm(array $form, FormStateInterface $form_state, $type = 'new') { // Build an 'Update options' form. $form['options'] = array('#type' => 'details', '#title' => $this->t('Update options'), '#open' => TRUE, '#attributes' => array('class' => array('container-inline'))); if ($type == 'approval') { $options['publish'] = $this->t('Publish the selected comments'); } else { $options['unpublish'] = $this->t('Unpublish the selected comments'); } $options['delete'] = $this->t('Delete the selected comments'); $form['options']['operation'] = array('#type' => 'select', '#title' => $this->t('Action'), '#title_display' => 'invisible', '#options' => $options, '#default_value' => 'publish'); $form['options']['submit'] = array('#type' => 'submit', '#value' => $this->t('Update')); // Load the comments that need to be displayed. $status = $type == 'approval' ? CommentInterface::NOT_PUBLISHED : CommentInterface::PUBLISHED; $header = array('subject' => array('data' => $this->t('Subject'), 'specifier' => 'subject'), 'author' => array('data' => $this->t('Author'), 'specifier' => 'name', 'class' => array(RESPONSIVE_PRIORITY_MEDIUM)), 'posted_in' => array('data' => $this->t('Posted in'), 'class' => array(RESPONSIVE_PRIORITY_LOW)), 'changed' => array('data' => $this->t('Updated'), 'specifier' => 'changed', 'sort' => 'desc', 'class' => array(RESPONSIVE_PRIORITY_LOW)), 'operations' => $this->t('Operations')); $cids = $this->commentStorage->getQuery()->condition('status', $status)->tableSort($header)->pager(50)->execute(); /** @var $comments \Drupal\comment\CommentInterface[] */ $comments = $this->commentStorage->loadMultiple($cids); // Build a table listing the appropriate comments. $options = array(); $destination = $this->getDestinationArray(); $commented_entity_ids = array(); $commented_entities = array(); foreach ($comments as $comment) { $commented_entity_ids[$comment->getCommentedEntityTypeId()][] = $comment->getCommentedEntityId(); } foreach ($commented_entity_ids as $entity_type => $ids) { $commented_entities[$entity_type] = $this->entityManager->getStorage($entity_type)->loadMultiple($ids); } foreach ($comments as $comment) { /** @var $commented_entity \Drupal\Core\Entity\EntityInterface */ $commented_entity = $commented_entities[$comment->getCommentedEntityTypeId()][$comment->getCommentedEntityId()]; $username = array('#theme' => 'username', '#account' => $comment->getOwner()); $body = ''; if (!empty($comment->comment_body->value)) { $body = $comment->comment_body->value; } $comment_permalink = $comment->permalink(); $attributes = $comment_permalink->getOption('attributes') ?: array(); $attributes += array('title' => Unicode::truncate($body, 128)); $comment_permalink->setOption('attributes', $attributes); $options[$comment->id()] = array('title' => array('data' => array('#title' => $comment->getSubject() ?: $comment->id())), 'subject' => array('data' => array('#type' => 'link', '#title' => $comment->getSubject(), '#url' => $comment_permalink)), 'author' => drupal_render($username), 'posted_in' => array('data' => array('#type' => 'link', '#title' => $commented_entity->label(), '#access' => $commented_entity->access('view'), '#url' => $commented_entity->urlInfo())), 'changed' => $this->dateFormatter->format($comment->getChangedTime(), 'short')); $comment_uri_options = $comment->urlInfo()->getOptions(); $links = array(); $links['edit'] = array('title' => $this->t('Edit'), 'url' => Url::fromRoute('entity.comment.edit_form', ['comment' => $comment->id()], $comment_uri_options + ['query' => $destination])); if ($this->moduleHandler->moduleExists('content_translation') && $this->moduleHandler->invoke('content_translation', 'translate_access', array($comment))->isAllowed()) { $links['translate'] = array('title' => $this->t('Translate'), 'url' => Url::fromRoute('entity.comment.content_translation_overview', ['comment' => $comment->id()], $comment_uri_options + ['query' => $destination])); } $options[$comment->id()]['operations']['data'] = array('#type' => 'operations', '#links' => $links); } $form['comments'] = array('#type' => 'tableselect', '#header' => $header, '#options' => $options, '#empty' => $this->t('No comments available.')); $form['pager'] = array('#type' => 'pager'); return $form; }
/** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { // The revision timestamp will be updated when the revision is saved. Keep // the original one for the confirmation message. $original_revision_timestamp = $this->revision->getRevisionCreationTime(); $this->revision = $this->prepareRevertedRevision($this->revision, $form_state); $this->revision->revision_log = t('Copy of the revision from %date.', ['%date' => $this->dateFormatter->format($original_revision_timestamp)]); $this->revision->save(); $this->logger('content')->notice('@type: reverted %title revision %revision.', ['@type' => $this->revision->bundle(), '%title' => $this->revision->label(), '%revision' => $this->revision->getRevisionId()]); drupal_set_message(t('@type %title has been reverted to the revision from %revision-date.', ['@type' => node_get_type_label($this->revision), '%title' => $this->revision->label(), '%revision-date' => $this->dateFormatter->format($original_revision_timestamp)])); $form_state->setRedirect('entity.node.version_history', array('node' => $this->revision->id())); }
/** * Tests the formatDiff method. * * @dataProvider providerTestFormatDiff * * @covers ::formatDiff */ public function testformatDiff($expected, $timestamp1, $timestamp2, $options = array()) { // Mocks a simple formatPlural implementation. $this->stringTranslation->expects($this->any())->method('formatPlural')->with($this->anything(), $this->anything(), $this->anything(), array(), array('langcode' => isset($options['langcode']) ? $options['langcode'] : NULL))->will($this->returnCallback(function ($count, $one, $multiple) { return $count == 1 ? $one : str_replace('@count', $count, $multiple); })); // Mocks a simple translate implementation. $this->stringTranslation->expects($this->any())->method('translate')->with($this->anything())->will($this->returnCallback(function ($string, $args, $options) { return $string; })); $this->assertEquals($expected, $this->dateFormatter->formatDiff($timestamp1, $timestamp2, $options)); }
/** * Displays details about a specific database log message. * * @param int $event_id * Unique ID of the database log message. * * @return array * If the ID is located in the Database Logging table, a build array in the * format expected by drupal_render(); * */ public function eventDetails($event_id) { $build = array(); if ($dblog = $this->database->query('SELECT w.*, u.name, u.uid FROM {watchdog} w INNER JOIN {users} u ON w.uid = u.uid WHERE w.wid = :id', array(':id' => $event_id))->fetchObject()) { $severity = watchdog_severity_levels(); $message = $this->formatMessage($dblog); $username = array('#theme' => 'username', '#account' => user_load($dblog->uid)); $rows = array(array(array('data' => $this->t('Type'), 'header' => TRUE), $this->t($dblog->type)), array(array('data' => $this->t('Date'), 'header' => TRUE), $this->dateFormatter->format($dblog->timestamp, 'long')), array(array('data' => $this->t('User'), 'header' => TRUE), array('data' => $username)), array(array('data' => $this->t('Location'), 'header' => TRUE), l($dblog->location, $dblog->location)), array(array('data' => $this->t('Referrer'), 'header' => TRUE), l($dblog->referer, $dblog->referer)), array(array('data' => $this->t('Message'), 'header' => TRUE), $message), array(array('data' => $this->t('Severity'), 'header' => TRUE), $severity[$dblog->severity]), array(array('data' => $this->t('Hostname'), 'header' => TRUE), String::checkPlain($dblog->hostname)), array(array('data' => $this->t('Operations'), 'header' => TRUE), $dblog->link)); $build['dblog_table'] = array('#type' => 'table', '#rows' => $rows, '#attributes' => array('class' => array('dblog-event')), '#attached' => array('library' => array('dblog/drupal.dblog'))); } return $build; }
/** * Displays details about a specific database log message. * * @param int $event_id * Unique ID of the database log message. * * @return array * If the ID is located in the Database Logging table, a build array in the * format expected by drupal_render(); * */ public function eventDetails($event_id) { $build = array(); if ($dblog = $this->database->query('SELECT w.*, u.uid FROM {watchdog} w LEFT JOIN {users} u ON u.uid = w.uid WHERE w.wid = :id', array(':id' => $event_id))->fetchObject()) { $severity = RfcLogLevel::getLevels(); $message = $this->formatMessage($dblog); $username = array('#theme' => 'username', '#account' => $dblog->uid ? $this->userStorage->load($dblog->uid) : User::getAnonymousUser()); $rows = array(array(array('data' => $this->t('Type'), 'header' => TRUE), $this->t($dblog->type)), array(array('data' => $this->t('Date'), 'header' => TRUE), $this->dateFormatter->format($dblog->timestamp, 'long')), array(array('data' => $this->t('User'), 'header' => TRUE), array('data' => $username)), array(array('data' => $this->t('Location'), 'header' => TRUE), $this->l($dblog->location, $dblog->location ? Url::fromUri($dblog->location) : Url::fromRoute('<none>'))), array(array('data' => $this->t('Referrer'), 'header' => TRUE), $this->l($dblog->referer, $dblog->referer ? Url::fromUri($dblog->referer) : Url::fromRoute('<none>'))), array(array('data' => $this->t('Message'), 'header' => TRUE), $message), array(array('data' => $this->t('Severity'), 'header' => TRUE), $severity[$dblog->severity]), array(array('data' => $this->t('Hostname'), 'header' => TRUE), SafeMarkup::checkPlain($dblog->hostname)), array(array('data' => $this->t('Operations'), 'header' => TRUE), SafeMarkup::checkAdminXss($dblog->link))); $build['dblog_table'] = array('#type' => 'table', '#rows' => $rows, '#attributes' => array('class' => array('dblog-event')), '#attached' => array('library' => array('dblog/drupal.dblog'))); } return $build; }
/** * {@inheritdoc} */ public function buildRow(EntityInterface $entity) { /** @var \Drupal\node\NodeInterface $entity */ $mark = array('#theme' => 'mark', '#mark_type' => node_mark($entity->id(), $entity->getChangedTime())); $langcode = $entity->language()->id; $uri = $entity->urlInfo(); $options = $uri->getOptions(); $options += $langcode != LanguageInterface::LANGCODE_NOT_SPECIFIED && isset($languages[$langcode]) ? array('language' => $languages[$langcode]) : array(); $uri->setOptions($options); $row['title']['data'] = array('#type' => 'link', '#title' => $entity->label(), '#suffix' => ' ' . drupal_render($mark)) + $uri->toRenderArray(); $row['type'] = String::checkPlain(node_get_type_label($entity)); $row['author']['data'] = array('#theme' => 'username', '#account' => $entity->getOwner()); $row['status'] = $entity->isPublished() ? $this->t('published') : $this->t('not published'); $row['changed'] = $this->dateFormatter->format($entity->getChangedTime(), 'short'); $language_manager = \Drupal::languageManager(); if ($language_manager->isMultilingual()) { $row['language_name'] = $language_manager->getLanguageName($langcode); } $row['operations']['data'] = $this->buildOperations($entity); return $row + parent::buildRow($entity); }