Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Build a new taxonomy hierarchy widget with parents as field labels #51

Merged
merged 7 commits into from
Sep 4, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 4 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,16 @@
}
],
"require": {
"drupal/core": "^9 || ^10 || ^11",
"drupal/core": "^10.2 || ^11",
"drupal/ds": "~3.3 || ^5.0@alpha",
"drupal/book": "^1.0"
},
"autoload-dev": {
"psr-4": {
"Drupal\\Tests\\stanford_fields\\": "./tests/src"
}
},
"require-dev": {
"drupal/cshs": "^4.0"
}
}
20 changes: 11 additions & 9 deletions src/Plugin/Block/BookForwardBackBlock.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,25 @@

namespace Drupal\stanford_fields\Plugin\Block;

use Drupal\Core\Block\Attribute\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\Context\EntityContextDefinition;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
* Provides a 'Book navigation' block.
*
* @Block(
* id = "book_forward_back",
* admin_label = @Translation("Book Forward & Back"),
* category = @Translation("Book"),
* context_definitions = {
* "node" = @ContextDefinition("entity:node", label = @Translation("Node"), required = FALSE)
* }
* )
*/
#[Block(
id: "book_forward_back",
admin_label: new TranslatableMarkup("Book Forward & Back"),
category: new TranslatableMarkup("Book"),
context_definitions: [
'node' => new EntityContextDefinition(data_type: 'entity:node', label: new TranslatableMarkup("Node"), required: FALSE),
]
)]
class BookForwardBackBlock extends BlockBase implements ContainerFactoryPluginInterface {

/**
Expand Down
15 changes: 7 additions & 8 deletions src/Plugin/Field/FieldFormatter/EntityTitleHeading.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,25 @@

namespace Drupal\stanford_fields\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\Attribute\FieldFormatter;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Drupal\Core\Path\PathMatcherInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
* Provide a string field to be used as a heading.
*
* @FieldFormatter(
* id = "entity_title_heading",
* label = @Translation("Heading"),
* field_types = {
* "string"
* }
* )
*/
#[FieldFormatter(
id: 'entity_title_heading',
label: new TranslatableMarkup('Heading'),
field_types: ['string'],
)]
class EntityTitleHeading extends FormatterBase implements ContainerFactoryPluginInterface {

/**
Expand Down
15 changes: 7 additions & 8 deletions src/Plugin/Field/FieldWidget/DateYearOnlyWidget.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,20 @@

namespace Drupal\stanford_fields\Plugin\Field\FieldWidget;

use Drupal\Core\Field\Attribute\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\datetime\Plugin\Field\FieldWidget\DateTimeDatelistWidget;

/**
* Plugin to provide a date widget that only collects the year.
*
* @FieldWidget(
* id = "datetime_year_only",
* label = @Translation("Year Only"),
* field_types = {
* "datetime"
* }
* )
*/
#[FieldWidget(
id: 'datetime_year_only',
label: new TranslatableMarkup('Year Only'),
field_types: ['datetime'],
)]
class DateYearOnlyWidget extends DateTimeDatelistWidget {

/**
Expand Down
15 changes: 7 additions & 8 deletions src/Plugin/Field/FieldWidget/LocalistUrlWidget.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Field\Attribute\FieldWidget;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\Url as UrlElement;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
use Drupal\link\Plugin\Field\FieldWidget\LinkWidget;
use GuzzleHttp\ClientInterface;
Expand All @@ -17,15 +19,12 @@

/**
* Plugin implementation of the 'localist_url' widget.
*
* @FieldWidget(
* id = "localist_url",
* label = @Translation("Localist"),
* field_types = {
* "link"
* }
* )
*/
#[FieldWidget(
id: 'localist_url',
label: new TranslatableMarkup('Localist URL'),
field_types: ['link'],
)]
class LocalistUrlWidget extends LinkWidget {

/**
Expand Down
152 changes: 152 additions & 0 deletions src/Plugin/Field/FieldWidget/TaxonomyLabelHierarchyWidget.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
<?php

declare(strict_types=1);

namespace Drupal\stanford_fields\Plugin\Field\FieldWidget;

use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Field\Attribute\FieldWidget;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\OptionsWidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\cshs\Component\CshsOption;
use Drupal\cshs\Element\CshsElement;

/**
* Defines the 'taxonomy_label_hierarchy' field widget.
*/
#[FieldWidget(
id: 'taxonomy_label_hierarchy',
label: new TranslatableMarkup('Taxonomy Label Hierarchy'),
field_types: ['entity_reference'],
multiple_values: TRUE,
)]
final class TaxonomyLabelHierarchyWidget extends OptionsWidgetBase {

/**
* {@inheritDoc}
*/
public static function isApplicable(FieldDefinitionInterface $field_definition) {
// Make sure the CSHS module is available.
return \Drupal::moduleHandler()->moduleExists('cshs');
}

/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state): array {
$element = parent::formElement($items, $delta, $element, $form, $form_state);
$options = $this->getOptions($items->getEntity());
$selected_items = $this->getSelectedOptions($items);

$element += [
'#type' => 'fieldset',
'#tree' => TRUE,
];

$grouped_options = [];
foreach ($options as $id => $option) {
if (!str_starts_with((string) $option, '-')) {
$parent = (string) $option;
continue;
}
$grouped_options[$parent][$id] = substr((string) $option, 1);
}

foreach ($grouped_options as $group_label => $group_options) {
$key = preg_replace('@[^a-z0-9_.]+@', '_', mb_strtolower($group_label));
foreach ($group_options as $tid => &$option) {
/** @var \Drupal\taxonomy\TermInterface $term */
$term = \Drupal::entityTypeManager()
->getStorage('taxonomy_term')
->load($tid);
$option = new CshsOption(ltrim($option, "-"), $term->get('parent')
->getString(), $group_label);
}

$num_values = $form_state->get($key);
$default_values = array_values(array_intersect($selected_items, array_keys($group_options)));

if (!$num_values) {
$num_values = max(1, count($default_values));
$form_state->set($key, $num_values);
}

$element[$key] = [
'#type' => 'fieldset',
'#title' => $group_label,
'#prefix' => '<div id="' . $key . '">',
'#suffix' => '</div>',
];

for ($i = 0; $i < $num_values; $i++) {
$element[$key][$i]['target_id'] = [
'#type' => CshsElement::ID,
'#labels' => [],
'#options' => $group_options,
'#multiple' => $this->multiple,
'#default_value' => $default_values[$i] ?? NULL,
];
}
$element[$key]['add'] = [
'#type' => 'submit',
'#value' => $this->t('Add More'),
'#name' => $key,
'#submit' => [[self::class, 'addOne']],
'#limit_validation_errors' => [],
'#ajax' => [
'callback' => [self::class, 'addMoreCallback'],
'wrapper' => $key,
],
];
}

return $element;
}

