You are here

class Block in Drupal 8

Same name in this branch
  1. 8 core/modules/block/src/Entity/Block.php \Drupal\block\Entity\Block
  2. 8 core/lib/Drupal/Core/Block/Annotation/Block.php \Drupal\Core\Block\Annotation\Block
  3. 8 core/modules/views/src/Plugin/views/display/Block.php \Drupal\views\Plugin\views\display\Block
  4. 8 core/modules/block/src/Plugin/migrate/source/Block.php \Drupal\block\Plugin\migrate\source\Block
Same name and namespace in other branches
  1. 9 core/modules/block/src/Entity/Block.php \Drupal\block\Entity\Block

Defines a Block configuration entity class.

Plugin annotation


@ConfigEntityType(
  id = "block",
  label = @Translation("Block"),
  label_collection = @Translation("Blocks"),
  label_singular = @Translation("block"),
  label_plural = @Translation("blocks"),
  label_count = @PluralTranslation(
    singular = "@count block",
    plural = "@count blocks",
  ),
  handlers = {
    "access" = "Drupal\block\BlockAccessControlHandler",
    "view_builder" = "Drupal\block\BlockViewBuilder",
    "list_builder" = "Drupal\block\BlockListBuilder",
    "form" = {
      "default" = "Drupal\block\BlockForm",
      "delete" = "Drupal\block\Form\BlockDeleteForm"
    }
  },
  admin_permission = "administer blocks",
  entity_keys = {
    "id" = "id",
    "status" = "status"
  },
  links = {
    "delete-form" = "/admin/structure/block/manage/{block}/delete",
    "edit-form" = "/admin/structure/block/manage/{block}",
    "enable" = "/admin/structure/block/manage/{block}/enable",
    "disable" = "/admin/structure/block/manage/{block}/disable",
  },
  config_export = {
    "id",
    "theme",
    "region",
    "weight",
    "provider",
    "plugin",
    "settings",
    "visibility",
  },
  lookup_keys = {
    "theme"
  }
)

Hierarchy

Expanded class hierarchy of Block

34 files declare their use of Block
AreaEntityUITest.php in core/modules/views_ui/tests/src/Functional/AreaEntityUITest.php
AssertBlockAppearsTrait.php in core/modules/block/tests/src/Functional/AssertBlockAppearsTrait.php
block.module in core/modules/block/block.module
Controls the visual building blocks a page is constructed with.
BlockConfigSchemaTest.php in core/modules/block/tests/src/Kernel/BlockConfigSchemaTest.php
BlockContextMappingUpdateTest.php in core/modules/block/tests/src/Functional/Update/BlockContextMappingUpdateTest.php

... See full list

38 string references to 'Block'
block.info.yml in core/modules/block/block.info.yml
core/modules/block/block.info.yml
block.schema.yml in core/modules/block/config/schema/block.schema.yml
core/modules/block/config/schema/block.schema.yml
BlockLibraryController::listBlocks in core/modules/block/src/Controller/BlockLibraryController.php
Shows a list of blocks that can be added to a theme's layout.
BlockListBuilder::buildBlocksForm in core/modules/block/src/BlockListBuilder.php
Builds the main "Blocks" portion of the form.
BlockManagerTest::setUp in core/tests/Drupal/Tests/Core/Block/BlockManagerTest.php

... See full list

File

core/modules/block/src/Entity/Block.php, line 62

Namespace

Drupal\block\Entity
View source
class Block extends ConfigEntityBase implements BlockInterface, EntityWithPluginCollectionInterface {

  /**
   * The ID of the block.
   *
   * @var string
   */
  protected $id;

  /**
   * The plugin instance settings.
   *
   * @var array
   */
  protected $settings = [];

  /**
   * The region this block is placed in.
   *
   * @var string
   */
  protected $region;

  /**
   * The block weight.
   *
   * @var int
   */
  protected $weight;

