currentUser example

$this->form = [
      '#property' => $this->randomMachineName(),
    ];
    $this->formState = new FormState();
    $this->formState->set('example', $this->randomMachineName());
  }

  /** * Tests the form cache with a logged-in user. */
  public function testCacheToken() {
    \Drupal::currentUser()->setAccount(new UserSession(['uid' => 1]));
    \Drupal::formBuilder()->setCache($this->formBuildId, $this->form, $this->formState);

    $cached_form_state = new FormState();
    $cached_form = \Drupal::formBuilder()->getCache($this->formBuildId, $cached_form_state);
    $this->assertEquals($this->form['#property']$cached_form['#property']);
    $this->assertNotEmpty($cached_form['#cache_token'], 'Form has a cache token');
    $this->assertEquals($this->formState->get('example')$cached_form_state->get('example'));

    // Test that the form cache isn't loaded when the session/token has changed.     // Change the private key. (We cannot change the session ID because this     // will break the parent site test runner batch.)

  public function contactSitePage(ContactFormInterface $contact_form = NULL) {
    $config = $this->config('contact.settings');

    // Use the default form if no form has been passed.     if (empty($contact_form)) {
      $contact_form = $this->entityTypeManager()
        ->getStorage('contact_form')
        ->load($config->get('default_form'));
      // If there are no forms, do not display the form.       if (empty($contact_form)) {
        if ($this->currentUser()->hasPermission('administer contact forms')) {
          $this->messenger()->addError($this->t('The contact form has not been configured. <a href=":add">Add one or more forms</a> .', [
            ':add' => Url::fromRoute('contact.form_add')->toString(),
          ]));
          return [];
        }
        else {
          throw new NotFoundHttpException();
        }
      }
    }

    
'#title' => $label,
        '#default_value' => $this->value,
      ];
    }
  }

  /** * {@inheritdoc} */
  public function query() {
    // This can only work if we're authenticated in.     if (!\Drupal::currentUser()->isAuthenticated()) {
      return;
    }

    // Don't filter if we're exposed and the checkbox isn't selected.     if ((!empty($this->options['exposed'])) && empty($this->value)) {
      return;
    }

    // Hey, Drupal kills old history, so nodes that haven't been updated     // since HISTORY_READ_LIMIT are outta here!     $limit = REQUEST_TIME - HISTORY_READ_LIMIT;

    
'info' => 'Non-reusable Block',
      'type' => 'spiffy',
      'reusable' => FALSE,
    ]);
    $this->blockNonReusable->save();

    $configuration = [
      'target_type' => 'block_content',
      'target_bundles' => ['spiffy' => 'spiffy'],
      'sort' => ['field' => '_none'],
    ];
    $this->selectionHandler = new TestSelection($configuration, '', '', $this->container->get('entity_type.manager')$this->container->get('module_handler'), \Drupal::currentUser(), \Drupal::service('entity_field.manager'), \Drupal::service('entity_type.bundle.info'), \Drupal::service('entity.repository'));

    // Setup the 3 expectation cases.     $this->expectations = [
      'both_blocks' => [
        'spiffy' => [
          $this->blockReusable->id() => $this->blockReusable->label(),
          $this->blockNonReusable->id() => $this->blockNonReusable->label(),
        ],
      ],
      'block_reusable' => ['spiffy' => [$this->blockReusable->id() => $this->blockReusable->label()]],
      'block_non_reusable' => ['spiffy' => [$this->blockNonReusable->id() => $this->blockNonReusable->label()]],
    ];