/**
* Ajax callback to add another.
*
* @codeCoverageIgnore
*/
public static function addMoreCallback(array &$form, FormStateInterface $form_state) {
$trigger = $form_state->getTriggeringElement();
$path = $trigger['#array_parents'];
array_pop($path);
return NestedArray::getValue($form, $path);
}

/**
* Form callback to add another.
*
* @codeCoverageIgnore
*/
public static function addOne(array &$form, FormStateInterface $form_state) {
$trigger = $form_state->getTriggeringElement();
$name = $trigger['#name'];
$form_state->set($name, $form_state->get($name) + 1);
$form_state->setRebuild();
}

/**
* {@inheritdoc}
*
* @codeCoverageIgnore
*/
public static function validateElement(array $element, FormStateInterface $form_state) {
$value = [];
foreach (Element::children($element) as $key) {
foreach (Element::children($element[$key]) as $delta) {
if (isset($element[$key][$delta]['target_id']['#value']) && is_array($element[$key][$delta]['target_id']['#value'])) {
$value[] = end($element[$key][$delta]['target_id']['#value']);
}
}
}
$element['#value'] = array_filter(array_unique($value));
parent::validateElement($element, $form_state);
}

}
23 changes: 12 additions & 11 deletions src/Plugin/views/display/ViewFieldBlock.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,28 @@

namespace Drupal\stanford_fields\Plugin\views\display;

use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\views\Attribute\ViewsDisplay;
use Drupal\views\Plugin\views\display\Block;

/**
* The plugin that handles a block.
*
* @ingroup views_display_plugins
*
* @ViewsDisplay(
* id = "viewfield_block",
* title = @Translation("View Field Block"),
* help = @Translation("Identical to a block, but allows for granular viewfield settings."),
* theme = "views_view",
* register_theme = FALSE,
* uses_hook_block = TRUE,
* contextual_links_locations = {"block"},
* admin = @Translation("Block")
* )
*
* @see \Drupal\views\Plugin\Block\ViewsBlock
* @see \Drupal\views\Plugin\Derivative\ViewsBlock
*/
#[ViewsDisplay(
id: "viewfield_block",
title: new TranslatableMarkup("View Field Block"),
admin: new TranslatableMarkup("Block"),
help: new TranslatableMarkup("Identical to a block, but allows for granular viewfield settings."),
theme: "views_view",
contextual_links_locations: ["block"],
register_theme: FALSE,
uses_hook_block: TRUE,
)]
class ViewFieldBlock extends Block {

/**
Expand Down
2 changes: 1 addition & 1 deletion stanford_fields.info.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name: 'Stanford Fields'
type: module
description: 'Field types, widgets and formatters to enhance Drupal and Contrib.'
core_version_requirement: ^9 || ^10 || ^11
core_version_requirement: ^10.2 || ^11
package: Stanford
version: 8.2.7
dependencies:
Expand Down
Loading
Loading