  /**
   * The plugin instance ID.
   *
   * @var string
   */
  protected $plugin;

  /**
   * The visibility settings for this block.
   *
   * @var array
   */
  protected $visibility = [];

  /**
   * The plugin collection that holds the block plugin for this entity.
   *
   * @var \Drupal\block\BlockPluginCollection
   */
  protected $pluginCollection;

  /**
   * The available contexts for this block and its visibility conditions.
   *
   * @var array
   */
  protected $contexts = [];

  /**
   * The visibility collection.
   *
   * @var \Drupal\Core\Condition\ConditionPluginCollection
   */
  protected $visibilityCollection;

  /**
   * The condition plugin manager.
   *
   * @var \Drupal\Core\Executable\ExecutableManagerInterface
   */
  protected $conditionPluginManager;

  /**
   * The theme that includes the block plugin for this entity.
   *
   * @var string
   */
  protected $theme;

  /**
   * {@inheritdoc}
   */
  public function getPlugin() {
    return $this
      ->getPluginCollection()
      ->get($this->plugin);
  }

  /**
   * Encapsulates the creation of the block's LazyPluginCollection.
   *
   * @return \Drupal\Component\Plugin\LazyPluginCollection
   *   The block's plugin collection.
   */
  protected function getPluginCollection() {
    if (!$this->pluginCollection) {
      $this->pluginCollection = new BlockPluginCollection(\Drupal::service('plugin.manager.block'), $this->plugin, $this
        ->get('settings'), $this
        ->id());
    }
    return $this->pluginCollection;
  }

