Skip to content
Closed
Show file tree
Hide file tree
Changes from 11 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 105 additions & 1 deletion src/OgGroupAudienceHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,16 @@
namespace Drupal\og;

use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldException;
use Drupal\Core\Field\FieldFilteredMarkup;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\field\Entity\FieldConfig;
use Drupal\og\Plugin\Field\FieldWidget\OgComplex;
use Drupal\Component\Utility\Html;

/**
* OG audience field helper methods.
Expand Down Expand Up @@ -111,4 +118,101 @@ public static function getMatchingField(ContentEntityInterface $entity, $group_t
return NULL;
}

/**
* Get list of available widgets.
*
* @return array
* List of available entity reference widgets.
*/
public static function getAvailableWidgets() {
$widget_manager = \Drupal::getContainer()->get('plugin.manager.field.widget');
$definitions = $widget_manager->getDefinitions();

$widgets = [];
foreach ($definitions as $id => $definition) {

if (!in_array('entity_reference', $definition['field_types'])) {
continue;
}

$widgets[] = $id;
}

return $widgets;
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's the reason for splitting this off as static methods in OgGroupAudienceHelper? Are you planning on reusing them somewhere else?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes - we would like to get all the available widget so the user could pick them through the UI. No?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK!

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Way to go! That's the spirit!


/**
* Set the field mode widget.
*
* @param $entity_id
* The entity id.
* @param $bundle
* The bundle.
* @param $field_name
* The field name.
* @param array $modes
* The field modes. Available keys: default, admin.
*
* @return int
* Either SAVED_NEW or SAVED_UPDATED, depending on the operation performed.
*/
public static function setWidgets($entity_id, $bundle, $field_name, array $modes) {
$field = FieldConfig::loadByName($entity_id, $bundle, $field_name);
$handler = $field->getSetting('handler_settings');
$handler['handler_settings']['widgets'] = $modes;
$field->setSetting('handler_settings', $handler);
return $field->save();
}

/**
* get the field mode widget.
*
* @param $entity_id
* The entity id.
* @param $bundle
* The bundle.
* @param $field_name
* The field name.
* @param null $mode
* The field mode - admin or default.
*
* @return array.
* The field modes.
*/
public static function getWidgets($entity_id, $bundle, $field_name, $mode = NULL) {
$field = FieldConfig::loadByName($entity_id, $bundle, $field_name);
$handler = $field->getSetting('handler_settings');
return $mode ? $handler['handler_settings']['widgets'][$mode] : $handler['handler_settings']['widgets'];
}

/**
* @param FieldDefinitionInterface $field
* The field definition.
* @param $widget_id
* An entity reference widget plugin id i.e: options_select, options_buttons.
* @param string $field_name
* The field name. Default to self::DEFAULT_FIELD.
* @param array $configuration
* Configuration which will be passed to the widget instance.
*
* @return WidgetBase The form API widget element.
* The form API widget element.
*/
public static function renderWidget(FieldDefinitionInterface $field, $widget_id, $field_name = self::DEFAULT_FIELD, array $configuration = []) {
$config = FieldConfig::load($field->getTargetEntityTypeId() . '.' . $field->getTargetBundle() . '.' . $field_name);

$default_configuration = $configuration + [
'type' => 'og_complex',
'settings' => [
'match_operator' => 'CONTAINS',
'size' => 60,
'placeholder' => '',
],
'third_party_settings' => [],
'field_definition' => $config,
];

return \Drupal::getContainer()->get('plugin.manager.field.widget')->createInstance($widget_id, $default_configuration);
}

}
137 changes: 33 additions & 104 deletions src/Plugin/Field/FieldWidget/OgComplex.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,16 @@

use Drupal\Component\Utility\Html;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldFilteredMarkup;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteTagsWidget;
use Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget;
use Drupal\Core\Form\FormStateInterface;
use Drupal\og\Og;
use Drupal\og\OgAccess;
use Drupal\og\OgGroupAudienceHelper;
use Drupal\user\Entity\User;

