View source
<?php
namespace Drupal\panelizer\Plugin\Field\FieldWidget;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
class PanelizerWidget extends WidgetBase {
public function getPanelsManager() {
return \Drupal::service('panels.display_manager');
}
public function getPanelizerManager() {
return \Drupal::service('plugin.manager.panelizer_entity');
}
public function getPanelizer() {
return \Drupal::service('panelizer');
}
public function getEntityDisplayRepository() {
return \Drupal::service('entity_display.repository');
}
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$entity = $items
->getEntity();
$entity_type_id = $entity
->getEntityTypeId();
$entity_view_modes = $this
->getEntityDisplayRepository()
->getViewModes($entity_type_id);
$values = [];
foreach ($items as $item) {
$values[$item->view_mode] = [
'default' => $item->default,
'panels_display' => $item->panels_display,
];
}
$displays = [];
foreach ($entity_view_modes as $view_mode => $view_mode_info) {
$display = EntityViewDisplay::collectRenderDisplay($entity, $view_mode);
$displays[$view_mode] = $display
->getThirdPartySetting('panelizer', 'displays', []);
if (!isset($values[$view_mode]) || $values[$view_mode]['default'] == '__bundle_default__' && empty($values[$view_mode]['panels_display'])) {
if ($display
->getThirdPartySetting('panelizer', 'enable', FALSE)) {
$values[$view_mode] = [
'default' => '__bundle_default__',
'panels_display' => [],
];
}
}
}
$delta = 0;
foreach ($values as $view_mode => $value) {
$element[$delta]['view_mode'] = [
'#type' => 'value',
'#value' => $view_mode,
];
$settings = $this
->getPanelizer()
->getPanelizerSettings($entity_type_id, $entity
->bundle(), $view_mode);
if (!empty($settings['allow'])) {
$options = [
'__bundle_default__' => $this
->t('Current default display'),
];
foreach ($displays[$view_mode] as $machine_name => $panels_display) {
$options[$machine_name] = $panels_display['label'];
}
$element[$delta]['default'] = [
'#title' => $entity_view_modes[$view_mode]['label'],
'#type' => 'select',
'#options' => $options,
'#default_value' => $value['default'],
];
if (!empty($value['panels_display'])) {
$element[$delta]['default']['#disabled'] = TRUE;
$element[$delta]['default']['#options'][$value['default']] = $this
->t('Custom Override');
}
}
else {
$element[$delta]['default'] = [
'#type' => 'value',
'#value' => $value['default'],
];
}
$element[$delta]['panels_display'] = [
'#type' => 'value',
'#value' => $value['panels_display'],
];
$delta++;
}
return $element;
}
}