block_generation-8.x-1.x-dev/src/Plugin/BlockGenerationEffect/CustomStyle.php

src/Plugin/BlockGenerationEffect/CustomStyle.php
<?php

namespace Drupal\block_generation\Plugin\BlockGenerationEffect;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\NestedArray;

/**
 * @BlockGenerationEffect(
 *   id = "custom_style",
 *   label = @Translation("Custom style"),
 *   description = @Translation("Custom style block effect.")
 * )
 */
class CustomStyle extends BlockGenerationEffectBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    $default = [
      'style' => NULL,
    ];

    return NestedArray::mergeDeep($default, parent::defaultConfiguration());
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $default = $this->defaultConfiguration();
    $form = parent::buildConfigurationForm($form, $form_state);

    $form['style'] = array(
      '#type' => 'textarea',
      '#title' => $this->t('Style'),
      '#default_value' => !empty($this->configuration['style']) ? $this->configuration['style'] : $default['style'],
      '#description' => $this->t('Custom styles for the wrapper.'),
      '#rows' => 3,
    );

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
    parent::validateConfigurationForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    $values = NestedArray::getValue($values, $form['#parents']);

    $this->configuration['style'] = $values['style'];

    parent::submitConfigurationForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function applyEffect($wrapper, array &$variables) {
    if (!empty($variables['settings'][$wrapper]['attributes']->offsetGet('style')) && $styles = explode(';', $variables['settings'][$wrapper]['attributes']->offsetGet('style'))) {
      // Prepare styles to be updated.
      foreach ($styles as $delta => &$style) {
        $style = trim($style);
        if ($style === '') {
          unset($styles[$delta]);
        }
      }
    }
    // Apply effect.
    $styles_to_apply = explode(';', $this->configuration['style']);
    foreach ($styles_to_apply as $delta => &$style_to_apply) {
      $style_to_apply = trim($style_to_apply);
      if ($style_to_apply !== '') {
        $styles[] = $style_to_apply;
      }
    }

    // Compose styles.
    $variables['settings'][$wrapper]['attributes']->setAttribute('style', implode('; ', $styles) . ';');
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc