getOwner example

$status = ($this->currentUser->hasPermission('skip comment approval') ? CommentInterface::PUBLISHED : CommentInterface::NOT_PUBLISHED);
    }

    $date = '';
    if ($comment->id()) {
      $date = !empty($comment->date) ? $comment->date : DrupalDateTime::createFromTimestamp($comment->getCreatedTime());
    }

    // The uid field is only displayed when a user with the permission     // 'administer comments' is editing an existing comment from an     // authenticated user.     $owner = $comment->getOwner();
    $form['author']['uid'] = [
      '#type' => 'entity_autocomplete',
      '#target_type' => 'user',
      '#default_value' => $owner->isAnonymous() ? NULL : $owner,
      // A comment can be made anonymous by leaving this field empty therefore       // there is no need to list them in the autocomplete.       '#selection_settings' => ['include_anonymous' => FALSE],
      '#title' => $this->t('Authored by'),
      '#description' => $this->t('Leave blank for %anonymous.', ['%anonymous' => $config->get('anonymous')]),
      '#access' => $is_admin,
    ];

    
$thread = $prefix . Number::intToAlphadecimal(++$n) . '/';
          $lock_name = "comment:{$this->getCommentedEntityId()}:$thread";
        } while (!\Drupal::lock()->acquire($lock_name));
        $this->threadLock = $lock_name;
      }
      $this->setThread($thread);
    }
    // The entity fields for name and mail have no meaning if the user is not     // Anonymous. Set them to NULL to make it clearer that they are not used.     // For anonymous users see \Drupal\comment\CommentForm::form() for mail,     // and \Drupal\comment\CommentForm::buildEntity() for name setting.     if (!$this->getOwner()->isAnonymous()) {
      $this->set('name', NULL);
      $this->set('mail', NULL);
    }
  }

  /** * {@inheritdoc} */
  public function postSave(EntityStorageInterface $storage$update = TRUE) {
    parent::postSave($storage$update);

    
'title' => ['data' => ['#title' => $comment->getSubject() ?: $comment->id()]],
        'subject' => [
          'data' => [
            '#type' => 'link',
            '#title' => $comment->getSubject(),
            '#url' => $comment_permalink,
          ],
        ],
        'author' => [
          'data' => [
            '#theme' => 'username',
            '#account' => $comment->getOwner(),
          ],
        ],
        'posted_in' => [
          'data' => [
            '#type' => 'link',
            '#title' => $commented_entity->label(),
            '#access' => $commented_entity->access('view'),
            '#url' => $commented_entity->toUrl(),
          ],
        ],
        'changed' => $this->dateFormatter->format($comment->getChangedTimeAcrossTranslations(), 'short'),
      ];

      }
    }
    $row['name']['data'] = [
      '#type' => 'link',
      '#title' => $entity->label(),
      '#url' => $entity->toUrl(),
    ];
    $row['type'] = $entity->bundle->entity->label();
    $row['author']['data'] = [
      '#theme' => 'username',
      '#account' => $entity->getOwner(),
    ];
    $row['status'] = $entity->isPublished() ? $this->t('Published') : $this->t('Unpublished');
    $row['changed'] = $this->dateFormatter->format($entity->getChangedTime(), 'short');

    if ($this->languageManager->isMultilingual()) {
      $row['language'] = $this->languageManager->getLanguageName($entity->language()->getId());
    }
    return $row + parent::buildRow($entity);
  }

  /** * {@inheritdoc} */

    $form_display->setComponent('uid', $widget);
    $form_display->save();

    $this->drupalLogin($this->adminUser);

    // Save the node without making any changes.     $this->drupalGet('node/' . $node->id() . '/edit');
    $this->submitForm([], 'Save');
    $this->nodeStorage->resetCache([$node->id()]);
    $node = $this->nodeStorage->load($node->id());
    $this->assertSame($this->webUser->id()$node->getOwner()->id());

    $this->checkVariousAuthoredByValues($node, 'uid[target_id]');

    // Hide the 'authored by' field from the form.     $form_display->removeComponent('uid')->save();

    // Check that saving the node without making any changes keeps the proper     // author ID.     $this->drupalGet('node/' . $node->id() . '/edit');
    $this->submitForm([], 'Save');
    $this->nodeStorage->resetCache([$node->id()]);
    
