Last active
April 19, 2024 08:52
-
-
Save drubb/0c9777bb37d1a44dd8cae374a372e41c to your computer and use it in GitHub Desktop.
Example for a paragraph behavior plugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Drupal\behaviors\Plugin\paragraphs\Behavior; | |
use Drupal\Core\Entity\Display\EntityViewDisplayInterface; | |
use Drupal\Core\Form\FormStateInterface; | |
use Drupal\paragraphs\Entity\Paragraph; | |
use Drupal\paragraphs\ParagraphInterface; | |
use Drupal\paragraphs\ParagraphsBehaviorBase; | |
/** | |
* Provides a paragraphs behaviour plugin for background styles. | |
* | |
* @ParagraphsBehavior( | |
* id = "background_behavior", | |
* label = @Translation("Background style"), | |
* description = @Translation("Configurable background style"), | |
* ) | |
*/ | |
class BackgroundBehavior extends ParagraphsBehaviorBase { | |
/** | |
* {@inheritdoc} | |
*/ | |
public function view(array &$build, Paragraph $paragraph, EntityViewDisplayInterface $display, $view_mode) { | |
$style = $paragraph->getBehaviorSetting($this->getPluginId(), 'style', 'bright'); | |
$build['#attributes']['class'][] = 'paragraph-background-' . $style; | |
$build['#attached']['library'][] = 'behaviors/styles'; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function buildBehaviorForm(ParagraphInterface $paragraph, array &$form, FormStateInterface $form_state) { | |
$form['style'] = [ | |
'#type' => 'radios', | |
'#title' => $this->t('Background style'), | |
'#default_value' => $paragraph->getBehaviorSetting($this->getPluginId(), 'style', 'bright'), | |
'#options' => [ | |
'dark' => $this->t('Dark background, bright text'), | |
'bright' => $this->t('Bright background, dark text'), | |
], | |
]; | |
return $form; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function settingsSummary(Paragraph $paragraph) { | |
$style = $paragraph->getBehaviorSetting('background_behavior', 'style', 'bright'); | |
return [$this->t('Background style: @style', ['@style' => $style])]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment