You are here

class SkinEditForm in Skinr 8.2

Hierarchy

Expanded class hierarchy of SkinEditForm

File

skinr_ui/src/Form/SkinEditForm.php, line 17
Contains Drupal\skinr_ui\Form\SkinEditForm.

Namespace

Drupal\skinr_ui\Form
View source
class SkinEditForm extends EntityForm {

  /**
   * The entity query factory.
   *
   * @var \Drupal\Core\Entity\Query\QueryFactory
   */
  protected $entityQueryFactory;

  /**
   * @param \Drupal\Core\Entity\Query\QueryFactory $entity_query_factory
   *   The entity query.
   */
  public function __construct(QueryFactory $entity_query_factory) {
    $this->entityQueryFactory = $entity_query_factory;
  }

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

  /**
   * {@inheritdoc}
   */
  protected function actions(array $form, FormStateInterface $form_state) {
    $actions = parent::actions($form, $form_state);

    // Override save button label.
    if ($this->entity
      ->isNew()) {
      $actions['submit']['#value'] = $this
        ->t('Add');
    }
    return $actions;
  }

  /**
   * Handles switching the available elements based on the selected theme and element type.
   */
  public function updateElement($form, FormStateInterface $form_state) {
    $theme_name = $form_state
      ->getValue('theme');
    $element_type = $form_state
      ->getValue('element_type');
    $form['element']['#options'] = self::elementOptions($theme_name, $element_type);
    Select::processSelect($form['element'], $form_state, $form);
    return $form['element'];
  }

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

    /* @var Skin $skin */
    $skin = $this->entity;
    $theme_handler = \Drupal::service('theme_handler');
    if ($skin
      ->isNew()) {
      $themes = $theme_handler
        ->listInfo();
      $form['theme'] = array(
        '#type' => 'select',
        '#title' => t('Theme'),
        '#options' => array_map(function ($theme) {
          return $theme->info['name'];
        }, $themes),
        '#default_value' => $form_state
          ->getValue('theme'),
        '#required' => TRUE,
        '#ajax' => array(
          'callback' => '::updateElement',
          'wrapper' => 'dropdown-element-replace',
        ),
      );
      $form['element_type'] = array(
        '#type' => 'select',
        '#title' => t('Type'),
        '#options' => skinr_get_config_info(),
        '#default_value' => $form_state
          ->getValue('element_type'),
        '#required' => TRUE,
        '#ajax' => array(
          'callback' => '::updateElement',
          'wrapper' => 'dropdown-element-replace',
        ),
      );
      $form['element'] = array(
        '#type' => 'select',
        '#title' => t('Element'),
        '#prefix' => '<div id="dropdown-element-replace">',
        '#suffix' => '</div>',
        '#options' => self::elementOptions($form_state
          ->getValue('theme'), $form_state
          ->getValue('element_type')),
        '#required' => TRUE,
      );
      $skin_infos = skinr_get_skin_info();

      // Apply overridden status to skins.
      foreach ($skin_infos as $skin_name => $skin_info) {
        $skin_infos[$skin_name]['status'] = skinr_skin_info_status_get($skin_infos[$skin_name]);
      }

      // @todo Only display enabled skins.
      // @todo Group by groups.
      $form['skin'] = array(
        '#type' => 'select',
        '#title' => t('Skin'),
        '#options' => array_map(function ($skin_info) {
          return $skin_info['title'];
        }, $skin_infos),
        '#required' => TRUE,
      );
    }
    else {
      $form['info']['element_type_info'] = array(
        '#type' => 'item',
        '#title' => t('Type'),
        '#markup' => $skin
          ->elementTypeLabel(),
      );
      $form['info']['element_info'] = array(
        '#type' => 'item',
        '#title' => t('Element'),
        '#markup' => $skin
          ->elementLabel(),
      );
      $form['info']['theme_info'] = array(
        '#type' => 'item',
        '#title' => t('Theme'),
        '#markup' => $skin
          ->themeLabel(),
      );
      $form['info']['skin_info'] = array(
        '#type' => 'item',
        '#title' => t('Skin'),
        '#markup' => $skin
          ->skinLabel(),
      );
      $form['element_type'] = array(
        '#type' => 'value',
        '#value' => $skin->element_type,
      );
      $form['element'] = array(
        '#type' => 'value',
        '#value' => $skin->element,
      );
      $form['theme'] = array(
        '#type' => 'value',
        '#value' => $skin->theme,
      );
      $form['skin'] = array(
        '#type' => 'value',
        '#value' => $skin->skin,
      );
      $skin_infos = skinr_get_skin_info();

      // Add custom info.
      $skin_infos['_additional'] = array(
        'title' => t('Additional'),
      );
      $skin_info = $skin_infos[$skin->skin];

      // Create options widget.
      $field = array();
      if (!empty($skin_info['form callback'])) {

        // Process custom form callbacks.
        // Load include file.
        if (!empty($skin_info['source']['include file'])) {
          skinr_load_include($skin_info['source']['include file']);
        }

        // Execute form callback.
        if (function_exists($skin_info['form callback'])) {
          $context = array(
            'theme' => $skin->theme,
            'skin_name' => $skin->skin,
            'skin_info' => $skin_info,
            'value' => isset($defaults[$skin->theme][$skin->skin]) ? $defaults[$skin->theme][$skin->skin] : array(),
          );
          $field = $skin_info['form callback']($form, $form_state, $context);
        }
      }
      elseif ($skin->skin == '_additional') {
        $field = array(
          '#type' => 'textfield',
          '#title' => t('CSS classes'),
          '#size' => 40,
          '#description' => t('To add CSS classes manually, enter classes separated by a single space i.e. <code>first-class second-class</code>'),
          '#default_value' => $skin
            ->getOptions(),
        );
        if (skinr_ui_access('edit advanced skin settings')) {
          $field['#disabled'] = TRUE;
          $field['#description'] .= '<br /><em>' . t('You require additional permissions to edit this setting.') . '</em>';
        }
      }
      else {
        switch ($skin_info['type']) {
          case 'checkboxes':
            $field = array(
              '#type' => 'checkboxes',
              '#multiple' => TRUE,
              '#title' => $skin_info['title'],
              '#options' => $this
                ->optionsToFormOptions($skin_info['options']),
              '#default_value' => $skin
                ->getOptions(),
              '#description' => $skin_info['description'],
              '#weight' => isset($skin_info['weight']) ? $skin_info['weight'] : NULL,
            );
            break;
          case 'radios':
            $field = array(
              '#type' => 'radios',
              '#title' => $skin_info['title'],
              '#options' => array_merge(array(
                '' => '&lt;none&gt;',
              ), $this
                ->optionsToFormOptions($skin_info['options'])),
              '#default_value' => $skin
                ->getOptions(),
              '#description' => $skin_info['description'],
              '#weight' => isset($skin_info['weight']) ? $skin_info['weight'] : NULL,
            );
            break;
          case 'select':
            $field = array(
              '#type' => 'select',
              '#title' => $skin_info['title'],
              '#options' => array_merge(array(
                '' => '<none>',
              ), $this
                ->optionsToFormOptions($skin_info['options'])),
              '#default_value' => $skin
                ->getOptions(),
              '#description' => $skin_info['description'],
              '#weight' => isset($skin_info['weight']) ? $skin_info['weight'] : NULL,
            );
            break;
          default:

            // Raise an error.
            drupal_set_message(t("Widget %name's type is invalid.", array(
              '%name' => $skin->skin,
            )), 'error', FALSE);
            break;
        }
      }
      $form['options'] = $field;
    }
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function save(array $form, FormStateInterface $form_state) {
    $status = parent::save($form, $form_state);
    $destination = \Drupal::service('redirect.destination')
      ->getAsArray();
    if ($destination['destination'] == base_path() . 'admin/structure/skinr/add') {
      $form_state
        ->setRedirect('entity.skin.edit_form', array(
        'skin' => $this->entity
          ->id(),
      ));
    }
    elseif ($destination['destination'] == base_path() . 'admin/structure/skinr/' . $this->entity
      ->id() . '/edit') {
      $form_state
        ->setRedirect('skinr_ui.list');
    }
    return $status;
  }

