BlockForm::getUniqueMachineName

public BlockForm::getUniqueMachineName(BlockInterface $block)

Generates a unique machine name for a block.

Parameters

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

Return value

string Returns the unique name.

File

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

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;
}
doc_Drupal
2016-10-29 08:47:32
Comments
Leave a Comment

Please login to continue.