/** * Asserts that two files have the same values (except timestamp). * * @param \Drupal\file\FileInterface $before * File object to compare. * @param \Drupal\file\FileInterface $after * File object to compare. */
  public function assertFileUnchanged(FileInterface $before, FileInterface $after) {
    $this->assertEquals($before->id()$after->id());
    $this->assertEquals($before->getOwner()->id()$after->getOwner()->id());
    $this->assertEquals($before->getFilename()$after->getFilename());
    $this->assertEquals($before->getFileUri()$after->getFileUri());
    $this->assertEquals($before->getMimeType()$after->getMimeType());
    $this->assertEquals($before->getSize()$after->getSize());
    $this->assertEquals($before->isPermanent()$after->isPermanent());
  }

  /** * Asserts that two files are not the same by comparing the fid and filepath. * * @param \Drupal\file\FileInterface $file1 * File object to compare. * @param \Drupal\file\FileInterface $file2 * File object to compare. */
case 'title':
          $replacements[$original] = $node->getTitle();
          break;

        case 'edit-url':
          $replacements[$original] = $node->toUrl('edit-form', $url_options)->toString();
          break;

        // Default values for the chained tokens handled below.         case 'author':
          $account = $node->getOwner() ? $node->getOwner() : User::load(0);
          $replacements[$original] = $account->label();
          $bubbleable_metadata->addCacheableDependency($account);
          break;

        case 'created':
          $replacements[$original] = \Drupal::service('date.formatter')->format($node->getCreatedTime(), 'medium', '', NULL, $langcode);
          break;
      }
    }

    if ($author_tokens = $token_service->findWithPrefix($tokens, 'author')) {
      

function hook_file_copy(\Drupal\file\FileInterface $file, \Drupal\file\FileInterface $source) {
  // Make sure that the file name starts with the owner's user name.   if (!str_starts_with($file->getFilename()$file->getOwner()->name)) {
    $file->setFilename($file->getOwner()->name . '_' . $file->getFilename());
    $file->save();

    \Drupal::logger('file')->notice('Copied file %source has been renamed to %destination', ['%source' => $source->filename, '%destination' => $file->getFilename()]);
  }
}

/** * Respond to a file that has been moved. * * @param \Drupal\file\FileInterface $file * The updated file entity after the move. * @param \Drupal\file\FileInterface $source * The original file entity before the move. * * @see \Drupal\file\FileRepositoryInterface::move() */
/** * Asserts that two files have the same values (except timestamp). * * @param \Drupal\file\FileInterface $before * File object to compare. * @param \Drupal\file\FileInterface $after * File object to compare. */
  public function assertFileUnchanged(FileInterface $before, FileInterface $after) {
    $this->assertEquals($before->id()$after->id(), 'File id is the same');
    $this->assertEquals($before->getOwner()->id()$after->getOwner()->id(), 'File owner is the same');
    $this->assertEquals($before->getFilename()$after->getFilename(), 'File name is the same');
    $this->assertEquals($before->getFileUri()$after->getFileUri(), 'File path is the same');
    $this->assertEquals($before->getMimeType()$after->getMimeType(), 'File MIME type is the same');
    $this->assertEquals($before->getSize()$after->getSize(), 'File size is the same');
    $this->assertEquals($before->isPermanent()$after->isPermanent(), 'File status is the same');
  }

  /** * Asserts that two files are not the same by comparing the fid and filepath. * * @param \Drupal\file\FileInterface $file1 * File object to compare. * @param \Drupal\file\FileInterface $file2 * File object to compare. */

  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $this->configuration['owner_uid'] = $form_state->getValue('owner_uid');
  }

  /** * {@inheritdoc} */
  public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
    /** @var \Drupal\node\NodeInterface $object */
    $result = $object->access('update', $account, TRUE)
      ->andIf($object->getOwner()->access('edit', $account, TRUE));

    return $return_as_object ? $result : $result->isAllowed();
  }

}
class AuthorNameFormatter extends FormatterBase {

