CommentFileSizeAuthor
#65 group-computed-fields-2718195-65.patch11.28 KBlexhouk
#62 group-computed-fields-2718195-62.patch10.71 KBlexhouk
#61 group-computedfields-2718195-60.patch9.2 KBhitesh-jain
#60 group-computedfields-2718195-58.patch9.2 KBhitesh-jain
#59 group-2718195-58-groups-computed-field.patch9.11 KBHenry Tran
#57 group-2718195-57-groups-computed-field.patch9.1 KBHenry Tran
#56 group-2718195-56-groups-computed-field.patch10.24 KBHenry Tran
#50 Capture d’écran du 2018-12-03 19-45-51.png105.33 KBzenimagine
#45 group-2718195-45-groups-computed-field.patch9.33 KBmodestmoes
#45 interdiff-40-45.txt3.37 KBmodestmoes
#44 group-2718195-43-groups-computed-field.patch5.73 KBmodestmoes
#43 group-2718195-43-groups-computed-field.patch7.43 KBmodestmoes
#43 interdiff-40-43.txt3.47 KBmodestmoes
#40 group-2718195-40-groups-computed-field.patch7.93 KBgeek-merlin
#40 Interdiff-37-40.txt4.36 KBgeek-merlin
#37 interdiff-2718195-35-37.txt1.83 KBrecrit
#37 add-computed-field-without-FieldItemListComputedInterface-2718195-37.patch6.88 KBrecrit
#35 interdiff-2718195-34-35.txt600 bytesrecrit
#35 add-computed-field-without-FieldItemListComputedInterface-2718195-35.patch6.53 KBrecrit
#34 add-computed-field-without-FieldItemListComputedInterface-2718195-34.patch6.4 KBrecrit
#26 add-computed-field-2718195-26.patch5.88 KBrealityloop
add-computed-field-2718195-25.patch2.83 KBrealityloop
#23 2718195-add-computed-field.patch6.09 KBadammalone
#12 2718195.group_.computed-ref-field-wip.patch6.37 KBjoachim
Support from Acquia helps fund testing for Drupal Acquia logo

Comments

joachim created an issue. See original summary.

joachim’s picture

Title: Add a pseudofield showing an entity's group(s) » Add a computed field or pseudofield showing an entity's group(s)

After a bit of thought about this, it seemed to me that a computed entityreference field would be better here.

We'd get the entityreference field formatters for free, along with access control to the group entities.

However, while I can define the field, see it in the node field display UI, it doesn't output anything on nodes. The entityreference field formatter class is called for the computed field, but $items is empty.

So tte basic problem is that I don't see where to actually tell the field what its computed value is.

I've got this:

/**
 * Implements hook_entity_base_field_info().
 */
function group_entity_base_field_info(\Drupal\Core\Entity\EntityTypeInterface $entity_type) {
  // Apply to all nodes for proof of concept. Would ultimately need to check group content plugins here.
  if ($entity_type->id() == 'node') {
    $fields = array();
    $fields['group'] = \Drupal\Core\Field\BaseFieldDefinition\BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Groups'))
      ->setDescription(t('The groups this @label belongs to.', ['@label' => $entity_type->getLabel()]))
      ->setSetting('target_type', 'group')
      ->setComputed(TRUE)
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayOptions('view', array(
        'label' => 'above',
        'type' => 'label',
        'weight' => -5,
      ));

    return $fields;
  }
}

I've tried adding

      //->setClass('\Drupal\group\TestEntRefFieldValue')

to that, but that has to be a class that inherits from EntityReferenceFieldItemList, but it's EntityReferenceItem which AFAICT actually returns a value.

I've also tried making a custom entity type, which inherits from EntityReferenceItem, and returning something in getValue(), but that doesn't work either.

kristiaanvandeneynde’s picture

This sounds like a nice idea. Have you tried setting the value in hook_entity_load()?

joachim’s picture

I haven't, but that felt a bit wrong in that we'd have to act on every single entity type and for every entity that's loaded, go check whether there's a Group Content plugin that's enabled for that entity type. That seems to me like it could really hurt performance.

