You are here

class ImceProfileForm in IMCE 8.2

Same name and namespace in other branches
  1. 8 src/Form/ImceProfileForm.php \Drupal\imce\Form\ImceProfileForm

Base form for Imce Profile entities.

Hierarchy

Expanded class hierarchy of ImceProfileForm

File

src/Form/ImceProfileForm.php, line 16

Namespace

Drupal\imce\Form
View source
class ImceProfileForm extends EntityForm {

  /**
   * Plugin manager for Imce Plugins.
   *
   * @var \Drupal\imce\ImcePluginManager
   */
  protected $pluginManagerImce;

  /**
   * The construct method.
   *
   * @param \Drupal\imce\ImcePluginManager $plugin_manager_imce
   *   Plugin manager for Imce Plugins.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   */
  public function __construct(ImcePluginManager $plugin_manager_imce) {
    $this->pluginManagerImce = $plugin_manager_imce;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('plugin.manager.imce.plugin'));
  }

  /**
   * Folder permissions.
   *
   * @var array
   */
  public $folderPermissions;

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

    /**
     * @var \Drupal\imce\Entity\ImceProfile
     */
    $imce_profile = $this
      ->getEntity();

    // Check duplication.
    if ($this
      ->getOperation() === 'duplicate') {
      $imce_profile = $imce_profile
        ->createDuplicate();
      $imce_profile
        ->set('label', $this
        ->t('Duplicate of @label', [
        '@label' => $imce_profile
          ->label(),
      ]));
      $this
        ->setEntity($imce_profile);
    }

    // Label.
    $form['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Name'),
      '#default_value' => $imce_profile
        ->label(),
      '#maxlength' => 64,
      '#required' => TRUE,
      '#weight' => -20,
    ];

    // Id.
    $form['id'] = [
      '#type' => 'machine_name',
      '#machine_name' => [
        'exists' => [
          get_class($imce_profile),
          'load',
        ],
        'source' => [
          'label',
        ],
      ],
      '#default_value' => $imce_profile
        ->id(),
      '#maxlength' => 32,
      '#required' => TRUE,
      '#weight' => -20,
    ];

    // Description.
    $form['description'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Description'),
      '#default_value' => $imce_profile
        ->get('description'),
      '#weight' => -10,
    ];

    // Conf.
    $conf = [
      '#tree' => TRUE,
    ];

    // Extensions.
    $conf['extensions'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Allowed file extensions'),
      '#default_value' => $imce_profile
        ->getConf('extensions'),
      '#maxlength' => 255,
      '#description' => $this
        ->t('Separate extensions with a space, and do not include the leading dot.') . ' ' . $this
        ->t('Set to * to allow all extensions.'),
      '#weight' => -9,
    ];

    // File size.
    $maxsize = Environment::getUploadMaxSize();
    $conf['maxsize'] = [
      '#type' => 'number',
      '#min' => 0,
      '#max' => ceil($maxsize / 1024 / 1024),
      '#step' => 'any',
      '#size' => 8,
      '#title' => $this
        ->t('Maximum file size'),
      '#default_value' => $imce_profile
        ->getConf('maxsize'),
      '#description' => $this
        ->t('Maximum allowed file size per upload.') . ' ' . $this
        ->t('Your PHP settings limit the upload size to %size.', [
        '%size' => format_size($maxsize),
      ]),
      '#field_suffix' => $this
        ->t('MB'),
      '#weight' => -8,
    ];

    // Quota.
    $conf['quota'] = [
      '#type' => 'number',
      '#min' => 0,
      '#step' => 'any',
      '#size' => 8,
      '#title' => $this
        ->t('Disk quota'),
      '#default_value' => $imce_profile
        ->getConf('quota'),
      '#description' => $this
        ->t('Maximum disk space that can be allocated by a user.'),
      '#field_suffix' => $this
        ->t('MB'),
      '#weight' => -7,
    ];

    // Image dimensions.
    $conf['dimensions'] = [
      '#type' => 'container',
      '#attributes' => [
        'class' => [
          'dimensions-wrapper form-item',
        ],
      ],
      '#weight' => -6,
    ];
    $conf['dimensions']['label'] = [
      '#markup' => '<label>' . $this
        ->t('Maximum image dimensions') . '</label>',
    ];
    $conf['dimensions']['maxwidth'] = [
      '#type' => 'number',
      '#default_value' => $imce_profile
        ->getConf('maxwidth'),
      '#maxlength' => 5,
      '#min' => 0,
      '#size' => 8,
      '#placeholder' => $this
        ->t('Width'),
      '#field_suffix' => ' x ',
      '#parents' => [
        'conf',
        'maxwidth',
      ],
    ];
    $conf['dimensions']['maxheight'] = [
      '#type' => 'number',
      '#default_value' => $imce_profile
        ->getConf('maxheight'),
      '#maxlength' => 5,
      '#min' => 0,
      '#size' => 8,
      '#placeholder' => $this
        ->t('Height'),
      '#field_suffix' => $this
        ->t('pixels'),
      '#parents' => [
        'conf',
        'maxheight',
      ],
    ];
    $conf['dimensions']['description'] = [
      '#markup' => '<div class="description">' . $this
        ->t('Images exceeding the limit will be scaled down.') . '</div>',
    ];

    // Advanced settings
    $conf['advanced'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Advanced settings'),
      '#open' => FALSE,
      '#parents' => [
        'conf',
      ],
      '#weight' => 9,
    ];

    // Replace method.
    $conf['advanced']['replace'] = [
      '#type' => 'radios',
      '#title' => $this
        ->t('Upload replace method'),
      '#default_value' => $imce_profile
        ->getConf('replace', FileSystemInterface::EXISTS_RENAME),
      '#options' => [
        FileSystemInterface::EXISTS_RENAME => $this
          ->t('Keep the existing file renaming the new one'),
        FileSystemInterface::EXISTS_REPLACE => $this
          ->t('Replace the existing file with the new one'),
        FileSystemInterface::EXISTS_ERROR => $this
          ->t('Keep the existing file rejecting the new one'),
      ],
      '#description' => $this
        ->t('Select the replace method for existing files during uploads.'),
      '#weight' => -5,
    ];

    // Image thumbnails.
    if (function_exists('image_style_options')) {
      $conf['advanced']['thumbnail_style'] = [
        '#type' => 'select',
        '#title' => $this
          ->t('Thumbnail style'),
        '#options' => image_style_options(),
        '#default_value' => $imce_profile
          ->getConf('thumbnail_style'),
        '#description' => $this
          ->t('Select a thumbnail style from the list to make the file browser display inline image previews. Note that this could reduce the performance of the file browser drastically.'),
      ];
      $conf['advanced']['thumbnail_grid_style'] = [
        '#type' => 'checkbox',
        '#title' => $this
          ->t('Thumbnail grid style'),
        '#default_value' => $imce_profile
          ->getConf('thumbnail_grid_style'),
        '#description' => $this
          ->t('Check it if you want to display the thumbnail in a grid. If not checked it will display the thumbnail in a list.'),
      ];
    }
    $conf['advanced']['ignore_usage'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Ignore file usage.'),
      '#default_value' => $imce_profile
        ->getConf('ignore_usage'),
      '#description' => $this
        ->t('IMCE avoids deletion or overwriting of files that are in use by other Drupal modules. Enabling this option skips the file usage check. Not recommended!'),
    ];

    // Folders.
    $conf['folders'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Folders'),
      'description' => [
        '#markup' => '<div class="description">' . $this
          ->t('You can use user tokens in folder paths, e.g. @tokens.', [
          '@tokens' => '[user:uid], [user:name]',
        ]) . ' ' . $this
          ->t('Subfolders inherit parent permissions when subfolder browsing is enabled.') . '</div>',
      ],
      '#weight' => 10,
    ];
    if ($this->moduleHandler
      ->moduleExists('token')) {
      $conf['folders']['token_tree'] = [
        '#theme' => 'token_tree_link',
        '#token_types' => [
          'user',
        ],
        '#show_restricted' => TRUE,
        '#global_types' => FALSE,
      ];
    }
    $folders = $imce_profile
      ->getConf('folders', []);
    $index = 0;
    foreach ($folders as $folder) {
      $conf['folders'][] = $this
        ->folderForm($index++, $folder);
    }
    $conf['folders'][] = $this
      ->folderForm($index++);
    $conf['folders'][] = $this
      ->folderForm($index);
    $form['conf'] = $conf;

    // Add library.
    $form['#attached']['library'][] = 'imce/drupal.imce.admin';

    // Call plugin form alterers.
    $this->pluginManagerImce
      ->alterProfileForm($form, $form_state, $imce_profile);
    return parent::form($form, $form_state);
  }

  /**
   * Returns folder form elements.
   */
  public function folderForm($index, array $folder = []) {
    $folder += [
      'path' => '',
      'permissions' => [],
    ];
    $form = [
      '#type' => 'container',
      '#attributes' => [
        'class' => [
          'folder-container',
        ],
      ],
    ];
    $fieldPrefix = $this
      ->t('root');
    $slach = '/';
    $form['path'] = [
      '#type' => 'textfield',
      '#default_value' => $folder['path'],
      '#field_prefix' => '&lt;' . $fieldPrefix . '&gt;' . $slach,
    ];
    $form['permissions'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Permissions'),
      '#attributes' => [
        'class' => [
          'folder-permissions',
        ],
      ],
    ];
    $perms = $this
      ->permissionInfo();
    $form['permissions']['all'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('All permissions'),
      '#default_value' => isset($folder['permissions']['all']) ? $folder['permissions']['all'] : 0,
    ];
    foreach ($perms as $perm => $title) {
      $form['permissions'][$perm] = [
        '#type' => 'checkbox',
        '#title' => $title,
        '#default_value' => isset($folder['permissions'][$perm]) ? $folder['permissions'][$perm] : 0,
        '#states' => [
          'disabled' => [
            'input[name="conf[folders][' . $index . '][permissions][all]"]' => [
              'checked' => TRUE,
            ],
          ],
        ],
      ];
    }
    return $form;
  }

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

    // Check folders.
    $folders = [];
    foreach ($form_state
      ->getValue([
      'conf',
      'folders',
    ]) as $i => $folder) {
      $path = trim($folder['path']);

      // Empty path.
      if ($path === '') {
        continue;
      }

      // Validate path.
      if (!Imce::regularPath($path)) {
        return $form_state
          ->setError($form['conf']['folders'][$i]['path'], $this
          ->t('Invalid folder path.'));
      }

      // Remove empty permissions.
      $folder['permissions'] = array_filter($folder['permissions']);
      $folder['path'] = $path;
      $folders[$path] = $folder;
    }

    // No valid folders.
    if (!$folders) {
      return $form_state
        ->setError($form['conf']['folders'][0]['path'], $this
        ->t('You must define a folder.'));
    }
    $form_state
      ->setValue([
      'conf',
      'folders',
    ], array_values($folders));

    // Call plugin validators.
    $this->pluginManagerImce
      ->validateProfileForm($form, $form_state, $this
      ->getEntity());
    return parent::validateForm($form, $form_state);
  }

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

    /**
     * @var \Drupal\imce\Entity\ImceProfile
     */
    $imce_profile = $this
      ->getEntity();
    $status = $imce_profile
      ->save();
    if ($status == SAVED_NEW) {
      $this
        ->messenger()
        ->addMessage($this
        ->t('Profile %name has been added.', [
        '%name' => $imce_profile
          ->label(),
      ]));
    }
    elseif ($status == SAVED_UPDATED) {
      $this
        ->messenger()
        ->addMessage($this
        ->t('The changes have been saved.'));
    }
    $form_state
      ->setRedirect('entity.imce_profile.edit_form', [
      'imce_profile' => $imce_profile
        ->id(),
    ]);
  }

  /**
   * Returns folder permission definitions.
   */
  public function permissionInfo() {
    if (!isset($this->folderPermissions)) {
      $this->folderPermissions = $this->pluginManagerImce
        ->permissionInfo();
    }
    return $this->folderPermissions;
  }

}

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
EntityForm::$entity protected property The entity being used by this form. 7
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::actions protected function Returns an array of supported actions for the current entity form. 29
EntityForm::actionsElement protected function Returns the action form element for the current entity form.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::buildForm public function Form constructor. Overrides FormInterface::buildForm 10
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides FormInterface::submitForm 17
EntityForm::__get public function
EntityForm::__set public function
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.
ImceProfileForm::$folderPermissions public property Folder permissions.
ImceProfileForm::$pluginManagerImce protected property Plugin manager for Imce Plugins.
ImceProfileForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
ImceProfileForm::folderForm public function Returns folder form elements.
ImceProfileForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
ImceProfileForm::permissionInfo public function Returns folder permission definitions.
ImceProfileForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
ImceProfileForm::validateForm public function Form validation handler. Overrides FormBase::validateForm
ImceProfileForm::__construct public function The construct method.
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.