3

I have written this code to render a list of profiles (using the Profile module). It works fine.

// render profiles
$accounts = \Drupal\user\Entity\User::loadMultiple($uids);
$storage = \Drupal::entityTypeManager()->getStorage('profile');
if (!empty($storage)) {
  foreach ($accounts as $account) {
    $profiles[] = $storage->loadByUser($account, 'profile');
  }
  if ($profiles) {
    $content = \Drupal::entityTypeManager()
      ->getViewBuilder('profile')
      ->viewMultiple($profiles, 'teaser');
  }
}

I have applied the same logic to rendering a list of groups (using the Group module). It fails with the error below.

// render groups
$groups = \Drupal\group\Entity\Group::loadMultiple($ids);
$storage = \Drupal::entityTypeManager()->getStorage('group');
if (!empty($storage)) {
  foreach ($groups as $group) {
    $test[] = $storage->loadByGroup($group, 'my_group');  // FAILS HERE
  }
  /* if ($groups) {
    $content = \Drupal::entityTypeManager()
      ->getViewBuilder('group')
      ->viewMultiple($group, 'teaser');
  } */
}

Fatal error: Call to undefined method Drupal\Core\Entity\Sql\SqlContentEntityStorage::loadByGroup()

What method should I use to load a group? or how should I programatically load a group?

Thanks

1
  • $groups = \Drupal\group\Entity\Group::loadMultiple($ids); is what loads your Group entities. Look at its code and you will see it does the storage bits already
    – zerolab
    Jan 25, 2017 at 10:39

1 Answer 1

4

Adding my comment as an answer:

$groups = \Drupal\group\Entity\Group::loadMultiple($ids); is all that is needed to load the groups based on IDs. Group::loadMultiple() does the storage bits already, so no need to duplicate the work.

So the full snippet would be something like:

<?php

$groups = \Drupal\group\Entity\Group::loadMultiple($ids);
if ($groups) {
  $content = \Drupal::entityTypeManager()
      ->getViewBuilder('group')
      ->viewMultiple($group, 'teaser');
}
3
  • What if I just want to load a single group? Group::load($id) doesn't work. Is there a shortcut to not loadMultiple and then getting the first element in the array?
    – Paul
    Jun 6, 2017 at 14:18
  • 1
    Group extends ContentEnityBase which defines the single load function. Group::load($id) works. Just make sure you pass the correct group id. Otherwise $group = reset($groups); will give you the first item
    – zerolab
    Jun 6, 2017 at 15:41
  • You are absolutely right. It does work. I probably messed up something else before.
    – Paul
    Jun 6, 2017 at 18:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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