kristiaanvandeneynde’s picture

We can approach the field the way Group already does for the group_roles field on memberships, i.e.:
- define the field in config
- then apply that field where necessary
- in hook_entity_load check if the entity has a field called 'group'
- if so, check if the field is an instance of our field from config
- if so, load all groups for the entity (we have a helper function for that)

joachim’s picture

- in hook_entity_load check if the entity has a field called 'group'
- if so, check if the field is an instance of our field from config
- if so, load all groups for the entity (we have a helper function for that)

That's all doable with a computed field too.

It's just that I'm hoping there's a more efficient way of setting its value than hook_entity_load().

Xano’s picture

You do not want to use hook_entity_load(), as it will fail for any reference that is changed after loading the entity. A field with a computed property is probably the way to go. You could look into extending EntityReferenceItem with your own class, so to outside code your field looks like any other entity reference field (there is no interface that can be implemented, unfortunately). Instead of storing an internal entity ID, it loads the reference ID by getting another entity reference field's value. The name of this other (sibling) field can be part of your new field's settings, as well as the name of the second entity reference field on the dynamically loaded entity. By storing this in the settings, your two-step dynamic entity reference field will become reusable.

joachim’s picture

> You could look into extending EntityReferenceItem with your own class, so to outside code your field looks like any other entity reference field (there is no interface that can be implemented, unfortunately).

I went some way down that route, but I couldn't figure out where to return the field's value within that class.

> Instead of storing an internal entity ID, it loads the reference ID by getting another entity reference field's value. The name of this other (sibling) field can be part of your new field's settings, as well as the name of the second entity reference field on the dynamically loaded entity. By storing this in the settings, your two-step dynamic entity reference field will become reusable.

In our case, the reference ID needs to be obtained by querying Group Content entities. I can see how this *could* be made reusable, but it would be more complicated than just storing the name of another field.

It goes like this:

- given a Node entity
- query for the GroupContent entity where:
- the type is derived from the Node's type
- the foo field is equal to the Node ID
- get a field value from the retrieved Group Content entity

So the settings would need to store the way of building the query. Or we hand over that logic to a plugin, and the settings store the plugin ID.

kristiaanvandeneynde’s picture

Right, I was thinking in D7 terms where a computed field would generally be set on entity or field load and then be kept up to date during runtime. If we can do this with an entity reference subclass, then that's fine too.

However, looking at https://www.drupal.org/node/2112677, it seems we may be able to pull it off by using setClass('\Drupal\group\ComputedValue\ParentGroup') or something.

Xano’s picture

I would recommend you set the following requirements for this new field:

  • Lazy-loading of referenced entities at all times, otherwise you willingly increase the chance of bugs.
  • To the outside world, your field must look exactly like the EntityReferenceItem class so formatters are able to work with it. There is no specific interface you can implement, so this requires a bit more thought to get right.
  • Implement hook_field_formatter_alter() to mark your new field type as supported for every formatter that already supports entity reference items.

In our case, the reference ID needs to be obtained by querying Group Content entities. I can see how this *could* be made reusable, but it would be more complicated than just storing the name of another field.

Is this a reverse entity reference? In that case this would be hard to make reusable in the beginning. I agree that writing a use-case-specific solution is probably best to start with.

joachim’s picture

> Is this a reverse entity reference?

Hmm come to think of it, not really.

There are two real fields (which are base fields) on Group Content entity which point to the Group entity and the Node entity (or other entity that is a group member). The computed field on the Node should point to the Group.

We have:

Node <-- GroupContent --> Group

and we want:

Node ~~~> Group
joachim’s picture

Status: Active » Needs work
FileSize
6.37 KB

> by using setClass('\Drupal\group\ComputedValue\ParentGroup') or something.

I tried that, but that class expects to be the same sort of thing as EntityReferenceFieldItemList, and I couldn't find a way to get that to return a value.

> To the outside world, your field must look exactly like the EntityReferenceItem class so formatters are able to work with it.