  /**
   * Helper function to convert an array of options, as specified in the .info
   * file, into an array usable by Form API.
   *
   * @param $options
   *   An array containing at least the 'class' and 'label' keys.
   *
   * @return string[]
   *   A Form API compatible array of options.
   *
   * @todo Rename function to be more descriptive.
   */
  protected function optionsToFormOptions($options) {
    $form_options = array();
    foreach ($options as $option_name => $option) {
      $form_options[$option_name] = $option['title'];
    }
    return $form_options;
  }

  /**
   * Return an array of element options for a module.
   *
   * If no field type is provided, returns a nested array of all element options,
   * keyed by module.
   *
   * @param string $theme_name
   * @param string $element_type
   *
   * @return array
   */
  protected function elementOptions($theme_name = NULL, $element_type = NULL) {
    $options =& drupal_static(__FUNCTION__);
    if (!isset($options)) {
      $options = skinr_invoke_all('skinr_ui_element_options', $theme_name);
    }
    if ($element_type && isset($options[$element_type])) {
      if (!empty($theme_name)) {
        $theme = \Drupal::service('theme_handler')
          ->getTheme($theme_name);
        $theme_label = $theme->info['name'];
        if (isset($options[$element_type][$theme_label])) {
          return $options[$element_type][$theme_label];
        }
      }
      return $options[$element_type];
    }
    return array();
  }

}

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::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.
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.
SkinEditForm::$entityQueryFactory protected property The entity query factory.
SkinEditForm::actions protected function Returns an array of supported actions for the current entity form. Overrides EntityForm::actions
SkinEditForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
SkinEditForm::elementOptions protected function Return an array of element options for a module.
SkinEditForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
SkinEditForm::optionsToFormOptions protected function Helper function to convert an array of options, as specified in the .info file, into an array usable by Form API.
SkinEditForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
SkinEditForm::updateElement public function Handles switching the available elements based on the selected theme and element type.
SkinEditForm::__construct public function
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.