Drupal Answers is a question and answer site for Drupal developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I created a new custom block type from /admin/structure/block/block-content/types having x and y fields with field types image and textfield respectively. Then created a block with the same block type and uploded image in x and some text in y. Here my problem is how to load this block via code? More than that how to get values of these block fields 'x' and 'y' by loading the block?

I tried these $block = \Drupal\block_content\Entity\BlockContent::load($bid); $render = \Drupal::entityManager()-> getViewBuilder('block_content')->view($block); didn't worked

share|improve this question

Place the block in the disabled section at admin/structure/block, this creates a block instance with your block_content type, give it a nice easy to remember machine name.

place block in disabled section

By placing it in the disabled section, it won't show up, until you load it programatically.

Then using your machine name:

$machine_name = 'myblock';

$block = \Drupal
  ->entityTypeManager()
  ->getStorage('block')
  ->load($machine_name);
if (!empty($block)) {
  $block_content = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);

  $pre_render = $block_content;
}

If you really want to get the rendered fields, you can do:

$render = \Drupal::entityTypeManager()
  ->getViewBuilder('block')
  ->build($pre_render);

But it is more standard practice to use Drupal's formatters and such and perhaps a custom template, rather than building the block and extracting elements from the rendered render array.

share|improve this answer

There are two questions. How to load and render a configured block is answered perfectly by @oknate.

The second question: More than that how to get values of these block fields 'x' and 'y' by loading the block?

That's easy, because you've already loaded the block content entity, where the fields are stored in the database.

$block = \Drupal\block_content\Entity\BlockContent::load($bid);

You can access the value from the text field

$text = $block->field_y->value;

and get the url from the image field.

$image_url = file_create_url($block->field_x->entity->uri->value);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.