I made a start on this approach. I don't see a way to change that class for the entity_ref field type, so I had to declare a new field type, which I don't think is ideal, as other modules won't know it's a reference field.

I've had to stop working on this for the time being, but here's a patch of my work branch. It's all a bit of a mess as I was trying various things, eg code from both the approaches above is still there, and also earlier work with pseudofields. But it can show what I've tried so far and perhaps be a starting point if someone else wants to look at this.

Xano’s picture

I made a start on this approach. I don't see a way to change that class for the entity_ref field type, so I had to declare a new field type, which I don't think is ideal, as other modules won't know it's a reference field.

A new field type is indeed the right way, and you are right about other code not knowing your new field type is compatible with the standard entity reference field. That is why formatter info must be altered to define that entity reference formatters work for the new field type as well.

joachim’s picture

> you are right about other code not knowing your new field type is compatible with the standard entity reference field

Isn't that going to rule out a lot of potential benefits? If this could use the existing entityreference field type, then any other module that does something with entityreference fields could work with this.

If it's not possible to make a computed entityreference field, should we be thinking of making a feature request on Core?

Xano’s picture

You can swap out the class of the existing entity reference plugin, but I'd recommend against that. Such practices should generally be limited to specific applications, and not be used by reusable extensions like Drupal modules. What if multiple modules start swapping out the same thing?

joachim’s picture

Agreed, that's not viable for a contrib module.

What bugs me is this:

> //->setClass('\Drupal\group\TestEntRefFieldValue')

This is changing a class for the field, but the wrong one!

kristiaanvandeneynde’s picture

> by using setClass('\Drupal\group\ComputedValue\ParentGroup') or something.

I tried that, but that class expects to be the same sort of thing as EntityReferenceFieldItemList, and I couldn't find a way to get that to return a value.

Inside of an EntityReferenceFieldItemList, you can call getEntity() to get the entity the field belongs to. When you have that, you can get the parent Groups for that entity and set them as the value in getValue()?

I really think we should try doing this with plain old entity reference fields for the reasons joachim mentioned.

seanB’s picture

Just ran into this. Link the core issue that could fix the computed property.

seanB’s picture

Just posting some code that seems to work with #2392845-66: Add a trait to standardize handling of computed item lists. Hopefully this help someone. This is helping me index, filter and show groups related to content when using search api solr views.

I could create a patch if you would consider adding this?

/**
 * Implements hook_entity_base_field_info().
 *
 * Creates computed fields to get the groups related to a entity. There will be
 * a field containing all groups. Each group type will also get a separate
 * field.
 *
 * We currently only use this for nodes and users since they can be installed
 * as group content.
 */
function mymodule_entity_base_field_info(EntityTypeInterface $entity_type) {
  $fields = [];

  $entity_types = ['node', 'user'];
  if (in_array($entity_type->id(), $entity_types)) {
    $fields['groups'] = BaseFieldDefinition::create('entity_reference')
      ->setName('groups')
      ->setTargetEntityTypeId($entity_type->id())
      ->setSetting('target_type', 'group')
      ->setLabel(t('Get the related groups for this entity.'))
      ->setDescription(t('A list of all the groups referencing this entity.'))
      ->setTranslatable(FALSE)
      ->setComputed(TRUE)
      ->setClass('\Drupal\mymodule\Fields\MyModuleGroupReferenceItemList')
      ->setDisplayConfigurable('view', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'above',
        'weight' => -5,
      ]);

    foreach (\Drupal::service('entity_type.manager')->getStorage('group_type')->loadMultiple() as $group_type) {
      /** @var \Drupal\group\Entity\GroupType $group_type */
      $field_name = 'groups_type_' . $group_type->id();
      $fields[$field_name] = BaseFieldDefinition::create('entity_reference')
        ->setName($field_name)
        ->setTargetEntityTypeId($entity_type->id())
        ->setSetting('target_type', 'group')
        ->setSetting('handler_settings', ['target_bundles' => [$group_type->id() => $group_type->id()]])
        ->setLabel(t('Get the related @type groups for this entity.', ['@type' => $group_type->label()]))
        ->setDescription(t('A list of all the groups referencing this entity.'))
        ->setTranslatable(FALSE)
        ->setComputed(TRUE)
        ->setClass('\Drupal\mymodule\Fields\MyModuleGroupReferenceItemList')
        ->setDisplayConfigurable('view', TRUE)
        ->setDisplayOptions('view', [
          'label' => 'above',
          'weight' => -5,
        ]);
    }
  }

  return $fields;
}

