Last active
May 4, 2018 00:44
-
-
Save quexpl/e287007d2aad242566ec7280407bdeea to your computer and use it in GitHub Desktop.
Drupal 8: Create and update custom block in hook_update()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Keep yours custom block in code! | |
* | |
* This approach let you avoid this error: | |
* "This block is broken or missing. You may be missing content or you might need to enable the original module." | |
*/ | |
/** | |
* Create new custom block. | |
*/ | |
function my_module_update_8001(){ | |
$block_body = <<<EOF | |
<div class="my-awesome-block"> | |
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, tempor ut ultrices non, blandit quis nulla. Nulla facilisi. | |
</div> | |
EOF; | |
$blocks = [ | |
'block_content' => [ | |
'a1e23473-ecac-4ad1-8308-80edc0114141' => [ | |
'info' => 'User links', | |
'type' => 'basic', | |
'body' => [ | |
'value' => $block_body, | |
'format' => 'full_html', | |
], | |
], | |
], | |
]; | |
foreach ($blocks as $block_type => $items) { | |
$storage = \Drupal::entityTypeManager()->getStorage($block_type); | |
foreach ($items as $uuid => $item) { | |
if (\Drupal::service('entity.repository')->loadEntityByUuid($block_type, $uuid) == FALSE) { | |
$entity = $storage->create($item + ['uuid' => $uuid]); | |
$entity->save(); | |
} | |
} | |
} | |
} | |
/** | |
* Update custom block. | |
*/ | |
function my_module_update_8002(){ | |
$block_type = 'block_content'; | |
$block_uuid = 'b399d911-f137-4d80-9f15-21f4ca230ba7'; | |
$block_body = <<<EOF | |
<div class="my-awesome-block"> | |
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam enim urna, tempor ut ultrices non, blandit quis nulla. Nulla facilisi. | |
</div> | |
EOF; | |
if ($block = \Drupal::service('entity.repository')->loadEntityByUuid($block_type, $block_uuid)) { | |
$block->set('body', [ | |
'value' => $block_body, | |
'format' => 'full_html', | |
]); | |
$block->save(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment