ultimate_table_field-1.0.0-alpha5/src/Plugin/Field/FieldWidget/UltimateTableFieldWidget.php
src/Plugin/Field/FieldWidget/UltimateTableFieldWidget.php
<?php
namespace Drupal\ultimate_table_field\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Plugin implementation of the ultimate table field widget.
*
* @FieldWidget(
* id = "ultimate_table",
* label = @Translation("Ultimate table"),
* description = @Translation("Ultimate table default widget."),
* field_types = {
* "ultimate_table"
* }
* )
*/
class UltimateTableFieldWidget extends WidgetBase {
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$table_data = $items[$delta];
$default_value = $table_data->value ?? [];
if (!empty($default_value)) {
$default_value = ['values' => $default_value];
}
$allowed_value = $this->getFieldSetting('allowed_types') ?? [];
$allowed_value = array_filter($allowed_value);
$element += [
'#type' => 'ultimate_table',
'#tree' => TRUE,
'#allowed_types' => array_values($allowed_value),
'#default_value' => $default_value,
'#enable_legend' => $this->getFieldSetting('enable_legend'),
'#enable_summary' => $this->getFieldSetting('enable_summary'),
];
return $element;
}
/**
* {@inheritDoc}
*/
public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
$values = !empty($values) ? array_map(fn($value) => $value['values'], $values) : [];
foreach ($values as &$value) {
$value = ['value' => $value];
}
return $values;
}
}
