You are here

class FormModeConfigForm in Form Mode Control 8

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

Hierarchy

Expanded class hierarchy of FormModeConfigForm

1 string reference to 'FormModeConfigForm'
form_mode_control.routing.yml in ./form_mode_control.routing.yml
form_mode_control.routing.yml

File

src/Form/FormModeConfigForm.php, line 17
@author Anis Taktak <anis@emerya.fr>

Namespace

Drupal\form_mode_control\Form
View source
class FormModeConfigForm extends ConfigFormBase {

  /*
   **
   * Returns a unique string identifying the form.
   *
   * @return string
   *   The unique string identifying the form.
   */
  public function getFormId() {
    return 'form_mode_config';
  }

  /**
   * Form constructor.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return array
   *   The form structure.
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    //The manager of content and config entities.
    $entity_manager = \Drupal::getContainer()
      ->get('entity_type.bundle.info');
    $form_state
      ->setRebuild();

    //Content entities which have form modes.
    $entities_has_form_mode = $this
      ->entitiesHasFormMode();

    // Load all roles.
    $roles = Role::loadMultiple();

    // Load configuration of the module.
    $configuration = \Drupal::configFactory()
      ->getEditable('form_mode_control.settings');

    //All data saved in configurations.
    $data = $configuration
      ->getRawData();
    $entities_actives = array_intersect($this
      ->getEntitiesFormModeActivated(), array_keys($entities_has_form_mode));
    $form['information'] = array(
      '#type' => 'vertical_tabs',
    );
    foreach ($entities_actives as $machine_name_entity) {
      $bundles_has_form_modes_activated = array_values(array_unique($this
        ->filterBundles()));
      $bundles = array_keys($this
        ->getBundleFormEntityType($machine_name_entity));

      // bundles which have form modes activated
      $bundle_finished = array_values(array_intersect($bundles_has_form_modes_activated, $bundles));
      $form['details_entity_type_' . $machine_name_entity] = array(
        '#type' => 'vertical_tabs',
        '#title' => getLabelEntityType($machine_name_entity),
        '#open' => TRUE,
        '#group' => 'information',
      );
      foreach ($bundle_finished as $id_bundle) {
        $form['details_entity_type_' . $machine_name_entity]['details_bundle_' . $machine_name_entity . '_' . $id_bundle] = array(
          '#type' => 'details',
          '#title' => $entity_manager
            ->getBundleInfo($machine_name_entity)[$id_bundle]['label'] . ' (' . getLabelEntityType($machine_name_entity) . ') ',
          '#open' => TRUE,
          '#group' => 'information',
        );
        $form['details_entity_type_' . $machine_name_entity]['details_bundle_' . $machine_name_entity . '_' . $id_bundle]['details_form_mode_creation' . '_' . $machine_name_entity . '_' . $id_bundle] = array(
          '#type' => 'details',
          '#title' => $this
            ->t('Creation ' . getLabelBundle($machine_name_entity, $id_bundle)),
          '#open' => TRUE,
        );
        $form['details_entity_type_' . $machine_name_entity]['details_bundle_' . $machine_name_entity . '_' . $id_bundle]['details_form_mode_modification' . '_' . $machine_name_entity . '_' . $id_bundle] = array(
          '#type' => 'details',
          '#title' => $this
            ->t('Modification ' . getLabelBundle($machine_name_entity, $id_bundle)),
          '#open' => TRUE,
        );
        foreach ($roles as $id_role => $role) {
          $options = $this
            ->filterFormModeByEntityType($machine_name_entity, $id_bundle, $role);
          if (count($options) > 0) {
            $id_creation = isset($data['creation_' . $id_role . '_' . $machine_name_entity . '_' . $id_bundle]) ? $data['creation_' . $id_role . '_' . $machine_name_entity . '_' . $id_bundle] : $machine_name_entity . '.' . $id_bundle . '.default';
            $form['details_entity_type_' . $machine_name_entity]['details_bundle_' . $machine_name_entity . '_' . $id_bundle]['details_form_mode_creation' . '_' . $machine_name_entity . '_' . $id_bundle]['creation_' . $id_role . '_' . $machine_name_entity . '_' . $id_bundle] = array(
              '#type' => 'select',
              "#options" => $options,
              '#title' => $role
                ->label(),
              '#default_value' => $id_creation,
              '#group' => 'information',
            );
            $id_modification = isset($data['modification_' . $id_role . '_' . $machine_name_entity . '_' . $id_bundle]) ? $data['modification_' . $id_role . '_' . $machine_name_entity . '_' . $id_bundle] : $machine_name_entity . '.' . $id_bundle . '.default';
            $form['details_entity_type_' . $machine_name_entity]['details_bundle_' . $machine_name_entity . '_' . $id_bundle]['details_form_mode_modification' . '_' . $machine_name_entity . '_' . $id_bundle]['modification_' . $id_role . '_' . $machine_name_entity . '_' . $id_bundle] = array(
              '#type' => 'select',
              "#options" => $options,
              '#title' => $role
                ->label(),
              '#default_value' => $id_modification,
              '#group' => 'information',
            );
          }
        }
      }
    }
    $form = parent::buildForm($form, $form_state);
    return $form;
  }

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

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

    /**
     *  Filter all values of form_state
     * and unused unused values.
     */
    $all_values = $form_state
      ->getValues();
    unset($all_values['submit']);
    unset($all_values['form_build_id']);
    unset($all_values['form_token']);
    unset($all_values['submit']);
    unset($all_values['form_id']);
    unset($all_values['op']);

