You are here

public function ClassyLayout::buildConfigurationForm in Layout Section Classes 8

Form constructor.

Plugin forms are embedded in other forms. In order to know where the plugin form is located in the parent form, #parents and #array_parents must be known, but these are not available during the initial build phase. In order to have these properties available when building the plugin form's elements, let this method return a form element that has a #process callback and build the rest of the form in the callback. By the time the callback is executed, the element's #parents and #array_parents properties will have been set by the form API. For more documentation on #parents and #array_parents, see \Drupal\Core\Render\Element\FormElement.

Parameters

array $form: An associative array containing the initial structure of the plugin form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form. Calling code should pass on a subform state created through \Drupal\Core\Form\SubformState::createForSubform().

Return value

array The form structure.

Overrides LayoutDefault::buildConfigurationForm

File

src/ClassyLayout.php, line 35

Class

ClassyLayout
A layout plugin class for layouts with selectable classes.

Namespace

Drupal\layout_section_classes

Code

public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
  $form = parent::buildConfigurationForm($form, $form_state);
  $form['classes'] = [
    '#type' => 'container',
    '#tree' => TRUE,
  ];
  $plugin_configuration = $this->configuration['additional']['classes'] ?? [];
  foreach ($this
    ->getPluginDefinition()
    ->get('classes') as $key => $class_definition) {
    if (!is_array($class_definition['options']) || empty($class_definition['options'])) {
      throw new \Exception('The "options" key is required for layout class definitions.');
    }
    $definition_default = $class_definition['default'] ?? NULL;
    $form['classes'][$key] = [
      '#title' => $class_definition['label'] ?? $this
        ->t('Classes'),
      '#type' => 'select',
      '#multiple' => $class_definition['multiple'] ?? FALSE,
      '#options' => $class_definition['options'],
      '#required' => $class_definition['required'] ?? FALSE,
      '#default_value' => $plugin_configuration[$key] ?? $definition_default,
      '#description' => $class_definition['description'] ?? '',
    ];

    // Add an empty option if the selection is option or it's required with no
    // default.
    if (!$form['classes'][$key]['#required'] || $form['classes'][$key]['#required'] && $form['classes'][$key]['#default_value'] === NULL) {
      $form['classes'][$key]['#empty_option'] = $this
        ->t('- Select -');
    }
  }
  return $form;
}