You are here

class ModulesListForm in Modules weight 8

Same name and namespace in other branches
  1. 8.2 src/Form/ModulesListForm.php \Drupal\modules_weight\Form\ModulesListForm

Builds the form to configure the Modules weight.

Hierarchy

Expanded class hierarchy of ModulesListForm

1 string reference to 'ModulesListForm'
modules_weight.routing.yml in ./modules_weight.routing.yml
modules_weight.routing.yml

File

src/Form/ModulesListForm.php, line 16

Namespace

Drupal\modules_weight\Form
View source
class ModulesListForm extends FormBase {

  /**
   * The module weight service.
   *
   * @var \Drupal\modules_weight\ModulesWeightInterface
   */
  protected $modulesWeight;

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The module extension list service.
   *
   * @var \Drupal\Core\Extension\ModuleExtensionList
   */
  protected $moduleExtensionList;

  /**
   * Constructs a new ModulesWeight object.
   *
   * @param \Drupal\modules_weight\ModulesWeightInterface $modules_weight
   *   The modules weight.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The configuration factory.
   * @param \Drupal\Core\Extension\ModuleExtensionList $module_extension_list
   *   The module extension list.
   */
  public function __construct(ModulesWeightInterface $modules_weight, ConfigFactoryInterface $config_factory, ModuleExtensionList $module_extension_list) {
    $this->modulesWeight = $modules_weight;
    $this->configFactory = $config_factory;
    $this->moduleExtensionList = $module_extension_list;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('modules_weight'), $container
      ->get('config.factory'), $container
      ->get('extension.list.module'));
  }

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    // The table header.
    $header = [
      $this
        ->t('Name'),
      [
        'data' => $this
          ->t('Description'),
        // Hidding the description on narrow width devices.
        'class' => [
          RESPONSIVE_PRIORITY_MEDIUM,
        ],
      ],
      $this
        ->t('Weight'),
      [
        'data' => $this
          ->t('Package'),
        // Hidding the description on narrow width devices.
        'class' => [
          RESPONSIVE_PRIORITY_MEDIUM,
        ],
      ],
    ];

    // The table.
    $form['modules'] = [
      '#type' => 'table',
      '#header' => $header,
      '#sticky' => TRUE,
    ];

    // Getting the config to know if we should show or not the core modules.
    $show_core_modules = $this->configFactory
      ->get('modules_weight.settings')
      ->get('show_system_modules');

    // Getting the module list.
    $modules = $this->modulesWeight
      ->getModulesList($show_core_modules);

    // Iterate over each module.
    foreach ($modules as $filename => $module) {

      // The rows info.
      // Module name.
      $form['modules'][$filename]['name'] = [
        '#markup' => $module['name'],
      ];

      // Module description.
      $form['modules'][$filename]['description'] = [
        '#markup' => $module['description'],
      ];

      // Module weight.
      $form['modules'][$filename]['weight'] = [
        '#type' => 'weight',
        '#default_value' => $module['weight'],
        '#delta' => FormElement::getMaxDelta($module['weight']),
      ];

      // Module package.
      $form['modules'][$filename]['package'] = [
        '#markup' => $module['package'],
      ];
    }

    // The form button.
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save Changes'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

    // The modules information.
    $modules_info = $form_state
      ->getValue('modules');

    // Doing the array unidimensional.
    $new_weight_value = array_combine(array_keys($modules_info), array_column($modules_info, 'weight'));

    // Getting the config to know if we should show or not the core modules.
    $show_core_modules = $this->configFactory
      ->get('modules_weight.settings')
      ->get('show_system_modules');

    // The old values information.
    $old_modules_info = $this->modulesWeight
      ->getModulesList($show_core_modules);

    // Doing the array unidimensional.
    $old_weight_value = array_combine(array_keys($old_modules_info), array_column($old_modules_info, 'weight'));
    if ($new_weight_value == $old_weight_value) {

      // Printing message if there are not module that has changed.
      $this
        ->messenger()
        ->addWarning($this
        ->t("You don't have changed the weight for any module."));
    }
    else {

      // Getting the changed modules.
      $changed = array_diff_assoc($new_weight_value, $old_weight_value);

      // Printing message because we have changes in the weights.
      $this
        ->messenger()
        ->addMessage($this
        ->t('The modules weight was updated.'));

      // Updating weights.
      foreach ($changed as $module_name => $weight) {

        // Setting the new weight.
        module_set_weight($module_name, $weight);
        $variables = [
          '@module_name' => $this->moduleExtensionList
            ->getExtensionInfo($module_name)['name'],
          '@weight' => $weight,
        ];

        // Printing information about the modules weight.
        $this
          ->messenger()
          ->addMessage($this
          ->t('@module_name have now as weight: @weight', $variables));
      }
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
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::$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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
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.
ModulesListForm::$configFactory protected property The config factory. Overrides FormBase::$configFactory
ModulesListForm::$moduleExtensionList protected property The module extension list service.
ModulesListForm::$modulesWeight protected property The module weight service.
ModulesListForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ModulesListForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ModulesListForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ModulesListForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
ModulesListForm::__construct public function Constructs a new ModulesWeight object.
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.