And the class:

<?php

namespace Drupal\mymodule\Fields;

use Drupal\Core\Field\EntityReferenceFieldItemList;
use Drupal\Core\Field\FieldItemListComputedInterface;
use Drupal\Core\TypedData\DataDefinitionInterface;
use Drupal\Core\TypedData\TypedDataInterface;

/**
 * A computed property for the related groups.
 */
class MyModuleGroupReferenceItemList extends EntityReferenceFieldItemList implements FieldItemListComputedInterface {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManager
   */
  protected $entityTypeManager;

  /**
   * Constructs a MyModuleGroupReferenceItemList object.
   *
   * @param \Drupal\Core\TypedData\DataDefinitionInterface $definition
   *   The data definition.
   * @param string $name
   *   (optional) The name of the created property, or NULL if it is the root
   *   of a typed data tree. Defaults to NULL.
   * @param \Drupal\Core\TypedData\TypedDataInterface $parent
   *   (optional) The parent object of the data property, or NULL if it is the
   *   root of a typed data tree. Defaults to NULL.
   */
  public function __construct(DataDefinitionInterface $definition, $name = NULL, TypedDataInterface $parent = NULL) {
    parent::__construct($definition, $name, $parent);
    $this->entityTypeManager = \Drupal::service('entity_type.manager');
  }

  /**
   * {@inheritdoc}
   */
  public function computeValue() {
    // We only support nodes and users.
    if ($this->getEntity()->getEntityTypeId() === 'node') {
      $plugin_id = 'group_node:' . $this->getEntity()->bundle();
    }
    elseif ($this->getEntity()->getEntityTypeId() === 'user') {
      $plugin_id = 'group_membership';
    }
    else {
      return NULL;
    }

    $handler_settings = $this->getItemDefinition()->getSetting('handler_settings');
    $group_types = isset($handler_settings['target_bundles']) ? $handler_settings['target_bundles'] : $this->entityTypeManager->getStorage('group_type')->loadMultiple();

    $group_content_types = $this->entityTypeManager->getStorage('group_content_type')->loadByProperties([
      'group_type' => array_keys($group_types),
      'content_plugin' => $plugin_id,
    ]);

    if (empty($group_content_types)) {
      return NULL;
    }

    $group_contents = $this->entityTypeManager->getStorage('group_content')->loadByProperties([
      'type' => array_keys($group_content_types),
      'entity_id' => $this->getEntity()->id(),
    ]);

    $this->list = [];
    if (!empty($group_contents)) {
      foreach ($group_contents as $delta => $group_content) {
        $this->list[] = $this->createItem($delta, [
          'target_id' => $group_content->gid->target_id,
        ]);
      }
    }
  }

}
kristiaanvandeneynde’s picture

If computed fields make it into core, I would definitely consider adding a backlink from groupable entities to their group.

realityloop’s picture

@SeanB This is good for existing nodes, but throws errors when creating new nodes.

The website encountered an unexpected error. Please try again later.

Drupal\Core\Database\InvalidQueryException: Query condition 'group_content_field_data.entity_id IN ()' cannot be empty. in Drupal\Core\Database\Query\Condition->condition() (line 71 of core/lib/Drupal/Core/Database/Query/Condition.php).

