You are here

abstract class ObjectOptionsFormBase in Ubercart 8.4

Defines the class/product attributes options form.

Hierarchy

Expanded class hierarchy of ObjectOptionsFormBase

File

uc_attribute/src/Form/ObjectOptionsFormBase.php, line 11

Namespace

Drupal\uc_attribute\Form
View source
abstract class ObjectOptionsFormBase extends FormBase {

  /**
   * The attributes.
   *
   * @var array
   */
  protected $attributes = [];

  /**
   * The attribute table that this form will write to.
   *
   * @var string
   */
  protected $attributeTable;

  /**
   * The option table that this form will write to.
   *
   * @var string
   */
  protected $optionTable;

  /**
   * The identifier field that this form will use.
   *
   * @var string
   */
  protected $idField;

  /**
   * The identifier value that this form will use.
   *
   * @var string
   */
  protected $idValue;

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

  /**
   * Constructs Options Form array on behalf of subclasses.
   *
   * @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 buildBaseForm(array $form, FormStateInterface $form_state) {
    $form['attributes']['#tree'] = TRUE;
    foreach ($this->attributes as $aid => $attribute) {
      $base_attr = uc_attribute_load($aid);
      if ($base_attr->options) {
        $form['attributes'][$aid]['options'] = [
          '#type' => 'table',
          '#header' => [
            $this
              ->t('Options'),
            $this
              ->t('Default'),
            $this
              ->t('Cost'),
            $this
              ->t('Price'),
            $this
              ->t('Weight'),
            $this
              ->t('List position'),
          ],
          '#caption' => [
            '#markup' => '<h2>' . $attribute->name . '</h2>',
          ],
          '#empty' => $this
            ->t('This attribute does not have any options.'),
          '#tabledrag' => [
            [
              'action' => 'order',
              'relationship' => 'sibling',
              'group' => 'uc-attribute-option-table-ordering',
            ],
          ],
        ];
        $query = \Drupal::database()
          ->select('uc_attribute_options', 'ao')
          ->fields('ao', [
          'aid',
          'oid',
          'name',
        ]);
        $query
          ->leftJoin($this->optionTable, 'po', "ao.oid = po.oid AND po." . $this->idField . " = :id", [
          ':id' => $this->idValue,
        ]);
        $query
          ->addField('ao', 'cost', 'default_cost');
        $query
          ->addField('ao', 'price', 'default_price');
        $query
          ->addField('ao', 'weight', 'default_weight');
        $query
          ->addField('ao', 'ordering', 'default_ordering');
        $query
          ->fields('po', [
          'cost',
          'price',
          'weight',
          'ordering',
        ])
          ->addExpression('CASE WHEN po.ordering IS NULL THEN 1 ELSE 0 END', 'null_order');
        $query
          ->condition('aid', $aid)
          ->orderBy('null_order')
          ->orderBy('po.ordering')
          ->orderBy('default_ordering')
          ->orderBy('ao.name');
        $result = $query
          ->execute();
        foreach ($result as $option) {
          $oid = $option->oid;
          $form['attributes'][$aid]['options'][$oid]['#attributes']['class'][] = 'draggable';
          $form['attributes'][$aid]['options'][$oid]['select'] = [
            '#type' => 'checkbox',
            '#title' => $option->name,
            '#default_value' => isset($attribute->options[$oid]),
          ];
          $form['attributes'][$aid]['options'][$oid]['default'] = [
            '#type' => 'radio',
            '#title' => $this
              ->t('Default'),
            '#title_display' => 'invisible',
            '#parents' => [
              'attributes',
              $aid,
              'default',
            ],
            '#return_value' => $oid,
            '#default_value' => $attribute->default_option,
          ];
          $form['attributes'][$aid]['options'][$oid]['cost'] = [
            '#type' => 'uc_price',
            '#title' => $this
              ->t('Cost'),
            '#title_display' => 'invisible',
            '#default_value' => is_null($option->cost) ? $option->default_cost : $option->cost,
            '#size' => 6,
            '#allow_negative' => TRUE,
          ];
          $form['attributes'][$aid]['options'][$oid]['price'] = [
            '#type' => 'uc_price',
            '#title' => $this
              ->t('Price'),
            '#title_display' => 'invisible',
            '#default_value' => is_null($option->price) ? $option->default_price : $option->price,
            '#size' => 6,
            '#allow_negative' => TRUE,
          ];
          $form['attributes'][$aid]['options'][$oid]['weight'] = [
            '#type' => 'textfield',
            '#title' => $this
              ->t('Weight'),
            '#title_display' => 'invisible',
            '#default_value' => is_null($option->weight) ? $option->default_weight : $option->weight,
            '#size' => 5,
          ];
          $form['attributes'][$aid]['options'][$oid]['ordering'] = [
            '#type' => 'weight',
            '#title' => $this
              ->t('List position'),
            '#title_display' => 'invisible',
            '#delta' => 50,
            '#default_value' => is_null($option->ordering) ? $option->default_ordering : $option->ordering,
            '#attributes' => [
              'class' => [
                'uc-attribute-option-table-ordering',
              ],
            ],
          ];
        }
      }
    }
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save changes'),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $error = FALSE;
    foreach ($form_state
      ->getValue('attributes') as $attribute) {
      $selected_opts = [];
      if (isset($attribute['options'])) {
        foreach ($attribute['options'] as $oid => $option) {
          if ($option['select']) {
            $selected_opts[] = $oid;
          }
        }
      }
      if (!empty($selected_opts) && !in_array($attribute['default'], $selected_opts)) {
        $form_state
          ->setErrorByName($attribute['default']);
        $error = TRUE;
      }
    }
    if ($error) {
      $this
        ->messenger()
        ->addError($this
        ->t('All attributes with enabled options must specify an enabled option as default.'));
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    foreach ($form_state
      ->getValue('attributes') as $aid => $attribute) {
      if (isset($attribute['default'])) {
        \Drupal::database()
          ->update($this->attributeTable)
          ->fields([
          'default_option' => $attribute['default'],
        ])
          ->condition($this->idField, $this->idValue)
          ->condition('aid', $aid)
          ->execute();
      }
      if (isset($attribute['options'])) {
        \Drupal::database()
          ->delete($this->optionTable)
          ->condition($this->idField, $this->idValue)
          ->condition('oid', array_keys($attribute['options']), 'IN')
          ->execute();
        foreach ($attribute['options'] as $oid => $option) {
          if ($option['select']) {
            unset($option['select']);
            $option[$this->idField] = $this->idValue;
            $option['oid'] = $oid;
            \Drupal::database()
              ->insert($this->optionTable)
              ->fields($option)
              ->execute();
          }
          else {
            $this
              ->optionRemoved($aid, $oid);
          }
        }
      }
    }
    $this
      ->messenger()
      ->addMessage($this
      ->t('The changes have been saved.'));
  }

  /**
   * Called when submission of this form caused an option to be removed.
   */
  protected function optionRemoved($aid, $oid) {
  }

}

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::$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::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 87
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.
FormInterface::buildForm public function Form constructor. 179
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.
ObjectOptionsFormBase::$attributes protected property The attributes.
ObjectOptionsFormBase::$attributeTable protected property The attribute table that this form will write to.
ObjectOptionsFormBase::$idField protected property The identifier field that this form will use.
ObjectOptionsFormBase::$idValue protected property The identifier value that this form will use.
ObjectOptionsFormBase::$optionTable protected property The option table that this form will write to.
ObjectOptionsFormBase::buildBaseForm public function Constructs Options Form array on behalf of subclasses.
ObjectOptionsFormBase::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ObjectOptionsFormBase::optionRemoved protected function Called when submission of this form caused an option to be removed. 1
ObjectOptionsFormBase::submitForm public function Form submission handler. Overrides FormInterface::submitForm 1
ObjectOptionsFormBase::validateForm public function Form validation handler. Overrides FormBase::validateForm
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.