4

I have a custom entity with a large amount of properties on it.

We want to format these entity properties to look a certain way, without modifying the underlying data in the table.

What is the most idiomatic (the most Drupal) way of doing it?

We're trying to put an Entity Reference of this custom entity on a node and render only a few fields - with a form of preprocessing or something along those lines so that we can control the ultimate output.

I can get the fields to show with this key => value pair in the entity array in hook_entity_info():

'extra fields controller class' => 'EntityDefaultExtraFieldsController',

But it doesn't seem to give me any control over the output.

Alternatively, I can put all of the properties into $entity->content in hook_entity_view() as such:

foreach ($entity as $field_name => $property) {
  if (in_array($field_name, $properties)) {
    $entity->content[$field_name] = array("#markup" => $property . "<br />");
  }

But this doesn't seem very idiomatic.

This seems like a problem that I can't find a lot of resources on.

  • In D8 base fields are first-class citizens, formatters and widgets work like any other field. Not sure about D7. – Sam152 Sep 4 '17 at 7:11
  • I could be way off base here but what about setting a custom view mode in hook_entity_info_alter, set that view mode in the Ui and then use theme debugger to get the custom view mode template name? Then theme away per field to your heart's content. You'll probably need to use some custom preprocess functions either to remove field markup or just get the vars via the array path or a combo of both. – Danny Englander Jun 26 '18 at 21:50
0

We're trying to put an Entity Reference of this custom entity on a node and render only a few fields - with a form of preprocessing or something along those lines so that we can control the ultimate output.

Sounds like hook_entity_view is what you want. Use "teaser" or create a new view mode, and attach the reference using the given view mode, then implement your logic to render the properties as you like.

Alternatively / additionally, you could look at Display Suite and DS Extras which will give you more flexibility to expose properties via DS custom fields or in field templates.

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.