    // Load the current configuration associeted to the config form (form_mode_control.settings).
    $configuration = \Drupal::configFactory()
      ->getEditable('form_mode_control.settings');
    $has_modification = FALSE;
    foreach ($all_values as $form_state_key => $form_mode_id_associated) {
      $display = $form_state
        ->getValue($form_state_key);
      if (substr_count($form_state_key, "modification_") != 0 || substr_count($form_state_key, "creation_") != 0) {
        $configuration
          ->set($form_state_key, $display);
        $has_modification = TRUE;
      }
    }

    // Save once configuration when there are modifications.
    if ($has_modification) {
      $configuration
        ->save();
    }
    parent::submitForm($form, $form_state);
  }

  /**
   * Gets the configuration names that will be editable.
   *
   * @return array
   *   An array of configuration object names that are editable if called in
   *   conjunction with the trait's config() method.
   */
  protected function getEditableConfigNames() {
    return [
      'form_mode_control.settings',
    ];
  }

  /**
   * Listing entities which have form mode
   * @return array
   */
  protected function entitiesHasFormMode() {

    //Initialising entities which have form modes.
    $entitiesHasFormMode = array();

    //All entities (content and config).
    $all_entities = \Drupal::entityTypeManager()
      ->getDefinitions();
    foreach ($all_entities as $entity_type_id => $entity_type) {

      // If the entity is a content entity and has form modes.
      // See formModeTypeSelection() in core/modules/field_ui/src/Controller/EntityDisplayModeController.php
      if ($entity_type
        ->get('field_ui_base_route') && $entity_type
        ->hasFormClasses()) {

        //Save content entities which have form modes.
        $entitiesHasFormMode[$entity_type_id] = $entity_type
          ->getLabel();
      }
    }
    return $entitiesHasFormMode;
  }

  /**
   * Load permission associated to display.
   * @param $form_mode_id
   * @return mixed
   */
  protected function importPermissionByFormModId($form_modes_id) {
    $permissions = array();
    $data = \Drupal::configFactory()
      ->getEditable('form_mode_control.settings')
      ->getRawData();
    foreach ($data as $key => $value) {
      if (substr_count($key, "linked to") != 0) {
        $permissions[$value] = $key;
      }
    }
    return isset($permissions[$form_modes_id]) ? $permissions[$form_modes_id] : NULL;
  }

  /**
   * Filter form modes which have permission by entity type, bundle.
   * @param $entity_type_id
   * @param $bundle_id
   * @return array
   */
  protected function filterFormModeByEntityType($entity_type_id, $bundle_id, $role) {

    //Load configuration.
    $storage = \Drupal::entityTypeManager()
      ->getStorage('entity_form_display');

    //Load all form modes.
    $form_modes_ids = $storage
      ->loadMultiple();

    //Initialisation of an array to add form mode searched.
    $id_form_mode_searched = array();
    foreach ($form_modes_ids as $form_modes_id => $form_mode_configuration) {
      $aux = explode(".", $form_modes_id);
      $entity_type_to_filter = $aux[0];
      $bundle_id_to_filter = $aux[1];
      $display = $aux[2];

      // TODO: verify if add default display name or no.
      if ($entity_type_to_filter == $entity_type_id && $bundle_id_to_filter == $bundle_id) {
        $imported_permission = $this
          ->importPermissionByFormModId($form_modes_id);
        if ($role
          ->hasPermission($imported_permission) && $form_mode_configuration
          ->status()) {
          $id_form_mode_searched[$form_modes_id] = getLabelFormModeFromMachineName($entity_type_to_filter, $bundle_id_to_filter, $display);
        }
      }
    }
    return $id_form_mode_searched;
  }

  /**
   *
   * @return array
   */
  protected function getEntitiesFormModeActivated() {
    $all_form_modes = \Drupal::entityTypeManager()
      ->getStorage('entity_form_display')
      ->loadMultiple();
    $entities = array();
    foreach ($all_form_modes as $id_form_mode => $form_mode) {
      $machine_name_form_mode = explode('.', $id_form_mode);
      $form_mode_id = $machine_name_form_mode[2];
      $entity_type = $machine_name_form_mode[0];
      if ($form_mode
        ->status() && $form_mode_id != "default") {
        $entities[$id_form_mode] = $entity_type;
      }
    }
    return $entities;
  }

  /**
   * Return bundles which have a form modes activated.
   * @param $entity_type_id
   * @return array
   */
  function filterBundles() {
    $bundles_final = array();
    $form_modes_activated = array_keys($this
      ->getEntitiesFormModeActivated());
    foreach ($form_modes_activated as $form_mode_id => $bundle) {
      $bundles_final[] = explode('.', $bundle)[1];
    }
    return $bundles_final;
  }

  /**
   *  Get the bundle info of an entity type.
   * @param $entity_type_id
   * @return mixed
   */
  protected function getBundleFormEntityType($entity_type_id) {
    $entity_manager = \Drupal::getContainer()
      ->get('entity_type.bundle.info');
    return $entity_manager
      ->getAllBundleInfo()[$entity_type_id];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create 13
ConfigFormBase::__construct public function Constructs a \Drupal\system\ConfigFormBase object. 11
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
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::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.
FormModeConfigForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
FormModeConfigForm::entitiesHasFormMode protected function Listing entities which have form mode
FormModeConfigForm::filterBundles function Return bundles which have a form modes activated.
FormModeConfigForm::filterFormModeByEntityType protected function Filter form modes which have permission by entity type, bundle.
FormModeConfigForm::getBundleFormEntityType protected function Get the bundle info of an entity type.
FormModeConfigForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
FormModeConfigForm::getEntitiesFormModeActivated protected function
FormModeConfigForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
FormModeConfigForm::importPermissionByFormModId protected function Load permission associated to display.
FormModeConfigForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
FormModeConfigForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
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.