/**
Expand Down Expand Up @@ -70,120 +73,46 @@ public function form(FieldItemListInterface $items, array &$form, FormStateInter
* - table display and drag-n-drop value reordering
*/
protected function formMultipleElements(FieldItemListInterface $items, array &$form, FormStateInterface $form_state) {
$field_name = $this->fieldDefinition->getName();
$cardinality = $this->fieldDefinition->getFieldStorageDefinition()->getCardinality();
$parents = $form['#parents'];
$multiple = parent::formMultipleElements($items, $form, $form_state);

$target_type = $this->fieldDefinition->getTargetEntityTypeId();
$user_groups = Og::getEntityGroups(User::load(\Drupal::currentUser()->id()));
$user_groups_target_type = isset($user_groups[$target_type]) ? $user_groups[$target_type] : [];
$user_group_ids = array_map(function($group) {
return $group->id();
}, $user_groups_target_type);
$widget_id = OgGroupAudienceHelper::getWidgets(
$this->fieldDefinition->getTargetEntityTypeId(),
$this->fieldDefinition->getTargetBundle(),
$this->fieldDefinition->getName(),
'default'
);

// Determine the number of widgets to display.
switch ($cardinality) {
case FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED:
$field_state = static::getWidgetState($parents, $field_name, $form_state);
$max = $field_state['items_count'];
$is_multiple = TRUE;
break;

default:
$max = $cardinality - 1;
$is_multiple = ($cardinality > 1);
break;
}
$handler = OgGroupAudienceHelper::renderWidget($this->fieldDefinition, $widget_id);

$title = $this->fieldDefinition->getLabel();
$description = FieldFilteredMarkup::create(\Drupal::token()->replace($this->fieldDefinition->getDescription()));
if ($handler instanceof EntityReferenceAutocompleteWidget) {
// No need for extra work here since we already extending the auto
// complete handler.
return $multiple;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

}

$elements = array();
// Change the functionality of the original handler and call the other
// handlers.
$cardinality = $this->fieldDefinition->getFieldStorageDefinition()->getCardinality();

for ($delta = 0; $delta <= $max; $delta++) {
// Add a new empty item if it doesn't exist yet at this delta.
if (!isset($items[$delta])) {
$items->appendItem();
}
elseif (!in_array($items[$delta]->get('target_id')->getValue(), $user_group_ids)) {
continue;
}
$element = [
'#required' => $this->fieldDefinition->isRequired(),
'#multiple' => $cardinality !== 1,
'#title' => $this->fieldDefinition->getLabel(),
'#description' => FieldFilteredMarkup::create(\Drupal::token()->replace($this->fieldDefinition->getDescription())),
];

// For multiple fields, title and description are handled by the wrapping
// table.
if ($is_multiple) {
$element = [
'#title' => $this->t('@title (value @number)', ['@title' => $title, '@number' => $delta + 1]),
'#title_display' => 'invisible',
'#description' => '',
];
}
else {
$element = [
'#title' => $title,
'#title_display' => 'before',
'#description' => $description,
];
}
$widget = $handler->formElement($items, 0, $element, $form, $form_state);

$element = $this->formSingleElement($items, $delta, $element, $form, $form_state);

if ($element) {
// Input field for the delta (drag-n-drop reordering).
if ($is_multiple) {
// We name the element '_weight' to avoid clashing with elements
// defined by widget.
$element['_weight'] = array(
'#type' => 'weight',
'#title' => $this->t('Weight for row @number', array('@number' => $delta + 1)),
'#title_display' => 'invisible',
// Note: this 'delta' is the FAPI #type 'weight' element's property.
'#delta' => $max,
'#default_value' => $items[$delta]->_weight ?: $delta,
'#weight' => 100,
);
}

$elements[$delta] = $element;
}
if ($handler instanceof EntityReferenceAutocompleteTagsWidget) {
// The auto complete tags widget return the form element wrapped in
// 'target_id' key. If the element won't be extracted the selected groups
// will not processed correct.
$widget = $widget['target_id'];
}

if ($elements) {
$elements += array(
'#theme' => 'field_multiple_value_form',
'#field_name' => $field_name,
'#cardinality' => $cardinality,
'#cardinality_multiple' => $this->fieldDefinition->getFieldStorageDefinition()->isMultiple(),
'#required' => $this->fieldDefinition->isRequired(),
'#title' => $title,
'#description' => $description,
'#max_delta' => $max,
);

// Add 'add more' button, if not working with a programmed form.
if ($cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED && !$form_state->isProgrammed()) {
$id_prefix = implode('-', array_merge($parents, array($field_name)));
$wrapper_id = Html::getUniqueId($id_prefix . '-add-more-wrapper');
$elements['#prefix'] = '<div id="' . $wrapper_id . '">';
$elements['#suffix'] = '</div>';

$elements['add_more'] = array(
'#type' => 'submit',
'#name' => strtr($id_prefix, '-', '_') . '_add_more',
'#value' => t('Add another item'),
'#attributes' => array('class' => array('field-add-more-submit')),
'#limit_validation_errors' => array(array_merge($parents, array($field_name))),
'#submit' => array(array(get_class($this), 'addMoreSubmit')),
'#ajax' => array(
'callback' => array(get_class($this), 'addMoreAjax'),
'wrapper' => $wrapper_id,
'effect' => 'fade',
),
);
}
}
$widget = $widget + $element;

return $elements;
return [$widget];
}

/**
Expand Down