isPublished example

$links['edit']['url'] = $edit_url;
          }

          if (isset($links['edit'])) {
            $links['edit']['title'] = $this->t('Edit');
          }
          $status = [
            'data' => [
              '#type' => 'inline_template',
              '#template' => '<span class="status">{% if status %}{{ "Published"|t }}{% else %}{{ "Not published"|t }}{% endif %}</span>{% if outdated %} <span class="marker">{{ "outdated"|t }}</span>{% endif %}',
              '#context' => [
                'status' => $metadata->isPublished(),
                'outdated' => $metadata->isOutdated(),
              ],
            ],
          ];

          if ($is_original) {
            $language_name = $this->t('<strong>@language_name (Original language)</strong>', ['@language_name' => $language_name]);
            $source_name = $this->t('n/a');
          }
          else {
            /** @var \Drupal\Core\Access\AccessResultInterface $delete_route_access */
            
$this->testNode->save();
    \Drupal::entityTypeManager()->getStorage('node')->resetCache();
    $this->testNode = Node::load($this->testNode->id());

    ConfigurableLanguage::createFromLangcode('de')->save();
  }

  /** * Tests the field item list when accessing an index. */
  public function testArrayIndex() {
    $this->assertFalse($this->testNode->isPublished());
    $this->assertEquals('draft', $this->testNode->moderation_state[0]->value);
  }

  /** * Tests the field item list when iterating. */
  public function testArrayIteration() {
    $states = [];
    foreach ($this->testNode->moderation_state as $item) {
      $states[] = $item->value;
    }
    
    // \Drupal\system\Tests\Entity\EntityAccessControlHandlerTest::testDefaultEntityAccess().     if ($entity->label() == 'forbid_access') {
      return AccessResult::forbidden();
    }

    if ($operation === 'view label' && $entity instanceof EntityTestLabel) {
      // Viewing the label of the 'entity_test_label' entity type is allowed.       return AccessResult::allowed();
    }
    elseif (in_array($operation['view', 'view label'])) {
      if (!$entity->isDefaultTranslation()) {
        if ($entity instanceof EntityPublishedInterface && !$entity->isPublished()) {
          return AccessResult::allowedIfHasPermission($account, 'view unpublished test entity translations');
        }
        else {
          return AccessResult::allowedIfHasPermission($account, 'view test entity translations');
        }
      }
      if ($entity instanceof EntityPublishedInterface && !$entity->isPublished()) {
        return AccessResult::neutral('Unpublished entity');
      }
      return AccessResult::allowedIfHasPermission($account, 'view test entity');
    }
    
/** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    if ($account->hasPermission('administer taxonomy')) {
      return AccessResult::allowed()->cachePerPermissions();
    }

    switch ($operation) {
      case 'view':
        $access_result = AccessResult::allowedIf($account->hasPermission('access content') && $entity->isPublished())
          ->cachePerPermissions()
          ->addCacheableDependency($entity);
        if (!$access_result->isAllowed()) {
          $access_result->setReason("The 'access content' permission is required and the taxonomy term must be published.");
        }
        return $access_result;

      case 'update':
        if ($account->hasPermission("edit terms in {$entity->bundle()}")) {
          return AccessResult::allowed()->cachePerPermissions();
        }

        

class CommentAccessControlHandler extends EntityAccessControlHandler {

  /** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    /** @var \Drupal\comment\CommentInterface|\Drupal\user\EntityOwnerInterface $entity */

    $comment_admin = $account->hasPermission('administer comments');
    if ($operation == 'approve') {
      return AccessResult::allowedIf($comment_admin && !$entity->isPublished())
        ->cachePerPermissions()
        ->addCacheableDependency($entity);
    }

    if ($comment_admin) {
      $access = AccessResult::allowed()->cachePerPermissions();
      return ($operation != 'view') ? $access : $access->andIf($entity->getCommentedEntity()->access($operation$account, TRUE));
    }

    switch ($operation) {
      case 'view':
        
$this->assertSame($loaded_media_type->getFieldMap()['attribute_1' => 'name']);

    // We need to clear the statically cached field definitions to account for     // fields that have been created by API calls in this test, since they exist     // in a separate memory space from the web server.     $this->container->get('entity_field.manager')->clearCachedFieldDefinitions();

    // Test that a media item being created with default status to "FALSE",     // will be created unpublished.     /** @var \Drupal\media\MediaInterface $unpublished_media */
    $unpublished_media = Media::create(['name' => 'unpublished test media', 'bundle' => $loaded_media_type->id()]);
    $this->assertFalse($unpublished_media->isPublished());
    $unpublished_media->delete();

    // Tests media type delete form.     $page->clickLink('Delete');
    $assert_session->assertWaitOnAjaxRequest();
    $this->assertNotEmpty($assert_session->waitForElementVisible('css', '#drupal-modal'));
    $assert_session->addressEquals('admin/structure/media/manage/' . $this->testMediaType->id());
    $this->click('.ui-dialog button:contains("Delete")');
    $assert_session->addressEquals('admin/structure/media');
    $assert_session->pageTextContains('The media type ' . $new_name . ' has been deleted.');

    
$request_options[RequestOptions::HEADERS]['Accept'] = static::$mimeType;
    $request_options[RequestOptions::HEADERS]['Content-Type'] = static::$mimeType;
    $request_options = array_merge_recursive($request_options$this->getAuthenticationRequestOptions('POST'));
    $request_options[RequestOptions::BODY] = $this->serializer->encode($this->getNormalizedPostEntity()static::$format);

    $url = $this->getEntityResourcePostUrl()->setOption('query', ['_format' => static::$format]);

    // Status should be FALSE when posting as anonymous.     $response = $this->request('POST', $url$request_options);
    $unserialized = $this->serializer->deserialize((string) $response->getBody()get_class($this->entity)static::$format);
    $this->assertResourceResponse(201, FALSE, $response);
    $this->assertFalse($unserialized->isPublished());

    // Grant anonymous permission to skip comment approval.     $this->grantPermissionsToTestedRole(['skip comment approval']);

    // Status should be TRUE when posting as anonymous and skip comment approval.     $response = $this->request('POST', $url$request_options);
    $unserialized = $this->serializer->deserialize((string) $response->getBody()get_class($this->entity)static::$format);
    $this->assertResourceResponse(201, FALSE, $response);
    $this->assertTrue($unserialized->isPublished());
  }

  
