4

On my controller for a custom page I've loaded an entity and I want to render, on the template for this custom page, only a field of the loaded entity. I would like to get the render array for this field.

Is it possible? I don't want to create a template for this content type only for this

8

This is an example for D8:

$node = Node::load('1');
$display_settings = array(
  'label' => 'inline',
);
$build = $node->body->view($display_settings);
| improve this answer | |
  • How would I render $build? – liquidcms Jan 10 at 17:39
0

I would use the following code.

$field_to_render = field_view_field('model', $model, 'field_headerimage_image', 'full');
$field_to_render[$active_image]['#image_style'] = 'header_style';
$output = render($field_to_render[$active_image]);
| improve this answer | |
0

I can't comment yet, otherwise I'd add this to the answer (https://drupal.stackexchange.com/a/206821/71534) but it's also helpful to know how to get the $display_settings for your field.

  1. Setup the field with Manage Display the way you want

  2. Then you can check the config (e.g. core.entity_view_display.node.page.teaser.yml

  3. Find the field you want under the content key in the root of the yml file, which may look like this:

    content:
      body:
        label: hidden
        type: text_default
        weight: 22
        settings: {  }
        third_party_settings: {  }
        region: content
    
  4. So in PHP you could set $display_settings to:

    $display_settings = array(
      'label' => 'hidden',
      'type' => 'text_default',
      'weight' => 22,
      'settings' => array(),
      'third_party_settings' => array(),
      'region' => 'content'
    );
    
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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