  /**
   * {@inheritdoc}
   */
  public function getPluginCollections() {
    return [
      'settings' => $this
        ->getPluginCollection(),
      'visibility' => $this
        ->getVisibilityConditions(),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getPluginId() {
    return $this->plugin;
  }

  /**
   * {@inheritdoc}
   */
  public function getRegion() {
    return $this->region;
  }

  /**
   * {@inheritdoc}
   */
  public function getTheme() {
    return $this->theme;
  }

  /**
   * {@inheritdoc}
   */
  public function getWeight() {
    return $this->weight;
  }

  /**
   * {@inheritdoc}
   */
  public function label() {
    $settings = $this
      ->get('settings');
    if ($settings['label']) {
      return $settings['label'];
    }
    else {
      $definition = $this
        ->getPlugin()
        ->getPluginDefinition();
      return $definition['admin_label'];
    }
  }

  /**
   * Sorts active blocks by weight; sorts inactive blocks by name.
   */
  public static function sort(ConfigEntityInterface $a, ConfigEntityInterface $b) {

    // Separate enabled from disabled.
    $status = (int) $b
      ->status() - (int) $a
      ->status();
    if ($status !== 0) {
      return $status;
    }

    // Sort by weight.
    $weight = $a
      ->getWeight() - $b
      ->getWeight();
    if ($weight) {
      return $weight;
    }

    // Sort by label.
    return strcmp($a
      ->label(), $b
      ->label());
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    parent::calculateDependencies();
    $this
      ->addDependency('theme', $this->theme);
    return $this;
  }

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

    // Entity::postSave() calls Entity::invalidateTagsOnSave(), which only
    // handles the regular cases. The Block entity has one special case: a
    // newly created block may *also* appear on any page in the current theme,
    // so we must invalidate the associated block's cache tag (which includes
    // the theme cache tag).
    if (!$update) {
      Cache::invalidateTags($this
        ->getCacheTagsToInvalidate());
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getVisibility() {
    return $this
      ->getVisibilityConditions()
      ->getConfiguration();
  }

  /**
   * {@inheritdoc}
   */
  public function setVisibilityConfig($instance_id, array $configuration) {
    $conditions = $this
      ->getVisibilityConditions();
    if (!$conditions
      ->has($instance_id)) {
      $configuration['id'] = $instance_id;
      $conditions
        ->addInstanceId($instance_id, $configuration);
    }
    else {
      $conditions
        ->setInstanceConfiguration($instance_id, $configuration);
    }
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getVisibilityConditions() {
    if (!isset($this->visibilityCollection)) {
      $this->visibilityCollection = new ConditionPluginCollection($this
        ->conditionPluginManager(), $this
        ->get('visibility'));
    }
    return $this->visibilityCollection;
  }

  /**
   * {@inheritdoc}
   */
  public function getVisibilityCondition($instance_id) {
    return $this
      ->getVisibilityConditions()
      ->get($instance_id);
  }

  /**
   * Gets the condition plugin manager.
   *
   * @return \Drupal\Core\Executable\ExecutableManagerInterface
   *   The condition plugin manager.
   */
  protected function conditionPluginManager() {
    if (!isset($this->conditionPluginManager)) {
      $this->conditionPluginManager = \Drupal::service('plugin.manager.condition');
    }
    return $this->conditionPluginManager;
  }

  /**
   * {@inheritdoc}
   */
  public function setRegion($region) {
    $this->region = $region;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function setWeight($weight) {
    $this->weight = $weight;
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function createDuplicateBlock($new_id = NULL, $new_theme = NULL) {
    $duplicate = parent::createDuplicate();
    if (!empty($new_id)) {
      $duplicate->id = $new_id;
    }
    if (!empty($new_theme)) {
      $duplicate->theme = $new_theme;
    }
    return $duplicate;
  }

  /**
   * {@inheritdoc}
   */
  public function preSave(EntityStorageInterface $storage) {
    parent::preSave($storage);

    // Ensure the region is valid to mirror the behavior of block_rebuild().
    // This is done primarily for backwards compatibility support of
    // \Drupal\block\BlockInterface::BLOCK_REGION_NONE.
    $regions = system_region_list($this->theme);
    if (!isset($regions[$this->region]) && $this
      ->status()) {
      $this
        ->setRegion(system_default_region($this->theme))
        ->disable();
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
Block::$conditionPluginManager protected property The condition plugin manager.
Block::$contexts protected property The available contexts for this block and its visibility conditions.
Block::$id protected property The ID of the block.
Block::$plugin protected property The plugin instance ID.
Block::$pluginCollection protected property The plugin collection that holds the block plugin for this entity.
Block::$region protected property The region this block is placed in.
Block::$settings protected property The plugin instance settings.
Block::$theme protected property The theme that includes the block plugin for this entity.
Block::$visibility protected property The visibility settings for this block.
Block::$visibilityCollection protected property The visibility collection.
Block::$weight protected property The block weight.
Block::calculateDependencies public function Calculates dependencies and stores them in the dependency property. Overrides ConfigEntityBase::calculateDependencies
Block::conditionPluginManager protected function Gets the condition plugin manager.
Block::createDuplicateBlock public function Creates a duplicate of the block entity. Overrides BlockInterface::createDuplicateBlock
Block::getPlugin public function Returns the plugin instance. Overrides BlockInterface::getPlugin
Block::getPluginCollection protected function Encapsulates the creation of the block's LazyPluginCollection.
Block::getPluginCollections public function Gets the plugin collections used by this object. Overrides ObjectWithPluginCollectionInterface::getPluginCollections
Block::getPluginId public function Returns the plugin ID. Overrides BlockInterface::getPluginId
Block::getRegion public function Returns the region this block is placed in. Overrides BlockInterface::getRegion
Block::getTheme public function Returns the theme ID. Overrides BlockInterface::getTheme
Block::getVisibility public function Returns an array of visibility condition configurations. Overrides BlockInterface::getVisibility
Block::getVisibilityCondition public function Gets a visibility condition plugin instance. Overrides BlockInterface::getVisibilityCondition
Block::getVisibilityConditions public function Gets conditions for this block. Overrides BlockInterface::getVisibilityConditions
Block::getWeight public function Returns the weight of this block (used for sorting). Overrides BlockInterface::getWeight
Block::label public function Gets the label of the entity. Overrides EntityBase::label
Block::postSave public function Acts on a saved entity before the insert or update hook is invoked. Overrides EntityBase::postSave
Block::preSave public function Acts on an entity before the presave hook is invoked. Overrides ConfigEntityBase::preSave
Block::setRegion public function Sets the region this block is placed in. Overrides BlockInterface::setRegion
Block::setVisibilityConfig public function Sets the visibility condition configuration. Overrides BlockInterface::setVisibilityConfig
Block::setWeight public function Sets the block weight. Overrides BlockInterface::setWeight
Block::sort public static function Sorts active blocks by weight; sorts inactive blocks by name. Overrides ConfigEntityBase::sort
BlockInterface::BLOCK_LABEL_VISIBLE Deprecated constant Indicates the block label (title) should be displayed to end users.
BlockInterface::BLOCK_REGION_NONE Deprecated constant Denotes that a block is not enabled in any region and should not be shown.
CacheableDependencyTrait::$cacheContexts protected property Cache contexts.
CacheableDependencyTrait::$cacheMaxAge protected property Cache max-age.
CacheableDependencyTrait::$cacheTags protected property Cache tags.
CacheableDependencyTrait::setCacheability protected function Sets cacheability; useful for value object constructors.
ConfigEntityBase::$isUninstalling private property Whether the config is being deleted by the uninstall process.
ConfigEntityBase::$langcode protected property The language code of the entity's default language.
ConfigEntityBase::$originalId protected property The original ID of the configuration entity.
ConfigEntityBase::$status protected property The enabled/disabled status of the configuration entity. 4
ConfigEntityBase::$third_party_settings protected property Third party entity settings.
ConfigEntityBase::$trustedData protected property Trust supplied data and not use configuration schema on save.
ConfigEntityBase::$uuid protected property The UUID for this entity.
ConfigEntityBase::$_core protected property Information maintained by Drupal core about configuration.
ConfigEntityBase::addDependency protected function Overrides \Drupal\Core\Entity\DependencyTrait:addDependency().
ConfigEntityBase::createDuplicate public function Creates a duplicate of the entity. Overrides EntityBase::createDuplicate 1
ConfigEntityBase::disable public function Disables the configuration entity. Overrides ConfigEntityInterface::disable 1
ConfigEntityBase::enable public function Enables the configuration entity. Overrides ConfigEntityInterface::enable
ConfigEntityBase::get public function Returns the value of a property. Overrides ConfigEntityInterface::get
ConfigEntityBase::getCacheTagsToInvalidate public function Returns the cache tags that should be used to invalidate caches. Overrides EntityBase::getCacheTagsToInvalidate 1
ConfigEntityBase::getConfigDependencyName public function Gets the configuration dependency name. Overrides EntityBase::getConfigDependencyName
ConfigEntityBase::getConfigManager protected static function Gets the configuration manager.
ConfigEntityBase::getConfigTarget public function Gets the configuration target identifier for the entity. Overrides EntityBase::getConfigTarget
ConfigEntityBase::getDependencies public function Gets the configuration dependencies. Overrides ConfigEntityInterface::getDependencies
ConfigEntityBase::getOriginalId public function Gets the original ID. Overrides EntityBase::getOriginalId
ConfigEntityBase::getThirdPartyProviders public function Gets the list of third parties that store information. Overrides ThirdPartySettingsInterface::getThirdPartyProviders
ConfigEntityBase::getThirdPartySetting public function Gets the value of a third-party setting. Overrides ThirdPartySettingsInterface::getThirdPartySetting
ConfigEntityBase::getThirdPartySettings public function Gets all third-party settings of a given module. Overrides ThirdPartySettingsInterface::getThirdPartySettings
ConfigEntityBase::getTypedConfig protected function Gets the typed config manager.
ConfigEntityBase::hasTrustedData public function Gets whether on not the data is trusted. Overrides ConfigEntityInterface::hasTrustedData
ConfigEntityBase::invalidateTagsOnDelete protected static function Override to never invalidate the individual entities' cache tags; the config system already invalidates them. Overrides EntityBase::invalidateTagsOnDelete
ConfigEntityBase::invalidateTagsOnSave protected function Override to never invalidate the entity's cache tag; the config system already invalidates it. Overrides EntityBase::invalidateTagsOnSave
ConfigEntityBase::isInstallable public function Checks whether this entity is installable. Overrides ConfigEntityInterface::isInstallable 2
ConfigEntityBase::isNew public function Overrides Entity::isNew(). Overrides EntityBase::isNew
ConfigEntityBase::isUninstalling public function Returns whether this entity is being changed during the uninstall process. Overrides ConfigEntityInterface::isUninstalling
ConfigEntityBase::link public function Deprecated way of generating a link to the entity. See toLink(). Overrides EntityBase::link
ConfigEntityBase::onDependencyRemoval public function Informs the entity that entities it depends on will be deleted. Overrides ConfigEntityInterface::onDependencyRemoval 7
ConfigEntityBase::preDelete public static function Acts on entities before they are deleted and before hooks are invoked. Overrides EntityBase::preDelete 8
ConfigEntityBase::save public function Saves an entity permanently. Overrides EntityBase::save 1
ConfigEntityBase::set public function Sets the value of a property. Overrides ConfigEntityInterface::set
ConfigEntityBase::setOriginalId public function Sets the original ID. Overrides EntityBase::setOriginalId
ConfigEntityBase::setStatus public function Sets the status of the configuration entity. Overrides ConfigEntityInterface::setStatus
ConfigEntityBase::setThirdPartySetting public function Sets the value of a third-party setting. Overrides ThirdPartySettingsInterface::setThirdPartySetting
ConfigEntityBase::setUninstalling public function
ConfigEntityBase::status public function Returns whether the configuration entity is enabled. Overrides ConfigEntityInterface::status 4
ConfigEntityBase::toArray public function Gets an array of all property values. Overrides EntityBase::toArray 2
ConfigEntityBase::toUrl public function Gets the URL object for the entity. Overrides EntityBase::toUrl
ConfigEntityBase::trustData public function Sets that the data should be trusted. Overrides ConfigEntityInterface::trustData
ConfigEntityBase::unsetThirdPartySetting public function Unsets a third-party setting. Overrides ThirdPartySettingsInterface::unsetThirdPartySetting
ConfigEntityBase::url public function Gets the public URL for this entity. Overrides EntityBase::url
ConfigEntityBase::urlInfo public function Gets the URL object for the entity. Overrides EntityBase::urlInfo
ConfigEntityBase::__construct public function Constructs an Entity object. Overrides EntityBase::__construct 10
ConfigEntityBase::__sleep public function Overrides EntityBase::__sleep 4
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function Aliased as: traitSleep 1
DependencySerializationTrait::__wakeup public function 2
DependencyTrait::$dependencies protected property The object's dependencies.
DependencyTrait::addDependencies protected function Adds multiple dependencies.
DependencyTrait::addDependency protected function Adds a dependency. Aliased as: addDependencyTrait
EntityBase::$enforceIsNew protected property Boolean indicating whether the entity should be forced to be new.
EntityBase::$entityTypeId protected property The entity type.
EntityBase::$typedData protected property A typed data object wrapping this entity.
EntityBase::access public function Checks data value access. Overrides AccessibleInterface::access 1
EntityBase::bundle public function Gets the bundle of the entity. Overrides EntityInterface::bundle 1
EntityBase::create public static function Constructs a new entity object, without permanently saving it. Overrides EntityInterface::create
EntityBase::delete public function Deletes an entity permanently. Overrides EntityInterface::delete 2
EntityBase::enforceIsNew public function Enforces an entity to be new. Overrides EntityInterface::enforceIsNew
EntityBase::entityManager Deprecated protected function Gets the entity manager.
EntityBase::entityTypeBundleInfo protected function Gets the entity type bundle info service.
EntityBase::entityTypeManager protected function Gets the entity type manager.
EntityBase::getCacheContexts public function The cache contexts associated with this object. Overrides CacheableDependencyTrait::getCacheContexts
EntityBase::getCacheMaxAge public function The maximum age for which this object may be cached. Overrides CacheableDependencyTrait::getCacheMaxAge
EntityBase::getCacheTags public function The cache tags associated with this object. Overrides CacheableDependencyTrait::getCacheTags
EntityBase::getConfigDependencyKey public function Gets the key that is used to store configuration dependencies. Overrides EntityInterface::getConfigDependencyKey
EntityBase::getEntityType public function Gets the entity type definition. Overrides EntityInterface::getEntityType
EntityBase::getEntityTypeId public function Gets the ID of the type of the entity. Overrides EntityInterface::getEntityTypeId
EntityBase::getListCacheTagsToInvalidate protected function The list cache tags to invalidate for this entity.
EntityBase::getTypedData public function Gets a typed data object for this entity object. Overrides EntityInterface::getTypedData
EntityBase::hasLinkTemplate public function Indicates if a link template exists for a given key. Overrides EntityInterface::hasLinkTemplate
EntityBase::id public function Gets the identifier. Overrides EntityInterface::id 11
EntityBase::language public function Gets the language of the entity. Overrides EntityInterface::language 1
EntityBase::languageManager protected function Gets the language manager.
EntityBase::linkTemplates protected function Gets an array link templates. 1
EntityBase::load public static function Loads an entity. Overrides EntityInterface::load
EntityBase::loadMultiple public static function Loads one or more entities. Overrides EntityInterface::loadMultiple
EntityBase::postCreate public function Acts on a created entity before hooks are invoked. Overrides EntityInterface::postCreate 4
EntityBase::postDelete public static function Acts on deleted entities before the delete hook is invoked. Overrides EntityInterface::postDelete 16
EntityBase::postLoad public static function Acts on loaded entities. Overrides EntityInterface::postLoad 2
EntityBase::preCreate public static function Changes the values of an entity before it is created. Overrides EntityInterface::preCreate 5
EntityBase::referencedEntities public function Gets a list of entities referenced by this entity. Overrides EntityInterface::referencedEntities 1
EntityBase::toLink public function Generates the HTML for a link to this entity. Overrides EntityInterface::toLink
EntityBase::uriRelationships public function Gets a list of URI relationships supported by this entity. Overrides EntityInterface::uriRelationships
EntityBase::urlRouteParameters protected function Gets an array of placeholders for this entity. 2
EntityBase::uuid public function Gets the entity UUID (Universally Unique Identifier). Overrides EntityInterface::uuid 1
EntityBase::uuidGenerator protected function Gets the UUID generator.
PluginDependencyTrait::calculatePluginDependencies protected function Calculates and adds dependencies of a specific plugin instance. 1
PluginDependencyTrait::getPluginDependencies protected function Calculates and returns dependencies of a specific plugin instance.
PluginDependencyTrait::moduleHandler protected function Wraps the module handler. 1
PluginDependencyTrait::themeHandler protected function Wraps the theme handler. 1
RefinableCacheableDependencyTrait::addCacheableDependency public function 1
RefinableCacheableDependencyTrait::addCacheContexts public function
RefinableCacheableDependencyTrait::addCacheTags public function
RefinableCacheableDependencyTrait::mergeCacheMaxAge public function
SynchronizableEntityTrait::$isSyncing protected property Whether this entity is being created, updated or deleted through a synchronization process.
SynchronizableEntityTrait::isSyncing public function
SynchronizableEntityTrait::setSyncing public function