  /** * {@inheritdoc} */
  public function viewElements(FieldItemListInterface $items$langcode) {
    $elements = [];

    foreach ($items as $delta => $item) {
      /** @var \Drupal\comment\CommentInterface $comment */
      $comment = $item->getEntity();
      $account = $comment->getOwner();
      $elements[$delta] = [
        '#theme' => 'username',
        '#account' => $account,
        '#cache' => [
          'tags' => $account->getCacheTags() + $comment->getCacheTags(),
        ],
      ];
    }

    return $elements;
  }

  
$build['#pre_render'][] = [$this, 'removeSubmittedInfo'];

      // Fetch comments for snippet.       $rendered = $this->renderer->renderPlain($build);
      $this->addCacheableDependency(CacheableMetadata::createFromRenderArray($build));
      $rendered .= ' ' . $this->moduleHandler->invoke('comment', 'node_update_index', [$node]);

      $extra = $this->moduleHandler->invokeAll('node_search_result', [$node]);

      $username = [
        '#theme' => 'username',
        '#account' => $node->getOwner(),
      ];

      $result = [
        'link' => $node->toUrl('canonical', ['absolute' => TRUE])->toString(),
        'type' => $type->label(),
        'title' => $node->label(),
        'node' => $node,
        'extra' => $extra,
        'score' => $item->calculated_score,
        'snippet' => search_excerpt($keys$rendered$item->langcode),
        'langcode' => $node->language()->getId(),
      ];
// Refresh variables after the treatment.     $this->refreshVariables();

    // Submit a phrase wrapped in double quotes to include the punctuation.     $edit = ['keys' => '"bunny\'s"'];
    $this->drupalGet('search/node');
    $this->submitForm($edit, 'Search');
    $this->assertSession()->pageTextContains($node->label());

    // Check if the author is linked correctly to the user profile page.     $username = $node->getOwner()->getAccountName();
    $this->assertSession()->linkExists($username);

    // Search for "&" and verify entities are not broken up in the output.     $edit = ['keys' => '&'];
    $this->drupalGet('search/node');
    $this->submitForm($edit, 'Search');
    $this->assertSession()->responseNotContains('<strong>&</strong>amp;');
    $this->assertSession()->statusMessageContains('You must include at least one keyword', 'warning');

    $edit = ['keys' => '&amp;'];
    $this->drupalGet('search/node');
    


    $this->drupalGet('activity');
    $this->assertSession()->pageTextNotContains($unpublished->label());
    $this->assertSession()->pageTextContains($published->label());
    $this->assertSession()->linkExists('My recent content', 0, 'User tab shows up on the global tracker page.');

    // Assert cache contexts, specifically the pager and node access contexts.     $this->assertCacheContexts(['languages:language_interface', 'route', 'theme', 'url.query_args:' . MainContentViewSubscriber::WRAPPER_FORMAT, 'url.query_args.pagers:0', 'user.node_grants:view', 'user']);
    // Assert cache tags for the action/tabs blocks, visible node, and node list     // cache tag.     $expected_tags = Cache::mergeTags($published->getCacheTags()$published->getOwner()->getCacheTags());
    // Because the 'user.permissions' cache context is being optimized away.     $role_tags = [];
    foreach ($this->user->getRoles() as $rid) {
      $role_tags[] = "config:user.role.$rid";
    }
    $expected_tags = Cache::mergeTags($expected_tags$role_tags);
    $block_tags = [
      'block_view',
      'local_task',
      'config:block.block.page_actions_block',
      'config:block.block.page_tabs_block',
      

    $override = BaseFieldOverride::loadByName('node', 'ponies', 'uid');
    if ($override) {
      $override->delete();
    }
    $uid_field = \Drupal::service('entity_field.manager')->getBaseFieldDefinitions('node')['uid'];
    $config = $uid_field->getConfig('ponies');
    $config->save();
    $this->assertEquals('Drupal\node\Entity\Node::getDefaultEntityOwner', $config->get('default_value_callback'));
    /** @var \Drupal\node\NodeInterface $node */
    $node = Node::create(['type' => 'ponies']);
    $owner = $node->getOwner();
    $this->assertInstanceOf(UserInterface::class$owner);
    $this->assertEquals($this->user->id()$owner->id());
  }

}
Home | Imprint | This part of the site doesn't use cookies.