Commit 5e49de6f authored by casey's avatar casey Committed by marcvangend

Issue #2513246 by casey, tedbow, marcvangend: New approach for fields as block, first iteration

parent 71aac1fb
<?php
///**
// * Implements hook_uninstall().
// */
//function fieldblock_uninstall() {
// // Delete variables.
// $entities = entity_get_info();
// // Loop over the entity types.
// foreach ($entities as $entity_type => $entity_info) {
// // Loop over each entity type's bundles.
// foreach ($entity_info['bundles'] as $bundle => $bundle_info) {
// $view_modes = field_view_mode_settings($entity_type, $bundle);
// // Treat the default settings as a real view mode with custom settings.
// $view_modes['default']['custom_settings'] = true;
// // Loop over the bundle's view modes.
// foreach ($view_modes as $view_mode => $view_mode_info) {
// // Delete the variable, if it exists.
// $variable_name = 'fieldblock-'. $entity_type .'-'. $bundle .'-'. $view_mode;
// variable_del($variable_name);
// }
// }
// }
//}
//
///**
// * Legacy helper function to undo drupal core schema alter.
// */
//function _fieldblock_db_alter_block_delta_length($length) {
// // Alter block table.
// db_drop_unique_key('block', 'tmd');
// db_change_field('block', 'delta', 'delta',
// array(
// 'type' => 'varchar',
// 'length' => $length,
// 'not null' => TRUE,
// 'default' => '0',
// 'description' => 'Unique ID for block within a module.',
// ),
// array(
// 'unique keys' => array(
// 'tmd' => array('theme', 'module', 'delta'),
// )
// )
// );
//
// // Alter block_role table.
// db_drop_primary_key('block_role');
// db_change_field('block_role', 'delta', 'delta',
// array(
// 'type' => 'varchar',
// 'length' => $length,
// 'not null' => TRUE,
// 'description' => "The block's unique delta within module, from {block}.delta.",
// ),
// array(
// 'primary key' => array('module', 'delta', 'rid'),
// )
// );
//
// // Alter block_node_type table.
// db_drop_primary_key('block_node_type');
// db_change_field('block_node_type', 'delta', 'delta',
// array(
// 'type' => 'varchar',
// 'length' => $length,
// 'not null' => TRUE,
// 'description' => "The block's unique delta within module, from {block}.delta.",
// ),
// array(
// 'primary key' => array('module', 'delta', 'type'),
// )
// );
//}
//
///**
// * Update legacy fieldblock deltas to use md5 identifier.
// * Reset drupal core block schema.
// */
//function fieldblock_update_7100() {
// $blocks = db_query("SELECT bid, delta FROM {block} WHERE module = 'fieldblock'");
// foreach ($blocks as $block) {
// db_query("UPDATE {block} SET delta = :new_delta WHERE bid = :bid AND delta = :old_delta AND module = 'fieldblock'", array(':new_delta' => md5($block->delta), ':bid' => $block->bid, ':old_delta' => $block->delta));
// }
// _fieldblock_db_alter_block_delta_length(32);
//}
<?php
/**
* @file
* Allow fields to be rendered in blocks.
*/
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
/**
* Implements hook_form_alter().
*
* Adds a column to the "display fields" table-form, with a checkbox for each
* field.
*/
function fieldblock_form_field_ui_display_overview_form_alter(&$form, FormStateInterface &$form_state, $form_id) {
$entity_type = $form['#entity_type'];
$bundle = $form['#bundle'];
$mode = $form['#mode'];
/** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $entity_view_display */
$entity_view_display = EntityViewDisplay::load($entity_type . '.' . $bundle . '.' . $mode);
// Add a column header.
$form['fields']['#header'][] = t('Display as block');
// Add checkboxes.
$field_names = array_merge($form['#fields'], $form['#extra']);
foreach ($field_names as $field_name) {
$form['fields'][$field_name]['fieldblock'] = array(
'#type' => 'checkbox',
'#default_value' => $entity_view_display->getThirdPartySetting('fieldblock', $field_name) ? true : false,
'#title' => '',
);
}
// Add a submit handler.
$form['#submit'][] = 'fieldblock_field_display_submit';
}
/**
* Form submit handler for field_ui_display_overview_form.
* Stores which fields are published as blocks as a third_party_settings array
* in the EntityViewDisplay object of the entity type / bundle / view mode.
*
* @param mixed[] $form
* A form API array.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The state of the submitted form.
*/
function fieldblock_field_display_submit($form, FormStateInterface $form_state) {
$entity_type = $form['#entity_type'];
$bundle = $form['#bundle'];
$mode = $form['#mode'];
/** @var \Drupal\Core\Entity\Display\EntityViewDisplayInterface $entity_view_display */
$entity_view_display = EntityViewDisplay::load($entity_type . '.' . $bundle . '.' . $mode);
$fields = $form_state->getValue('fields');
foreach ($fields as $field_name => $field) {
if (isset($field['fieldblock']) && $field['fieldblock'] == 1) {
$entity_view_display->setThirdPartySetting('fieldblock', $field_name, $form['fields'][$field_name]['human_name']['#markup']);
}
else if ($entity_view_display->getThirdPartySetting('fieldblock', $field_name)) {
$entity_view_display->unsetThirdPartySetting('fieldblock', $field_name);
}
}
$entity_view_display->save();
// Invalidate the block cache to update fielblock derivatives.
if (\Drupal::moduleHandler()->moduleExists('block')) {
\Drupal::service('plugin.manager.block')->clearCachedDefinitions();
}
}
/**
* Implements hook_entity_view_alter().
*
* Takes fields out of the current entity and caches them in a post render cache
* context. The #post_render_cache callback makes this data available to the
* fieldblock when it is built, We also hide the field from the render array.
*
* @param array &$build
* A renderable array representing the entity content.
* @param \Drupal\Core\Entity\EntityInterface $entity
* The entity object being rendered. Not used in this implementation.
* @param \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display
* The entity view display holding the display options configured for the
* entity components.
*
* @see \Drupal\fieldblock\Plugin\Block\FieldBlock::fieldBlockPostRenderCache
* @see https://www.drupal.org/node/2151609
*/
function fieldblock_entity_view_alter(array &$build, $entity, EntityViewDisplayInterface $display) {
$fieldblock_settings = $display->getThirdPartySettings('fieldblock');
$display_id = $display->get('id');
foreach ($fieldblock_settings as $field_name => $field_label) {
$fieldblock_id = $display_id . ':' . $field_name;
if (count(\Drupal\Core\Render\Element::children($build[$field_name]))) {
// This is where we take out the field and cache it in a post render
// cache context.
$build['#post_render_cache']['Drupal\fieldblock\Plugin\Block\FieldBlock::fieldBlockPostRenderCache'][] = array(
'build' => $build[$field_name],
'fieldblock_id' => $fieldblock_id,
);
hide($build[$field_name]);
}
}
}
# Schema for the configuration files of the Field as Block module.
block.settings.fieldblock:*:
type: block_settings
label: 'Field as Block'
mapping:
label_from_field:
type: boolean
lable: 'Use field label as block title'
field_name:
type: string
label: 'Field name'
formatter_id:
type: string
label: 'Format type machine name'
formatter_settings:
type: field.formatter.settings.[%parent.formatter_id]
label: 'Settings'
This diff is collapsed.
<?php
/**
* @file
* Contains \Drupal\fieldblock\Plugin\Derivative\FieldBlock.
*/
namespace Drupal\fieldblock\Plugin\Derivative;
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides block plugin definitions for fieldblock blocks.
*
* @see \Drupal\fieldblock\Plugin\Block\FieldBlock
*/
class FieldBlock extends DeriverBase implements ContainerDeriverInterface {
use StringTranslationTrait;
/**
* The entity view display storage.
*
* @var \Drupal\Core\Entity\EntityStorageInterface
*/
protected $entityViewDisplayStorage;
/**
* Constructs a FieldBlock deriver object.
*
* @param \Drupal\Core\Entity\Entity\EntityViewDisplay $entity_view_display
* The entity view display storage.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation.
*/
public function __construct($entity_view_display, TranslationInterface $string_translation) {
$this->entityViewDisplayStorage = $entity_view_display;
$this->stringTranslation = $string_translation;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $base_plugin_id) {
/** @var EntityManagerInterface $entity_manager */
$entity_manager = $container->get('entity.manager');
return new static(
$entity_manager->getStorage('entity_view_display'),
$container->get('string_translation')
);
}
/**
* {@inheritdoc}
*/
public function getDerivativeDefinitions($base_plugin_definition) {
$blocks = $this->fieldBlockGetBlockList();
foreach ($blocks as $fieldblock_id => $description) {
$this->derivatives[$fieldblock_id] = $base_plugin_definition;
$this->derivatives[$fieldblock_id]['admin_label'] = $description;
}
return $this->derivatives;
}
/**
* Builds a list of fields that have been made available as a block.
*
* @return string[]
* An array of fieldblocks in the form of fieldblock_id => admin label.
*/
protected function fieldBlockGetBlockList() {
$fieldblocks = array();
// Get all EntityViewDisplay config entities and iterate over them.
$entity_view_displays = $this->entityViewDisplayStorage->loadMultiple();
/** @var \Drupal\Core\Entity\EntityDisplayModeInterface $entity_view_display */
foreach ($entity_view_displays as $display_id => $entity_view_display) {
$view_display_fieldblocks = $entity_view_display->getThirdPartySettings('fieldblock');
$entity_type = $entity_view_display->get('targetEntityType');
$bundle = $entity_view_display->get('bundle');
$mode = $entity_view_display->get('mode');
foreach ($view_display_fieldblocks as $field_name => $field_label) {
$fieldblock_id = $display_id . ':' . $field_name;
$fieldblocks[$fieldblock_id] = $this->t('@field field (from @type: @bundle: @mode)', array(
'@field' => $field_label,
'@type' => $entity_type,
'@bundle' => $bundle,
'@mode' => $mode,
));
}
}
return $fieldblocks;
}
}
<?php
/**
* @file
* Contains \Drupal\fieldblock\Plugin\Derivative\FieldBlockDeriver.
*/
namespace Drupal\fieldblock\Plugin\Derivative;
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Entity\ContentEntityTypeInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides block plugin definitions for fieldblock blocks.
*
* @see \Drupal\fieldblock\Plugin\Block\FieldBlock
*/
class FieldBlockDeriver extends DeriverBase implements ContainerDeriverInterface {
use StringTranslationTrait;
/**
* The entity manager.
*
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* Constructs a FieldBlockDeriver object.
*
* @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
* The entity manager.
*/
public function __construct(EntityManagerInterface $entity_manager) {
$this->entityManager = $entity_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $base_plugin_id) {
return new static(
$container->get('entity.manager')
);
}
/**
* {@inheritdoc}
*/
public function getDerivativeDefinitions($base_plugin_definition) {
$definitions = $this->entityManager->getDefinitions();
foreach ($definitions as $entity_type_id => $definition) {
if ($definition instanceof ContentEntityTypeInterface) {
$this->derivatives[$entity_type_id] = $base_plugin_definition;
$this->derivatives[$entity_type_id]['admin_label'] = $this->t('@type field', [
'@type' => $definition->getLabel(),
]);
}
}
return $this->derivatives;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment