function BlockForm::getUniqueMachineName

Same name in other branches
  1. 9 core/modules/block/src/BlockForm.php \Drupal\block\BlockForm::getUniqueMachineName()
  2. 10 core/modules/block/src/BlockForm.php \Drupal\block\BlockForm::getUniqueMachineName()
  3. 11.x core/modules/block/src/BlockForm.php \Drupal\block\BlockForm::getUniqueMachineName()

Generates a unique machine name for a block.

Parameters

\Drupal\block\BlockInterface $block: The block entity.

Return value

string Returns the unique name.

1 call to BlockForm::getUniqueMachineName()
BlockForm::form in core/modules/block/src/BlockForm.php
Gets the actual form array to be built.

File

core/modules/block/src/BlockForm.php, line 412

Class

BlockForm
Provides form for block instance forms.

Namespace

Drupal\block

Code

public function getUniqueMachineName(BlockInterface $block) {
    $suggestion = $block->getPlugin()
        ->getMachineNameSuggestion();
    // Get all the blocks which starts with the suggested machine name.
    $query = $this->storage
        ->getQuery();
    $query->condition('id', $suggestion, 'CONTAINS');
    $block_ids = $query->execute();
    $block_ids = array_map(function ($block_id) {
        $parts = explode('.', $block_id);
        return end($parts);
    }, $block_ids);
    // Iterate through potential IDs until we get a new one. E.g.
    // 'plugin', 'plugin_2', 'plugin_3', etc.
    $count = 1;
    $machine_default = $suggestion;
    while (in_array($machine_default, $block_ids)) {
        $machine_default = $suggestion . '_' . ++$count;
    }
    return $machine_default;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.