improvements-2.x-dev/modules/improvements_paragraphs/src/Plugin/paragraphs/Behavior/HtmlAttributesParagraphBehavior.php
modules/improvements_paragraphs/src/Plugin/paragraphs/Behavior/HtmlAttributesParagraphBehavior.php
<?php namespace Drupal\improvements_paragraphs\Plugin\paragraphs\Behavior; use Drupal\Core\Entity\Display\EntityViewDisplayInterface; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Template\AttributeHelper; use Drupal\druhels\ArrayHelper; use Drupal\paragraphs\Entity\Paragraph; use Drupal\paragraphs\ParagraphInterface; use Drupal\paragraphs\ParagraphsBehaviorBase; /** * @ParagraphsBehavior( * id = "html_attributes", * label = @Translation("Html attributes"), * description = @Translation("Allows to set paragraph html attributes."), * weight = 104, * ) */ class HtmlAttributesParagraphBehavior extends ParagraphsBehaviorBase { /** * {@inheritdoc} */ public function buildBehaviorForm(ParagraphInterface $paragraph, array &$form, FormStateInterface $form_state): array { $attributes = $paragraph->getBehaviorSetting($this->pluginId, 'value', []); $form['html_attributes'] = [ '#type' => 'textarea', '#title' => t('Html attributes'), '#description' => t('Example') . ' <code>class: my-paragraph-class</code>', '#default_value' => ArrayHelper::formatArrayAsKeyValueList($attributes), '#rows' => 2, ]; $form['#weight'] = $this->pluginDefinition['weight']; return $form; } /** * {@inheritdoc} */ public function submitBehaviorForm(ParagraphInterface $paragraph, array &$form, FormStateInterface $form_state): void { $filtered_values = $this->filterBehaviorFormSubmitValues($paragraph, $form, $form_state); $attributes = !empty($filtered_values['html_attributes']) ? ArrayHelper::formatKeyValueListAsArray($filtered_values['html_attributes'], ': ') : []; $paragraph->setBehaviorSettings($this->pluginId, ['value' => $attributes]); } /** * {@inheritDoc} */ public function view(array &$build, Paragraph $paragraph, EntityViewDisplayInterface $display, $view_mode): void { $all_behavior_settings = $paragraph->getAllBehaviorSettings(); // Not used getBehaviorSetting() for increase performance if ($new_attributes = $all_behavior_settings[$this->pluginId]['value'] ?? NULL) { $build['#attributes'] = AttributeHelper::mergeCollections( $build['#attributes'] ?? [], ArrayHelper::formatArrayAsAttributes($new_attributes) ); } } }