You are here

class ProductAdjustmentsForm in Ubercart 8.4

Associates option combinations with a product variant's SKU.

Hierarchy

Expanded class hierarchy of ProductAdjustmentsForm

1 string reference to 'ProductAdjustmentsForm'
uc_attribute.routing.yml in uc_attribute/uc_attribute.routing.yml
uc_attribute/uc_attribute.routing.yml

File

uc_attribute/src/Form/ProductAdjustmentsForm.php, line 13

Namespace

Drupal\uc_attribute\Form
View source
class ProductAdjustmentsForm extends FormBase {

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, NodeInterface $node = NULL) {
    $nid = $node
      ->id();

    // Populate table and such.
    $model = $node->model->value;
    $query = \Drupal::database()
      ->select('uc_product_attributes', 'pa');
    $query
      ->leftJoin('uc_attributes', 'a', 'pa.aid = a.aid');
    $query
      ->leftJoin('uc_attribute_options', 'ao', 'a.aid = ao.aid');
    $query
      ->leftJoin('uc_product_options', 'po', 'ao.oid = po.oid AND po.nid = :po_nid', [
      ':po_nid' => $nid,
    ]);
    $result = $query
      ->fields('pa', [
      'nid',
      'aid',
      'ordering',
      'display',
    ])
      ->fields('a', [
      'name',
      'ordering',
      'aid',
    ])
      ->fields('ao', [
      'aid',
    ])
      ->condition('pa.nid', $nid)
      ->having('COUNT(po.oid) > 0')
      ->groupBy('ao.aid')
      ->groupBy('pa.aid')
      ->groupBy('pa.display')
      ->groupBy('a.name')
      ->groupBy('pa.ordering')
      ->groupBy('a.ordering')
      ->groupBy('pa.nid')
      ->groupBy('a.aid')
      ->addTag('uc_product_adjustments_form')
      ->execute();
    $i = 1;
    $attribute_names = '';
    $query = \Drupal::database()
      ->select('uc_product_options', "po{$i}")
      ->extend('Drupal\\Core\\Database\\Query\\PagerSelectExtender')
      ->limit(20);
    $attribute_ids = [];
    foreach ($result as $prod_attr) {
      if ($i > 1) {
        $query
          ->join('uc_product_options', "po{$i}");
      }
      $query
        ->leftJoin('uc_attribute_options', "ao{$i}", "po{$i}.oid = ao{$i}.oid AND po{$i}.nid = :nid", [
        ':nid' => $nid,
      ]);
      $query
        ->addField("ao{$i}", 'aid', "aid{$i}");
      $query
        ->addField("ao{$i}", 'name', "name{$i}");
      $query
        ->addField("ao{$i}", 'oid', "oid{$i}");
      $query
        ->addField("po{$i}", 'ordering', "ordering{$i}");
      $query
        ->condition("ao{$i}.aid", $prod_attr->aid)
        ->orderBy("po{$i}.ordering")
        ->orderBy("ao{$i}.name");
      ++$i;
      $attribute_names .= '<th>' . SafeMarkup::checkPlain($prod_attr->name) . '</th>';
      $attribute_ids[] = $prod_attr->aid;
    }
    $num_prod_attr = count($attribute_ids);
    if ($num_prod_attr) {

      // Get previous values.
      $old_vals = \Drupal::database()
        ->query("SELECT * FROM {uc_product_adjustments} WHERE nid = :nid", [
        ':nid' => $nid,
      ])
        ->fetchAll();
      $result = $query
        ->execute();
      $form['original'] = [
        '#markup' => '<p><b>' . $this
          ->t('Default product SKU: @sku', [
          '@sku' => $model,
        ]) . '</b></p>',
      ];
      $form['default'] = [
        '#type' => 'value',
        '#value' => $model,
      ];
      $form['table'] = [
        '#prefix' => '<table class="combinations">',
        '#suffix' => '</table>',
      ];
      $form['table']['head'] = [
        '#markup' => '<thead><tr>' . $attribute_names . '<th>' . $this
          ->t('Alternate SKU') . '</th></tr></thead>',
        '#weight' => 0,
      ];
      $form['table']['body'] = [
        '#prefix' => '<tbody>',
        '#suffix' => '</tbody>',
        '#weight' => 1,
        '#tree' => TRUE,
      ];
      $i = 0;
      while ($combo = $result
        ->fetchObject()) {
        $cells = '';
        $row_title = '';
        $comb_array = [];
        for ($j = 1; $j <= $num_prod_attr; ++$j) {
          $cells .= '<td>' . SafeMarkup::checkPlain($combo->{'name' . $j}) . '</td>';
          $row_title .= SafeMarkup::checkPlain($combo->{'name' . $j}) . ', ';
          $comb_array[$combo->{'aid' . $j}] = $combo->{'oid' . $j};
        }
        ksort($comb_array);
        $row_title = substr($row_title, 0, strlen($row_title) - 2);
        $default_model = $model;
        foreach ($old_vals as $ov) {
          if ($ov->combination == serialize($comb_array)) {
            $default_model = $ov->model;
            break;
          }
        }
        $form['table']['body'][$i] = [
          '#prefix' => '<tr title="' . $row_title . '">',
          '#suffix' => '</tr>',
        ];
        $form['table']['body'][$i]['combo'] = [
          '#markup' => $cells,
        ];
        $form['table']['body'][$i]['combo_array'] = [
          '#type' => 'value',
          '#value' => serialize($comb_array),
        ];
        $form['table']['body'][$i]['model'] = [
          '#type' => 'textfield',
          '#default_value' => $default_model,
          '#prefix' => '<td>',
          '#suffix' => '</td>',
        ];
        ++$i;
      }
      $form['nid'] = [
        '#type' => 'hidden',
        '#value' => $nid,
      ];
      $form['actions'] = [
        '#type' => 'actions',
      ];
      $form['actions']['submit'] = [
        '#type' => 'submit',
        '#value' => $this
          ->t('Submit'),
      ];
    }
    else {
      $form['error'] = [
        '#markup' => '<div><br />' . $this
          ->t('This product does not have any attributes that can be used for SKU adjustments.') . '</div>',
      ];
    }
    $form['pager'] = [
      '#type' => 'pager',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    foreach ($form_state
      ->getValue('body') as $value) {
      if (!empty($value['model']) && $value['model'] != $form_state
        ->getValue('default')) {
        \Drupal::database()
          ->merge('uc_product_adjustments')
          ->key([
          'nid' => $form_state
            ->getValue('nid'),
          'combination' => $value['combo_array'],
        ])
          ->fields([
          'model' => $value['model'],
        ])
          ->execute();
      }
      else {
        \Drupal::database()
          ->delete('uc_product_adjustments')
          ->condition('nid', $form_state
          ->getValue('nid'))
          ->condition('combination', $value['combo_array'])
          ->execute();
      }
    }
    $this
      ->messenger()
      ->addMessage($this
      ->t('Product adjustments have been saved.'));
  }

}

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.
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.
ProductAdjustmentsForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
ProductAdjustmentsForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
ProductAdjustmentsForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
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.