You are here

class DashboardManageForm in Draggable dashboard 8

Provides the draggable dashboard edit form.

Hierarchy

Expanded class hierarchy of DashboardManageForm

1 string reference to 'DashboardManageForm'
draggable_dashboard.routing.yml in ./draggable_dashboard.routing.yml
draggable_dashboard.routing.yml

File

src/Form/DashboardManageForm.php, line 15

Namespace

Drupal\draggable_dashboard\Form
View source
class DashboardManageForm extends DashboardFormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'draggable_dashboard_manage';
  }

  /**
   * {@inheritdoc}
   */
  protected function buildDashboard($did) {
    return DashboardEntity::load($did);
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, $did = NULL) {
    $this->dashboard = $this
      ->buildDashboard($did);
    $active_theme = $this->themeManager
      ->getActiveTheme();
    $theme_name = $active_theme
      ->getName();
    $form['#title'] = $this->dashboard
      ->get('title');
    $form['did'] = [
      '#type' => 'hidden',
      '#value' => $this->dashboard
        ->id(),
    ];
    $form['#attached']['library'][] = 'core/drupal.tableheader';
    $form['#attached']['library'][] = 'draggable_dashboard/draggable_dashboard.main';
    $form['dashboard_blocks_table'] = [
      '#type' => 'table',
      '#header' => [
        $this
          ->t('Block'),
        $this
          ->t('Category'),
        $this
          ->t('Region'),
        $this
          ->t('Weight'),
        $this
          ->t('Operations'),
      ],
      '#empty' => $this
        ->t('No columns defined.'),
      '#attributes' => [
        'id' => 'dashboardblocks',
      ],
    ];

    // Prepare available regions list.
    $regionOptions = [];
    for ($i = 1; $i <= $this->dashboard
      ->get('columns'); $i++) {
      $regionOptions[$i] = $i . ' ' . t('Column');
    }
    $entities = json_decode($this->dashboard
      ->get('blocks'), TRUE);

    // Weights range from -delta to +delta, so delta should be at least half
    // of the amount of blocks present. This makes sure all blocks in the same
    // region get an unique weight.
    $weight_delta = round(count($entities) / 2);
    for ($i = 1; $i <= $this->dashboard
      ->get('columns'); $i++) {
      $region = $i;
      $title = $this
        ->t('Column #@id', [
        '@id' => $i,
      ]);
      $form['dashboard_blocks_table']['#tabledrag'][] = [
        'action' => 'match',
        'relationship' => 'sibling',
        'group' => 'block-region-select',
        'subgroup' => 'block-region-' . $region,
        'hidden' => FALSE,
      ];
      $form['dashboard_blocks_table']['#tabledrag'][] = [
        'action' => 'order',
        'relationship' => 'sibling',
        'group' => 'block-weight',
        'subgroup' => 'block-weight-' . $region,
      ];
      $form['dashboard_blocks_table']['region-' . $region] = [
        '#attributes' => [
          'class' => [
            'region-title',
            'region-title-' . $region,
          ],
          'no_striping' => TRUE,
        ],
      ];
      $form['dashboard_blocks_table']['region-' . $region]['title'] = [
        '#theme_wrappers' => [
          'container' => [
            '#attributes' => [
              'class' => 'region-title__action',
            ],
          ],
        ],
        '#prefix' => $title,
        '#type' => 'link',
        '#title' => $this
          ->t('Place block <span class="visually-hidden">in the %region region</span>', [
          '%region' => $title,
        ]),
        '#url' => Url::fromRoute('block.admin_library', [
          'theme' => $theme_name,
        ], [
          'query' => [
            'region' => 'draggable_dashboard-' . base64_encode(json_encode([
              'did' => $did,
              'cln' => $region,
            ])),
          ],
        ]),
        '#wrapper_attributes' => [
          'colspan' => 5,
        ],
        '#attributes' => [
          'class' => [
            'use-ajax',
            'button',
            'button--small',
            'place-blocks',
          ],
          'data-dialog-type' => 'modal',
          'data-dialog-options' => Json::encode([
            'width' => 700,
          ]),
        ],
      ];

      // Collect all blocks from one particular column.
      $relations = [];
      if (!empty($entities)) {
        foreach ($entities as $entity) {
          if ($entity['cln'] == $i) {
            $relations[] = $entity;
          }
        }
      }
      $form['dashboard_blocks_table']['region-' . $region . '-message'] = [
        '#attributes' => [
          'class' => [
            'region-message',
            'region-' . $region . '-message',
            empty($relations) ? 'region-empty' : 'region-populated',
          ],
        ],
      ];
      $form['dashboard_blocks_table']['region-' . $region . '-message']['message'] = [
        '#markup' => '<em>' . t('No blocks in this region') . '</em>',
        '#wrapper_attributes' => [
          'colspan' => 5,
        ],
      ];
      if (!empty($relations)) {
        foreach ($relations as $relation) {
          $block = Block::load($relation['bid']);
          if (empty($block)) {
            continue;
          }
          $block
            ->set('region', DashboardEntityInterface::BASE_REGION_NAME);
          $block
            ->set('theme', $this
            ->config('system.theme')
            ->get('admin'));
          $block
            ->save();
          $entity_id = $relation['bid'];
          $form['dashboard_blocks_table'][$entity_id] = [
            '#attributes' => [
              'class' => [
                'draggable',
              ],
            ],
          ];
          $form['dashboard_blocks_table'][$entity_id]['info'] = [
            '#plain_text' => $block
              ->label(),
            '#wrapper_attributes' => [
              'class' => [
                'block',
              ],
            ],
          ];
          $form['dashboard_blocks_table'][$entity_id]['type'] = [
            '#markup' => $block
              ->getPluginId(),
          ];
          $form['dashboard_blocks_table'][$entity_id]['region-theme']['region'] = [
            '#type' => 'select',
            '#default_value' => $relation['cln'],
            '#required' => TRUE,
            '#title' => $this
              ->t('Region for @block block', [
              '@block' => $block
                ->label(),
            ]),
            '#title_display' => 'invisible',
            '#options' => $regionOptions,
            '#attributes' => [
              'class' => [
                'block-region-select',
                'block-region-' . $region,
              ],
            ],
            '#parents' => [
              'blocks',
              $entity_id,
              'region',
            ],
          ];
          $form['dashboard_blocks_table'][$entity_id]['weight'] = [
            '#type' => 'weight',
            '#default_value' => $relation['position'],
            '#delta' => $weight_delta,
            '#title' => t('Weight for @block block', [
              '@block' => $block
                ->label(),
            ]),
            '#title_display' => 'invisible',
            '#attributes' => [
              'class' => [
                'block-weight',
                'block-weight-' . $region,
              ],
            ],
          ];
          $links = [];
          $links['edit'] = [
            'title' => $this
              ->t('Configure'),
            'url' => Url::fromRoute('entity.block.edit_form', [
              'block' => $block
                ->id(),
            ]),
          ];
          $links['delete'] = [
            'title' => $this
              ->t('Delete'),
            'url' => Url::fromRoute('draggable_dashboard.delete_block', [
              'did' => $did,
              'bid' => $relation['bid'],
            ]),
          ];
          $form['dashboard_blocks_table'][$entity_id]['operations'] = [
            'data' => [
              '#type' => 'operations',
              '#links' => $links,
            ],
          ];
        }
      }
    }
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
      '#button_type' => 'primary',
    ];
    $form['actions']['back'] = [
      '#type' => 'link',
      '#title' => $this
        ->t('Back To Dashboards'),
      '#url' => new Url('draggable_dashboard.overview'),
      '#attributes' => [
        'class' => [
          'button',
        ],
      ],
    ];
    return $form;
  }

  /**
   * Form submit.
   *
   * @param array $form
   *   Form elements array.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state object.
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // Remove unnecessary values.
    $form_state
      ->cleanValues();
    $did = $form_state
      ->getValue('did', 0);

    // Save Dashboard Blocks.
    $dBlocks = [];
    $blocks = $form_state
      ->getValue('blocks', []);
    $table = $form_state
      ->getValue('dashboard_blocks_table', []);
    foreach ($blocks as $id => $block) {
      $position = 0;
      foreach ($table as $key => $new_position) {
        if ($id == $key) {
          break;
        }
        if ($block['region'] == $blocks[$key]['region']) {
          $position++;
        }
      }
      $dBlocks[] = [
        'bid' => $id,
        'cln' => $block['region'],
        'position' => (int) $position,
      ];
    }
    $this->dashboard
      ->set('blocks', json_encode($dBlocks))
      ->save();
    $this
      ->messenger()
      ->addMessage($this
      ->t('Dashboard blocks has been updated.'));
    $form_state
      ->setRedirect('draggable_dashboard.manage_dashboard', [
      'did' => $did,
    ]);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DashboardFormBase::$blockManager protected property The block manager.
DashboardFormBase::$dashboard protected property An array containing the dashboard ID, etc.
DashboardFormBase::$themeManager protected property The theme manager.
DashboardFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create
DashboardFormBase::MAX_COLUMNS_COUNT constant Maximum dashboard columns count.
DashboardFormBase::validateForm public function Form validation handler. Overrides FormBase::validateForm
DashboardFormBase::__construct public function DashboardFormBase constructor.
DashboardManageForm::buildDashboard protected function Builds the path used by the form. Overrides DashboardFormBase::buildDashboard
DashboardManageForm::buildForm public function Form constructor. Overrides DashboardFormBase::buildForm
DashboardManageForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
DashboardManageForm::submitForm public function Form submit. Overrides DashboardFormBase::submitForm
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.