$form['meta'] = [
      '#type' => 'details',
      '#group' => 'advanced',
      '#weight' => -10,
      '#title' => $this->t('Status'),
      '#attributes' => ['class' => ['entity-meta__header']],
      '#tree' => TRUE,
      '#access' => $this->currentUser->hasPermission('administer nodes'),
    ];
    $form['meta']['published'] = [
      '#type' => 'item',
      '#markup' => $node->isPublished() ? $this->t('Published') : $this->t('Not published'),
      '#access' => !$node->isNew(),
      '#wrapper_attributes' => ['class' => ['entity-meta__title']],
    ];
    $form['meta']['changed'] = [
      '#type' => 'item',
      '#title' => $this->t('Last saved'),
      '#markup' => !$node->isNew() ? $this->dateFormatter->format($node->getChangedTime(), 'short') : $this->t('Not saved yet'),
      '#wrapper_attributes' => ['class' => ['entity-meta__last-saved']],
    ];
    $form['meta']['author'] = [
      '#type' => 'item',
      

function hook_node_access_records(\Drupal\node\NodeInterface $node) {
  // We only care about the node if it has been marked private. If not, it is   // treated just like any other node and we completely ignore it.   if ($node->private->value) {
    $grants = [];
    // Only published Catalan translations of private nodes should be viewable     // to all users. If we fail to check $node->isPublished(), all users would be able     // to view an unpublished node.     if ($node->isPublished()) {
      $grants[] = [
        'realm' => 'example',
        'gid' => 1,
        'grant_view' => 1,
        'grant_update' => 0,
        'grant_delete' => 0,
        'langcode' => 'ca',
      ];
    }
    // For the example_author array, the GID is equivalent to a UID, which     // means there are many groups of just 1 user.
// Publish the English article and check that the translation stays     // unpublished.     $this->drupalGet('node/' . $english_node->id() . '/edit');
    $this->submitForm(['moderation_state[0][state]' => 'published'], 'Save (this translation)');
    $this->assertSession()->pageTextContains('Article English node has been updated.');
    $english_node = $this->drupalGetNodeByTitle('English node', TRUE);
    $french_node = $english_node->getTranslation('fr');
    $this->assertEquals('French node', $french_node->label());

    $this->assertEquals('published', $english_node->moderation_state->value);
    $this->assertTrue($english_node->isPublished());
    $this->assertEquals('draft', $french_node->moderation_state->value);
    $this->assertFalse($french_node->isPublished());

    // Create another article with its translation. This time we will publish     // the translation first.     $edit = [
      'title[0][value]' => 'Another node',
      'moderation_state[0][state]' => 'draft',
    ];
    $this->drupalGet('node/add/article');
    $this->submitForm($edit, 'Save');
    
