You are here

public function ComponentBlock::blockForm in Component blocks 1.0.x

Same name and namespace in other branches
  1. 1.x src/Plugin/Block/ComponentBlock.php \Drupal\component_blocks\Plugin\Block\ComponentBlock::blockForm()
  2. 1.1.x src/Plugin/Block/ComponentBlock.php \Drupal\component_blocks\Plugin\Block\ComponentBlock::blockForm()

Overrides BlockPluginTrait::blockForm

File

src/Plugin/Block/ComponentBlock.php, line 240

Class

ComponentBlock
Defines a class for a specially shaped block.

Namespace

Drupal\component_blocks\Plugin\Block

Code

public function blockForm($form, FormStateInterface $form_state) {
  $plugin = $this
    ->uiPatternsManager()
    ->getDefinition($this->pluginDefinition['ui_pattern_id']);
  $form = parent::blockForm($form, $form_state);
  $form['variables'] = [
    '#type' => 'details',
    '#title' => $this
      ->t('Context variables'),
    '#open' => TRUE,
    '#tree' => TRUE,
  ];
  $contexts = $this
    ->contextHandler()
    ->getMatchingContexts($form_state
    ->getTemporaryValue('gathered_contexts') ?: [], $this
    ->getContextDefinition('entity'));
  $context = reset($contexts);

  /** @var \Drupal\Core\Entity\ContentEntityInterface $sample_entity */
  $sample_entity = $context
    ->getContextData()
    ->getValue();
  $fields = array_map(function (FieldDefinitionInterface $field) {
    return $field
      ->getLabel();
  }, $sample_entity
    ->getFieldDefinitions());
  $fields[self::FIXED] = $this
    ->t('Fixed input');
  foreach ($plugin['fields'] as $id => $details) {
    if (!($details['ui'] ?? TRUE)) {
      $form['variables'][$id] = [
        'source' => [
          '#type' => 'value',
          '#value' => self::FIXED,
        ],
        'value' => [
          '#type' => 'value',
          '#value' => $details['default'],
        ],
      ];
      continue;
    }
    $form['variables'][$id] = [
      '#type' => 'container',
      '#process' => [
        [
          $this,
          'formatterSettingsProcessCallback',
        ],
      ],
      '#prefix' => '<div id="component-settings-' . $id . '">',
      '#suffix' => '</div>',
      'label' => [
        '#type' => 'item',
        '#markup' => $details['label'],
      ],
      'source' => [
        '#type' => 'select',
        '#options' => $fields,
        '#default_value' => self::FIXED,
        '#title' => $this
          ->t('Source'),
        '#ajax' => [
          'callback' => [
            get_class($this),
            'updateElementValue',
          ],
          'wrapper' => 'component-settings-' . $id,
        ],
      ],
    ];
  }
  return $form;
}