Drupal\Core\Database\Query\Select->condition('group_content_field_data.entity_id', Array, 'IN') (Line: 53)
Drupal\Core\Entity\Query\Sql\Condition->compile(Object) (Line: 155)
Drupal\Core\Entity\Query\Sql\Query->compile() (Line: 74)
Drupal\Core\Entity\Query\Sql\Query->execute() (Line: 503)
Drupal\Core\Entity\EntityStorageBase->loadByProperties(Array) (Line: 69)
Drupal\council_hubs\Fields\GroupReferenceItemList->computeValue() (Line: 201)
Drupal\Core\TypedData\TypedDataManager->getPropertyInstance(Object, 'groups', NULL) (Line: 74)
Drupal\Core\Field\FieldTypePluginManager->createFieldItemList(Object, 'groups', NULL) (Line: 488)
Drupal\Core\Entity\ContentEntityBase->getTranslatedField('groups', 'x-default') (Line: 452)
Drupal\Core\Entity\ContentEntityBase->get('groups') (Line: 523)
Drupal\Core\Entity\ContentEntityBase->getFields() (Line: 546)
Drupal\Core\Entity\ContentEntityBase->getIterator() (Line: 106)
Drupal\Core\Entity\ContentEntityStorageBase->initFieldValues(Object, Array) (Line: 88)
Drupal\Core\Entity\ContentEntityStorageBase->doCreate(Array) (Line: 184)
Drupal\Core\Entity\EntityStorageBase->create(Array) (Line: 330)
Drupal\group\Entity\Controller\GroupContentController->createForm(Object, 'group_node:page')
call_user_func_array(Array, Array) (Line: 123)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}() (Line: 574)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 124)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->wrapControllerExecutionInRenderContext(Array, Array) (Line: 97)
Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber->Drupal\Core\EventSubscriber\{closure}()
call_user_func_array(Object, Array) (Line: 144)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 64)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 60)
Drupal\shield\ShieldMiddleware->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 652)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

Offending code block:

    $group_contents = $this->entityTypeManager->getStorage('group_content')->loadByProperties([
      'type' => array_keys($group_content_types),
      'entity_id' => $this->getEntity()->id(),
    ]);
seanB’s picture

Yeah, if $this->getEntity()->id() is empty we should probably bail out directly.

adammalone’s picture

I've rolled the code in #19 along with recommendations from #22 into a patch for the group module. It seems to work fine at my end although would likely another review.

Status: Needs review » Needs work

The last submitted patch, 23: 2718195-add-computed-field.patch, failed testing.

realityloop’s picture

mparker17’s picture

The test failures in #26 occur because the test environment hasn't applied the patch in #2392845: Add a trait to standardize handling of computed item lists to Drupal core.

mparker17’s picture

Title: Add a computed field or pseudofield showing an entity's group(s) » [PP-1] Add a computed field or pseudofield showing an entity's group(s)
Issue summary: View changes
Status: Needs review » Postponed
Parent issue: » #2392845: Add a trait to standardize handling of computed item lists
Related issues: -#2392845: Add a trait to standardize handling of computed item lists

Updated the issue summary and hid older patches.

Since the module maintainer (@kristiaanvandeneynde) said in #20 that he wants to wait for #2392845: Add a trait to standardize handling of computed item lists to make it into core first, I've moved that issue to be a parent of this one, rather than simply a related issue, marking this issue as postponed, and updating the issue title accordingly.

If, for whatever reason, 2392845 does not make it into core, it may be wroth noting that the latest patch which does not depend on that patch is in #12.

mparker17’s picture

Issue summary: View changes

Updated the issue summary problem/motivation and proposed resolution with more information.

mparker17’s picture

Currently GroupGroupReferenceItemList extends EntityReferenceFieldItemList implements FieldItemListComputedInterface.

But it looks like FieldItemListComputedInterface was removed in #2392845-86: Add a trait to standardize handling of computed item lists in favor of an abstract base class named ComputedFieldItemListBase (see point #4 in @nuez's response) .

Since multiple inheritance isn't a thing in PHP do you think it would work if we modified GroupGroupReferenceItemList to extend ComputedFieldItemListBase and implement EntityReferenceFieldItemListInterface (i.e.: the interface that EntityReferenceFieldItemList implements), copying over methods from EntityReferenceFieldItemList and its ancestors? Or should we look for a different solution?

seanB’s picture