/** * Tests changing the moderation state during a sync. */
  public function testSingleRevisionStateChangedDuringSync() {
    $entity = EntityTestMulRevPub::create([
      'moderation_state' => 'published',
      'name' => 'foo',
    ]);
    $entity->save();
    $initial_revision_id = $entity->getRevisionId();
    $this->assertTrue($entity->isDefaultRevision());
    $this->assertTrue($entity->isPublished());

    $entity->setSyncing(TRUE);
    $entity->moderation_state = 'draft';
    $entity->save();

    // If a moderation state is changed to a draft while syncing, it will revert     // to the same properties of an item of content that was initially created     // as a draft.     $this->assertEquals($initial_revision_id$entity->getRevisionId());
    $this->assertFalse($entity->isPublished());
    $this->assertTrue($entity->isDefaultRevision());
    
'type' => 'page',
      'title' => 'Another node',
      'uid' => 1,
    ]);
    $node2->setPublished();
    $node2->save();

    $this->container->get('renderer')->executeInRenderContext(new RenderContext()function D) use (&$node1, &$node2$action) {
      $action->execute([$node1$node2]);
    });

    $this->assertFalse($node1->isPublished());
    $this->assertTrue($node2->isPublished());
  }

}
$request_options[RequestOptions::HEADERS]['Accept'] = 'application/vnd.api+json';
    $request_options[RequestOptions::HEADERS]['Content-Type'] = 'application/vnd.api+json';
    $request_options = NestedArray::mergeDeep($request_options$this->getAuthenticationRequestOptions());
    $request_options[RequestOptions::BODY] = Json::encode($this->getPostDocument());

    $url = Url::fromRoute('jsonapi.comment--comment.collection.post');

    // Status should be FALSE when posting as anonymous.     $response = $this->request('POST', $url$request_options);
    $this->assertResourceResponse(201, FALSE, $response);
    $this->assertFalse(Json::decode((string) $response->getBody())['data']['attributes']['status']);
    $this->assertFalse($this->entityStorage->loadUnchanged(2)->isPublished());

    // Grant anonymous permission to skip comment approval.     $this->grantPermissionsToTestedRole(['skip comment approval']);

    // Status must be TRUE when posting as anonymous and skip comment approval.     $response = $this->request('POST', $url$request_options);
    $this->assertResourceResponse(201, FALSE, $response);
    $this->assertTrue(Json::decode((string) $response->getBody())['data']['attributes']['status']);
    $this->assertTrue($this->entityStorage->loadUnchanged(3)->isPublished());
  }

  


  /** * Tests the migrated comments. */
  public function testMigration() {
    $comment = Comment::load(1);
    $this->assertInstanceOf(Comment::class$comment);
    $this->assertSame('Subject field in English', $comment->getSubject());
    $this->assertSame('1421727536', $comment->getCreatedTime());
    $this->assertSame(1421727536, $comment->getChangedTime());
    $this->assertTrue($comment->isPublished());
    $this->assertSame('admin', $comment->getAuthorName());
    $this->assertSame('admin@local.host', $comment->getAuthorEmail());
    $this->assertSame('This is a comment', $comment->comment_body->value);
    $this->assertSame('filtered_html', $comment->comment_body->format);
    $this->assertSame('2001:db8:ffff:ffff:ffff:ffff:ffff:ffff', $comment->getHostname());
    $this->assertSame('en', $comment->language()->getId());
    $this->assertSame('1000000', $comment->field_integer->value);

    $node = $comment->getCommentedEntity();
    $this->assertInstanceOf(NodeInterface::class$node);
    $this->assertSame('1', $node->id());

    
protected function checkAccess(EntityInterface $entity$operation, AccountInterface $account) {
    /** @var \Drupal\media\MediaInterface $entity */
    // Allow admin permission to override all operations.     if ($account->hasPermission($this->entityType->getAdminPermission())) {
      return AccessResult::allowed()->cachePerPermissions();
    }

    $type = $entity->bundle();
    $is_owner = ($account->id() && $account->id() === $entity->getOwnerId());
    switch ($operation) {
      case 'view':
        if ($entity->isPublished()) {
          $access_result = AccessResult::allowedIf($account->hasPermission('view media'))
            ->cachePerPermissions()
            ->addCacheableDependency($entity);
          if (!$access_result->isAllowed()) {
            $access_result->setReason("The 'view media' permission is required when the media item is published.");
          }
        }
        elseif ($account->hasPermission('view own unpublished media')) {
          $access_result = AccessResult::allowedIf($is_owner)
            ->cachePerPermissions()
            ->cachePerUser()
            
Home | Imprint | This part of the site doesn't use cookies.