You are here

class AutoEntityLabelForm in Automatic Entity Label 8

Same name and namespace in other branches
  1. 8.3 src/Form/AutoEntityLabelForm.php \Drupal\auto_entitylabel\Form\AutoEntityLabelForm
  2. 8.2 src/Form/AutoEntityLabelForm.php \Drupal\auto_entitylabel\Form\AutoEntityLabelForm

Class AutoEntityLabelForm.

@property \Drupal\Core\Config\ConfigFactoryInterface config_factory @property \Drupal\Core\Entity\EntityTypeManagerInterface entity_manager @property String entity_type_parameter @property String entity_type_id @property \Drupal\auto_entitylabel\AutoEntityLabelManager auto_entity_label_manager @package Drupal\auto_entitylabel\Controller

Hierarchy

Expanded class hierarchy of AutoEntityLabelForm

File

src/Form/AutoEntityLabelForm.php, line 23

Namespace

Drupal\auto_entitylabel\Form
View source
class AutoEntityLabelForm extends ConfigFormBase {

  /**
   * The config factory.
   *
   * Subclasses should use the self::config() method, which may be overridden to
   * address specific needs when loading config, rather than this property
   * directly. See \Drupal\Core\Form\ConfigFormBase::config() for an example of
   * this.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;
  protected $entitymanager;

  // @codingStandardsIgnoreLine
  protected $route_match;

  /**
   * AutoEntityLabelController constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   Config Factory.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_manager
   *   Entity manager.
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The route.
   */
  public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_manager, RouteMatchInterface $route_match) {
    parent::__construct($config_factory);
    $this->entitymanager = $entity_manager;
    $this->route_match = $route_match;
    $route_options = $this->route_match
      ->getRouteObject()
      ->getOptions();
    $array_keys = array_keys($route_options['parameters']);
    $this->entity_type_parameter = array_shift($array_keys);
    $entity_type = $this->route_match
      ->getParameter($this->entity_type_parameter);
    $this->entity_type_id = $entity_type
      ->id();
    $this->entity_type_provider = $entity_type
      ->getEntityType()
      ->getProvider();
  }

  /**
   * 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 [
      'auto_entitylabel.settings',
    ];
  }

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

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('entity.manager'), $container
      ->get('current_route_match'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $key = $this->entity_type_parameter . '_' . $this->entity_type_id;
    $config = $this
      ->config('auto_entitylabel.settings');

    /*
     * @todo
     *  Find a generic way of determining if the label is rendered on the
     *  entity form. If not, don't show 'auto_entitylabel_optional' option.
     */
    $options = [
      AutoEntityLabelManager::DISABLED => $this
        ->t('Disabled'),
      AutoEntityLabelManager::ENABLED => $this
        ->t('Automatically generate the label and hide the label field'),
      AutoEntityLabelManager::OPTIONAL => $this
        ->t('Automatically generate the label if the label field is left empty'),
    ];
    $form['auto_entitylabel'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Automatic label generation for @type', [
        '@type' => $this->entity_type_id,
      ]),
      '#weight' => 0,
    ];
    $form['auto_entitylabel'][$key . '_status'] = [
      '#type' => 'radios',
      '#default_value' => $config
        ->get($key . '_status'),
      '#options' => $options,
    ];
    $form['auto_entitylabel'][$key . '_pattern'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Pattern for the label'),
      '#description' => $this
        ->t('Leave blank for using the per default generated label. Otherwise this string will be used as label. Use the syntax [token] if you want to insert a replacement pattern.'),
      '#default_value' => $config
        ->get($key . '_pattern'),
    ];

    // Don't allow editing of the pattern if PHP is used, but the users lacks
    // permission for PHP.
    // @codingStandardsIgnoreLine
    if ($config
      ->get($key . '_php') && !\Drupal::currentUser()
      ->hasPermission('use PHP for auto entity labels')) {
      $form['auto_entitylabel'][$key . '_pattern']['#disabled'] = TRUE;
      $form['auto_entitylabel'][$key . '_pattern']['#description'] = $this
        ->t('You are not allowed the configure the pattern for the label, because you do not have the %permission permission.', [
        '%permission' => $this
          ->t('Use PHP for automatic entity label patterns'),
      ]);
    }

    // Display the list of available placeholders if token module is installed.
    // @codingStandardsIgnoreLine
    $module_handler = \Drupal::moduleHandler();
    if ($module_handler
      ->moduleExists('token')) {
      $token_info = $module_handler
        ->invoke($this->entity_type_provider, 'token_info');
      $token_types = isset($token_info['types']) ? array_keys($token_info['types']) : [];
      $form['auto_entitylabel']['token_help'] = [
        '#theme' => 'token_tree_link',
        '#token_types' => $token_types,
        '#dialog' => TRUE,
      ];
    }
    $form['auto_entitylabel'][$key . '_php'] = [
      // @codingStandardsIgnoreLine
      '#access' => \Drupal::currentUser()
        ->hasPermission('use PHP for auto entity labels'),
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Evaluate PHP in pattern.'),
      '#description' => $this
        ->t('Put PHP code above that returns your string, but make sure you surround code in <code>&lt;?php</code> and <code>?&gt;</code>. Note that <code>$entity</code> and <code>$language</code> are available and can be used by your code.'),
      '#default_value' => $config
        ->get($key . '_php'),
    ];
    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this->configFactory
      ->getEditable('auto_entitylabel.settings');
    foreach ($form_state
      ->getValues() as $key => $value) {
      $config
        ->set($key, $value);
    }
    $config
      ->save();
    parent::submitForm($form, $form_state);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
AutoEntityLabelForm::$configFactory protected property The config factory. Overrides FormBase::$configFactory
AutoEntityLabelForm::$entitymanager protected property
AutoEntityLabelForm::$route_match protected property
AutoEntityLabelForm::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
AutoEntityLabelForm::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
AutoEntityLabelForm::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
AutoEntityLabelForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
AutoEntityLabelForm::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
AutoEntityLabelForm::__construct public function AutoEntityLabelController constructor. Overrides ConfigFormBase::__construct
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::$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.
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.
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.