block_generation-8.x-1.x-dev/src/Plugin/BlockGenerationEffect/BackgroundColor.php
src/Plugin/BlockGenerationEffect/BackgroundColor.php
<?php namespace Drupal\block_generation\Plugin\BlockGenerationEffect; use Drupal\Core\Form\FormStateInterface; use Drupal\Component\Utility\NestedArray; /** * @BlockGenerationEffect( * id = "background_color", * label = @Translation("Background color"), * description = @Translation("Background color block effect.") * ) */ class BackgroundColor extends BlockGenerationEffectBase { /** * {@inheritdoc} */ public function defaultConfiguration() { $default = [ 'color' => 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['color'] = array( '#type' => 'textfield', '#title' => $this->t('Background color'), '#default_value' => !empty($this->configuration['color']) ? $this->configuration['color'] : $default['color'], '#description' => $this->t('Color of the background.'), ); 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['color'] = $values['color']; 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[] = 'background-color:' . $this->configuration['color']; // Compose styles. $variables['settings'][$wrapper]['attributes']->setAttribute('style', implode('; ', $styles) . ';'); } }