0

On my Drupal 8 site I'm trying to create a view of a custom entity that contains a custom field type which is multivalued in the entity. It works fine when I try to display the multiple values on the same row, but when I uncheck the checkbox in views to move them to separate rows, I do end up with multiple rows but it still displays both values on the same row, just in multiple instances. Worse, it just shoves them together without any sort of separation. For instance:

Row 1: Item1Item2

Row 2: Item1Item2

When it should be:

Row 1: Item 1

Row 2: Item 2

Again, it works fine if I want them in the same row, using Views multivalued format, so I'm guessing the problem lies somewhere in my custom FieldFormatter. For the sake of testing I'm just displaying the deltas for each item, which come out as 01 on the rows that have multiple values and 0 on the rows that only have one value.

Here's my viewElements method in the field formatter:

public function viewElements(FieldItemListInterface $items, $langcode) {

  $elements = [];

  foreach ($items as $delta => $item) {

    $elements[$delta] = [
      '#markup' => $delta ,
    ];
  }

  return $elements;
}

This type of thing seems to work for the core field formatters that I looked at, but is obviously not working here. Does anybody see anything odd or missing from this?

  • No, the core field formatters don't handle the deltas for multiple rows, this is done by the "field" plugin Drupal\views\Plugin\views\field\EntityField. What core does however is to assign this for most fields as default plugin in views_data. – 4k4 Jun 27 '18 at 21:21
  • I'm not sure I follow. What do I do to fix this problem in my instance? – A.J. Jun 28 '18 at 13:14
  • I simply wanted to point in another direction, the problem is IMHO not the custom field formatter, see EntityField::prepareItemsByDelta – 4k4 Jun 28 '18 at 14:07
  • Ok, I'm not really sure what's going on there. I'm really surprised that this doesn't work out of the box. Especially considering my field was generated by Drupal Console. – A.J. Jun 28 '18 at 17:45
  • Then console generated also a MyEntityViewsData.php for your entity and you need to tweak the views data here, although for normal bundle fields this class should discover the correct views data automatically. For base fields, especially multi value ones (not used very often), this might be different. – 4k4 Jun 28 '18 at 18:27

Your Answer

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

Browse other questions tagged or ask your own question.