I believe the patch in [#12219727] should not be necessary. In 8.4 there is an example of a computed field in Drupal\content_moderation\Plugin\Field\ModerationStateFieldItemList. This doesn't need the patch. The base class proposed in the patch would make it easier, but this does not have to be blocked on that.

I guess this clears the path to add this in the module right now and just extend EntityReferenceFieldItemList.

Something like this should work (don't have time to test it, but just changed some working code I had somewhere as an example):

<?php

namespace Drupal\group\Fields;

use Drupal\Core\Field\EntityReferenceFieldItemList;

/**
 * A computed property for the related groups.
 */
class GroupReferenceItemList extends EntityReferenceFieldItemList {

  /**
   * {@inheritdoc}
   */
  public function get($index) {
    $this->computeValues();
    return isset($this->list[$index]) ? $this->list[$index] : NULL;
  }

  /**
   * {@inheritdoc}
   */
  public function referencedEntities() {
    $this->computeValues();
    return parent::referencedEntities();
  }

  /**
   * {@inheritdoc}
   */
  public function getIterator() {
    $this->computeValues();
    return parent::getIterator();
  }

  /**
   * Compute the field item list.
   */
  protected function computeValues() {
    // We only support nodes and users.
    if ($this->getEntity()->getEntityTypeId() === 'node') {
      $plugin_id = 'group_node:' . $this->getEntity()->bundle();
    }
    elseif ($this->getEntity()->getEntityTypeId() === 'user') {
      $plugin_id = 'group_membership';
    }
    else {
      return NULL;
    }

    $handler_settings = $this->getItemDefinition()
      ->getSetting('handler_settings');
    $group_types = isset($handler_settings['target_bundles']) ? $handler_settings['target_bundles'] : $this->entityTypeManager->getStorage('group_type')
      ->loadMultiple();

    $group_content_types = $this->entityTypeManager->getStorage('group_content_type')
      ->loadByProperties([
        'group_type' => array_keys($group_types),
        'content_plugin' => $plugin_id,
      ]);

    if (empty($group_content_types)) {
      return NULL;
    }

    $group_contents = $this->entityTypeManager->getStorage('group_content')
      ->loadByProperties([
        'type' => array_keys($group_content_types),
        'entity_id' => $this->getEntity()->id(),
      ]);

    if (!empty($group_contents)) {
      foreach ($group_contents as $delta => $group_content) {
        $this->list[] = $this->createItem($delta, [
          'target_id' => $group_content->gid->target_id,
        ]);
      }
    }
  }

}
seanB’s picture

Status: Postponed » Needs work

Back to needs work..

amateescu’s picture

I just posted a patch in #2392845-105: Add a trait to standardize handling of computed item lists that will be very helpful if the Group module can add a dependency on Drupal 8.4.x. The code from #31 will be reduced to the implementation of the computeValues() method.

recrit’s picture

Rolled #31 into a patch that can be used now without the need for Drupal\Core\Field\FieldItemListComputedInterface.

recrit’s picture

The attached #35 patch implements the isEmpty() method. I ran into the issue where search api would not index the field since it checks isEmpty() first.

kristiaanvandeneynde’s picture

I was following that issue amateescu, nice work there! We should definitely use that trait and up the version dependency to 8.4.x

recrit’s picture

Patch updates:
* Set cardinality to unlimited. This should be unlimited since its a single to multiple relationship. Search API would incorrectly index the field as a single value causing errors during indexing.

* By default, hide the fields from the view display. This should be the default so that it does not pollute displays of existing sites. An admin can opt-in to show the fields.

seanB’s picture

Awesome the computed trait from #2392845: Add a trait to standardize handling of computed item lists is in core now! Let's use that :)

jibran’s picture

Title: [PP-1] Add a computed field or pseudofield showing an entity's group(s) » Add a computed field or pseudofield showing an entity's group(s)
geek-merlin’s picture

OK, here we go! Patch flying in that
* leverages ComputedItemListTrait thus greatly simplifying the computed field
* enables the field's widget with a POC postSave() method that can trigger adding and deleting content/group relations. (for now it shows the selected IDs, tested)

kristiaanvandeneynde’s picture

Nice, thanks for working on this!

+++ b/group.module
@@ -201,6 +204,78 @@ function group_form_block_form_alter(&$form, FormStateInterface $form_state, $fo
+ * We currently only use this for nodes and users since they can be installed
+ * as group content.
+ */

You could perhaps load all GroupContentType entities and see which entity types are supported?

Also I'd like to see tests for any new functionality going in. Even if it's as simple as "yup, this node knows about the group it's in"

clemens.tolboom’s picture

Issue tags: +Needs tests
modestmoes’s picture

modestmoes’s picture

FileSize
5.73 KB
modestmoes’s picture

FileSize
3.37 KB
9.33 KB

Trying to re-roll this patch.

Made a patch working out how the postSave() from #40 could work

geek-merlin’s picture

Nice work! I did not test this but the code looks straightforward and well commented.

2 nits:
* I'd remove the _none option earlier in the code for more clarity.
* The code is not at all node specific so let's call it entity.

;-)

anruether’s picture

#45 works for me!

zenimagine’s picture

I applied the patch #45 and it works.

But I have some questions:

- Currently if I create a node, I have access to all groups. How to restrict to my own groups?

- The group field is not required. How to require the selection of a group?

- Currently the field allows to select several groups. How to limit it to a single group?

- In the TWIG of my type of node, I want to make the field group. What is the TWIG code to display the group in relation?

Thank you

zenimagine’s picture

- In the TWIG of my type of node, I want to make the field group. What is the TWIG code to display the group in relation?

I succeeded with the following code :

{{ content.groups }}

But in the module "Message" I tested the following token and it does not work. There is no group field in the token.

[message:field_node_reference:entity:groups]

zenimagine’s picture

It would be nice to do like "Drupal Commerce".

Create a true lock field for groups.

anruether’s picture

Just to inform those who worked on the patch in this issue: There is ongoing work on another patch with similar functionality in #2813405: Adding Content Relationships Outside of Groups.

From what I understand with a different approach and a bit different functionality.

geek-merlin’s picture

I have looked into all 3 dup issues and propose to move some of this code to #2813405-46: Add a field to view and edit content's groups - see my comment there.

jidrone’s picture

Hi everyone,

I also propose to close this as duplicated in favor of #2813405: Add a field to view and edit content's groups, that one now have the computed field approach and provides a more complete solution.

anruether’s picture

Status: Needs work » Closed (duplicate)
Issue tags: -Needs tests

Let's do it.

scuba_fly’s picture

+++ b/src/Fields/GroupGroupReferenceItemList.php
@@ -0,0 +1,165 @@
+    // No value will exist if the entity has not been created so exit early.:wq

I know this is closed duplicate, but I just noticed this in the patch.
:wq

Henry Tran’s picture

I've rerolled #45 to 8.x-1.x

Henry Tran’s picture

FileSize
9.1 KB

Sorry #65 does not work correctly, I've re uploaded.
Thanks

clemens.tolboom’s picture

@tvhung this issue was closed as a duplicate of #2813405: Add a field to view and edit content's groups so your patch will not be reviewed.

Henry Tran’s picture

FileSize
9.11 KB

I've rerolled to drupal 9 compatibly.

hitesh-jain’s picture

Fixed issue for empty computed field value.

Added below condition to GroupGroupReferenceItemList -> postSave method

if (empty($gids_wanted)) {
   return parent::postSave($update);
}
hitesh-jain’s picture

Fix patch number.

lexhouk’s picture

Extend patch from #59 by adding a possibility to support different entity types.

anruether’s picture

@chmez and @hitesh-jain please note that most people won't see this anymore, because this issue is closed. The most recent (and robust) approach is worked on in a dedicated module now: https://www.drupal.org/project/entitygroupfield It would be great to join forces over there.

lexhouk’s picture

@anruether thanks for the info. The last patch was created just like a workaround for Open Social but in future, we definitely should switch to a solution from a related issue or the suggested module.

lexhouk’s picture

FileSize
11.28 KB

Define content plugin based on the entity type.