Accessing a block types content programatically

You are here

For anyone who is looking to access Block Fields programmatically that were created in block content in Drupal 8, this function will achieve that and will also allow you to access the files URL created in the "block content" image field if it exists. This uses Drupals new namespacing so it should work into the future with Drupal 9

I created a block type in Drupal 8's UI (structure/block/block-content/types ) and added the fields. To access block type in hook_preprocessor_html programmatically you can use the following function

/**
 * @param $bidArr Block BIDS
 * @param $fieldRequestArr Array of the field you want to access
 */
function _access_content_block_fields_build_arr($bidArr, $fieldRequestArr)
{

    $return = array();
    $blockElements = array();
    //-- Get all blocks
    $blocks = \Drupal\block_content\Entity\BlockContent::loadMultiple($bidArr);
    //-- Add them to return array
    foreach ($blocks as $block) {
        foreach ($fieldRequestArr as $fieldRequest) {
            $blockResult = $block->get($fieldRequest)->getValue();
            $blockElements[$fieldRequest] = $blockResult[0];
            //-- If it is an image field
            if ($fieldRequest == 'field_background_image') {
                $file = \Drupal\file\Entity\File::load($blockResult[0]['target_id']);
                $blockElements['image_url'] =  _access_public_file_path_and_name($file->uri->value);
            }
        }
        $return[] = $blockElements;
    }

    return $return;
}