/** * {@inheritdoc} */
  public function getFormId() {
    return 'shortcut_set_switch';
  }

  /** * {@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 DShortcutSet $set) {
      return $set->label();
    }$this->shortcutSetStorage->loadMultiple());

    $current_set = shortcut_current_displayed_set($this->user);

    // Only administrators can add shortcut sets.
'%title' => $revisionLabel,
      ]));
    }

    $this->logger($this->revision->getEntityType()->getProvider())->info('@type: reverted %title revision %revision.', [
      '@type' => $this->revision->bundle(),
      '%title' => $revisionLabel,
      '%revision' => $revisionId,
    ]);

    $versionHistoryUrl = $this->revision->toUrl('version-history');
    if ($versionHistoryUrl->access($this->currentUser())) {
      $form_state->setRedirectUrl($versionHistoryUrl);
    }

    if (!$form_state->getRedirect()) {
      $canonicalUrl = $this->revision->toUrl();
      if ($canonicalUrl->access($this->currentUser())) {
        $form_state->setRedirectUrl($canonicalUrl);
      }
    }
  }

  


    $this->assertSame('1', $user1->id());

    $file = File::create([
      'uid' => $user1->id(),
      'filename' => 'druplicon.txt',
      'filemime' => 'text/plain',
    ]);
    $this->assertFalse($file->access('create'));

    \Drupal::currentUser()->setAccount($user1);
    $this->assertFalse($file->access('create'));
  }

  /** * Tests cacheability metadata. */
  public function testFileCacheability() {
    $file = File::create([
      'filename' => 'green-scarf',
      'uri' => 'private://green-scarf',
      'filemime' => 'text/plain',
    ]);

  public function access(Route $route, RouteMatchInterface $route_match$bundle = NULL): AccessResultInterface {
    $permission = $route->getRequirement('_permission');
    if ($permission && !$this->currentUser()->hasPermission($permission)) {
      return AccessResult::neutral()->cachePerPermissions();
    }
    // Set $this->bundle for use by ::permissionsByProvider().     if ($bundle instanceof EntityInterface) {
      $this->bundle = $bundle;
    }
    else {
      $bundle_entity_type = $route->getDefault('bundle_entity_type');
      $bundle_name = is_string($bundle) ? $bundle : $route_match->getRawParameter($bundle_entity_type);
      $this->bundle = $this->entityTypeManager
        ->getStorage($bundle_entity_type)
        
$entity = $this->container->get('entity_type.manager')
      ->getStorage($entity_type)
      ->create([
        'name' => 'test',
        'user_id' => $this->container->get('current_user')->id(),
      ]);
    $this->assertEquals($this->languageManager->getDefaultLanguage()->getId()$entity->language()->getId()new FormattableMarkup('%entity_type: Entity created with API has default language.', ['%entity_type' => $entity_type]));
    $entity = $this->container->get('entity_type.manager')
      ->getStorage($entity_type)
      ->create([
        'name' => 'test',
        'user_id' => \Drupal::currentUser()->id(),
        $langcode_key => LanguageInterface::LANGCODE_NOT_SPECIFIED,
      ]);

    $this->assertEquals(LanguageInterface::LANGCODE_NOT_SPECIFIED, $entity->language()->getId()new FormattableMarkup('%entity_type: Entity language not specified.', ['%entity_type' => $entity_type]));
    $this->assertEmpty($entity->getTranslationLanguages(FALSE)new FormattableMarkup('%entity_type: No translations are available', ['%entity_type' => $entity_type]));

    // Set the value in default language.     $entity->set($this->fieldName, [0 => ['value' => 'default value']]);
    // Get the value.     $field = $entity->getTranslation(LanguageInterface::LANGCODE_DEFAULT)->get($this->fieldName);
    $this->assertEquals('default value', $field->value, new FormattableMarkup('%entity_type: Untranslated value retrieved.', ['%entity_type' => $entity_type]));
    
protected function entityFormTitle(EntityInterface $entity) {
    return $entity->label();
  }

  /** * Default value callback for the owner base field definition. * * @return int * The user ID. */
  public static function getDefaultOwnerId() {
    return \Drupal::currentUser()->id();
  }

}

        else {
          unset($current_page[$key]);
        }
      }
    }

    $args = [
      '%capital_name' => Unicode::ucfirst($taxonomy_vocabulary->label()),
      '%name' => $taxonomy_vocabulary->label(),
    ];
    if ($this->currentUser()->hasPermission('administer taxonomy') || $this->currentUser()->hasPermission('edit terms in ' . $taxonomy_vocabulary->id())) {
      switch ($vocabulary_hierarchy) {
        case VocabularyInterface::HIERARCHY_DISABLED:
          $help_message = $this->t('You can reorganize the terms in %capital_name using their drag-and-drop handles, and group terms under a parent term by sliding them under and to the right of the parent.', $args);
          break;

        case VocabularyInterface::HIERARCHY_SINGLE:
          $help_message = $this->t('%capital_name contains terms grouped under parent terms. You can reorganize the terms in %capital_name using their drag-and-drop handles.', $args);
          break;

        case VocabularyInterface::HIERARCHY_MULTIPLE:
          $help_message = $this->t('%capital_name contains terms with multiple parents. Drag and drop of terms with multiple parents is not supported, but you can re-enable drag-and-drop support by editing each term to include only a single parent.', $args);
          

    return parent::offsetExists($offset);
  }

  /** * {@inheritdoc} */
  public function access($operation = 'view', AccountInterface $account = NULL, $return_as_object = FALSE) {
    if ($operation === 'edit') {
      // Only users with administer comments permission can edit the comment       // status field.       $result = AccessResult::allowedIfHasPermission($account ?: \Drupal::currentUser(), 'administer comments');
      return $return_as_object ? $result : $result->isAllowed();
    }
    if ($operation === 'view') {
      // Only users with "post comments" or "access comments" permission can       // view the field value. The formatter,       // Drupal\comment\Plugin\Field\FieldFormatter\CommentDefaultFormatter,       // takes care of showing the thread and form based on individual       // permissions, so if a user only has ‘post comments’ access, only the       // form will be shown and not the comments.       $result = AccessResult::allowedIfHasPermission($account ?: \Drupal::currentUser(), 'access comments')
        ->orIf(AccessResult::allowedIfHasPermission($account ?: \Drupal::currentUser(), 'post comments'));
      

function hook_file_url_alter(&$uri) {
  $user = \Drupal::currentUser();

  // User 1 will always see the local file in this example.   if ($user->id() == 1) {
    return;
  }

  $cdn1 = 'http://cdn1.example.com';
  $cdn2 = 'http://cdn2.example.com';
  $cdn_extensions = ['css', 'js', 'gif', 'jpg', 'jpeg', 'png'];

  // Most CDNs don't support private file transfers without a lot of hassle,

  public function getReplyForm(Request $request, EntityInterface $entity$field_name$pid = NULL) {
    $account = $this->currentUser();
    $build = [];

    // The user is not just previewing a comment.     if ($request->request->get('op') != $this->t('Preview')) {

      // $pid indicates that this is a reply to a comment.       if ($pid) {
        // Load the parent comment.         $comment = $this->entityTypeManager()->getStorage('comment')->load($pid);
        // Display the parent comment.         $build['comment_parent'] = $this->entityTypeManager()->getViewBuilder('comment')->view($comment);
      }
return [
      '#type' => 'container',
      '#attributes' => [
        'class' => ['js-show'],
      ],
      'toggle_content_preview' => [
        '#title' => $this->t('Show content preview'),
        '#type' => 'checkbox',
        '#value' => TRUE,
        '#attributes' => [
          // Set attribute used by local storage to get content preview status.           'data-content-preview-id' => "Drupal.layout_builder.content_preview.{$this->currentUser()->id()}",
        ],
        '#id' => 'layout-builder-content-preview',
      ],
    ];
  }

  /** * Gets the current user. * * @return \Drupal\Core\Session\AccountInterface * The current user. */
Home | Imprint | This part of the site doesn't use cookies.