Skip to content
Snippets Groups Projects

Add image-style config

Compare and
2 files
+ 261
2
Compare changes
  • Side-by-side
  • Inline
Files
2
@@ -3,6 +3,8 @@
namespace Drupal\custom_elements\Plugin\CustomElementsFieldFormatter;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\custom_elements\CustomElementsImageStyleConfigTrait;
/**
* Implementation of the 'file' custom element formatter plugin.
@@ -25,13 +27,58 @@ use Drupal\Core\Field\FieldItemInterface;
*/
class FileCeFieldFormatter extends FlattenedCeFieldFormatter {
use CustomElementsImageStyleConfigTrait;
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'image_style' => '',
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$element = parent::buildConfigurationForm($form, $form_state);
if ($this->getFieldDefinition()->getType() === 'image') {
$element += $this->getImageStyleConfigForm($this->configuration['image_style'] ?? '');
}
return $element;
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
if ($this->getFieldDefinition()->getType() === 'image') {
$this->configuration['image_style'] = $form_state->getValue('image_style');
}
}
/**
* {@inheritdoc}
*/
protected function getFieldItemProperties(FieldItemInterface $field_item, array $ignore_properties = []): array {
$values = parent::getFieldItemProperties($field_item, ['target_id']);
// Add url property of the referenced file to the values.
$values['url'] = $field_item->entity->uri->url;
if ($this->getFieldDefinition()->getType() === 'image' && !empty($this->configuration['image_style'])) {
$image_style = $this->loadImageStyle($this->configuration['image_style']);
if ($image_style) {
$values['url'] = $this->getImageStyleUrl($image_style, $field_item->entity->getFileUri());
}
else {
// Wrong/incomplete backend configuration must be fixed, rather than
// silently output an unintended response.
throw new \UnexpectedValueException("Image style '{$this->configuration['image_style']}' cannot be loaded.");
}
}
else {
// Add url property of the referenced file to the values.
$values['url'] = $field_item->entity->uri->url;
}
return $values;
}
@@ -40,6 +87,9 @@ class FileCeFieldFormatter extends FlattenedCeFieldFormatter {
*/
public function settingsSummary() {
$summary = parent::settingsSummary();
if ($this->getFieldDefinition()->getType() === 'image') {
$summary += $this->getSettingsSummary($this->configuration['image_style'] ?? '');
}
// target_id is the 'main' property, so nothing gets set into a slot.
$summary[] = $this->t('Is Slot is ignored.');
return $summary;
Loading