trinion_tp-1.0.x-dev/src/Plugin/Field/FieldWidget/KommercheskoePredlogenieFieldWidget.php

src/Plugin/Field/FieldWidget/KommercheskoePredlogenieFieldWidget.php
<?php

namespace Drupal\trinion_tp\Plugin\Field\FieldWidget;

use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\node\Entity\Node;

/**
 * Виджет для отображения элементов коммерческого предложения
 *
 * @FieldWidget(
 *   id = "trinion_tp_kommercheskoe_predlogenie_field_widget",
 *   label = "Строки КП, з.клиента, ...",
 *   field_types = {"entity_reference"},
 * )
 */
class KommercheskoePredlogenieFieldWidget extends WidgetBase {

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    $stroka_uit = $items[$delta]->entity;
    $vals = $form_state->get('vals');
    if ($stroka_uit) {
      if (($stroka_uit_tovar = $stroka_uit->get('field_tp_tovar')->first()) && isset($stroka_uit_tovar->entity)) {
        $stroka_uit_tovar_name = $stroka_uit_tovar->entity->label() . ' [' . $stroka_uit_tovar->entity->get('field_tp_artikul')->getString() . ']';
        $harakteristiki = \Drupal::service('trinion_tp.helper')->getHarakteristikiTovara($stroka_uit_tovar->entity);
        $harakteristika = $stroka_uit->get('field_tp_kharakteristika_tovara')->getString();
      }
      else
        $stroka_uit_tovar_name = $stroka_uit->label();
    }
    else {
      if (isset($vals[$delta])) {
        $stroka_uit = $vals[$delta];
        if ($stroka_uit['target_id']) {
          $stroka_uit = Node::load($stroka_uit['target_id']);
          if ($tovar = $stroka_uit->get('field_tp_tovar')->first()->entity)
            $harakteristiki = \Drupal::service('trinion_tp.helper')->getHarakteristikiTovara($tovar, FALSE, FALSE);
        }
      }
    }

    $element['uit'] = [
      '#type' => 'textfield',
      '#autocomplete_route_name' => 'trinion_tp.tovar.autocomplete',
      '#title' => 'Услуга и товар',
      '#attributes' => ['class' => ['uit']],
      '#default_value' => $stroka_uit_tovar_name ?? '',
      '#element_validate' => [[$this, 'uitValidate']],
      '#size' => '255',
    ];
    if (\Drupal::config('trinion_tp.settings')->get('harakteristiki')) {
      $element['harakteristika'] = [
        '#type' => 'select',
        '#title' => t('Сharacteristics'),
        '#options' => $harakteristiki ?? [],
        '#attributes' => ['class' => ['harakteristika']],
        '#default_value' => $harakteristika ?? '',
        '#validated' => TRUE,
      ];
    }
    $options = [];
    $skladi = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadByProperties([
      'vid' => 'sklad',
    ]);

    foreach ($skladi as $sklad) {
      $options[$sklad->id()] = $sklad->label();
    }
    $element['sklad'] = [
      '#type' => 'select',
      '#title' => 'Склад',
      '#empty_value' => '',
      '#options' => $options ?? [],
      '#attributes' => ['class' => ['sklad']],
      '#default_value' => is_object($stroka_uit) ? $stroka_uit->get('field_tp_sklad')->getString() : '',
    ];
    $element['kolichestvo'] = [
      '#type' => 'number',
      '#title' => 'Кол-во',
      '#attributes' => ['class' => ['kolichestvo']],
      '#step' => '0.01',
      '#default_value' => is_object($stroka_uit) ? $stroka_uit->get('field_tp_kolichestvo')->getString() : '',
    ];
    if (is_object($stroka_uit))
      $time_stamp = strtotime($stroka_uit->get('field_tp_plan_vrem_postupleniya')->getString());
    $element['plan_vrem_postupleniya'] = [
      '#type' => 'datetime',
      '#title' => 'Планируемое время поступления',
      '#attributes' => ['class' => ['plan_vrem_postupleniya']],
      '#step' => '0.01',
      '#default_value' => !empty($time_stamp) ? DrupalDateTime::createFromTimestamp($time_stamp) : '',
    ];
    $element['cena'] = [
      '#type' => 'number',
      '#title' => 'Цена',
      '#attributes' => ['class' => ['cena']],
      '#step' => '0.01',
      '#default_value' => is_object($stroka_uit) ? $stroka_uit->get('field_tp_cena')->getString() : '0',
    ];
    $element['skidka_procent'] = [
      '#type' => 'number',
      '#title' => 'Скидка %',
      '#attributes' => ['class' => ['skidka_procent']],
      '#step' => '0.01',
      '#default_value' => is_object($stroka_uit) ? $stroka_uit->get('field_tp_skidka')->getString() : '',
    ];
    $element['skidka_summa'] = [
      '#type' => 'number',
      '#title' => 'Скидка сумма',
      '#attributes' => ['class' => ['skidka_summa']],
      '#step' => '0.01',
      '#default_value' => is_object($stroka_uit) ? $stroka_uit->get('field_tp_skidka_summa')->getString() : '',
    ];
    $element['nacenka_procent'] = [
      '#type' => 'number',
      '#title' => 'Наценка %',
      '#attributes' => ['class' => ['nacenka_procent']],
      '#step' => '0.01',
      '#default_value' => is_object($stroka_uit) ? $stroka_uit->get('field_tp_nacenka')->getString() : '',
    ];
    $element['nacenka_summa'] = [
      '#type' => 'number',
      '#title' => 'Наценка сумма',
      '#attributes' => ['class' => ['nacenka_summa']],
      '#step' => '0.01',
      '#default_value' => is_object($stroka_uit) ? $stroka_uit->get('field_tp_nacenka_summa')->getString() : '',
    ];
    $element['opisanie'] = [
      '#type' => 'textfield',
      '#title' => 'Описание',
      '#attributes' => ['class' => ['opisanie']],
      '#default_value' => is_object($stroka_uit) ? $stroka_uit->get('field_tp_opisanie')->getString() : '',
      '#rows' => 2,
    ];
    $opts = [];
    foreach (\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree('edinicy_izmereniya') as $term)
      $opts[$term->tid] = $term->name;
    $element['edinica_izmereniya'] = [
      '#type' => 'select',
      '#title' => 'Единица',
      '#options' => $opts,
      '#attributes' => ['class' => ['edinica_izmereniya']],
      '#default_value' => is_object($stroka_uit) ? $stroka_uit->get('field_tp_edinica_izmereniya')->getString() : key($opts),
    ];
    $field_definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'tp_stroka_dokumenta_uit');
    $opts = $field_definitions['field_tp_nds']->getSetting('allowed_values');
    $element['nds'] = [
      '#type' => 'select',
      '#title' => 'НДС',
      '#options' => $opts,
      '#attributes' => ['class' => ['nds']],
      '#default_value' => is_object($stroka_uit) ? $stroka_uit->get('field_tp_nds')->getString() : key($opts),
    ];
    $element['itogo'] = [
      '#type' => 'hidden',
      '#attributes' => ['class' => ['itogo']],
      '#default_value' => is_object($stroka_uit) ? $stroka_uit->get('field_tp_itogo')->getString() : '',
    ];
    $element['id'] = [
      '#type' => 'hidden',
      '#value' => is_object($stroka_uit) ? $stroka_uit->id() : ($vals[$delta]['target_id'] ?? ''),
    ];

    return $element;
  }

  public function massageFormValues(array $values, array $form, FormStateInterface $form_state) {
    static $vals = [];
    if ($vals)
      return $vals;
    if ($form_state->getErrors())
      return;
    else {
      $vals = [];
      foreach ($values as $item) {
        if (empty($item['kolichestvo']) || empty($item['uit']))
          continue;
        /** @var DrupalDateTime $plan_vrem_postupleniya */
        $plan_vrem_postupleniya = $item['plan_vrem_postupleniya'];
        if (empty($item['id'])) {
          $data = [
            'type' => 'tp_stroka_dokumenta_uit',
            'title' => $item['uit'],
            'uid' => \Drupal::currentUser()->id(),
            'status' => 1,
            'field_tp_kolichestvo' => $item['kolichestvo'],
            'field_tp_cena' => $item['cena'],
            'field_tp_skidka_summa' => $item['skidka_summa'],
            'field_tp_skidka' => $item['skidka_procent'],
            'field_tp_nacenka_summa' => $item['nacenka_summa'],
            'field_tp_nacenka' => $item['nacenka_procent'],
            'field_tp_edinica_izmereniya' => $item['edinica_izmereniya'],
            'field_tp_opisanie' => $item['opisanie'],
            'field_tp_plan_vrem_postupleniya' => !empty($plan_vrem_postupleniya) ? date('Y-m-d\TH:i:s', $plan_vrem_postupleniya->getTimestamp()) : NULL,
            'field_tp_sklad' => !empty($item['sklad']) ? $item['sklad'] : NULL,
            'field_tp_itogo' => $item['itogo'],
            'field_tp_nds' => $item['nds'],
          ];
          if (!empty($item['harakteristika']))
            $data['field_tp_kharakteristika_tovara'] = $item['harakteristika'];
          if ($tovar = \Drupal::service('trinion_tp.helper')->tovarfromAutocomleteString($item['uit'])) {
            $data['field_tp_tovar'] = $tovar->id();
            $data['field_tp_artikul'] = $tovar->get('field_tp_artikul')->getString();
          }
          $stroka_uit = Node::create($data);
          $stroka_uit->save();
          $vals[] = ['target_id' => $stroka_uit->id()];
        }
        else {
          if ($form_state->getValue('field_tp_stroki_add_more')) {
            $stroka_id = $item['id'];
          }
          else {
            $tovar = \Drupal::service('trinion_tp.helper')->tovarfromAutocomleteString($item['uit']);
            $stroka_uit = Node::load($item['id']);
            $stroka_uit->field_tp_cena = $item['cena'];
            $stroka_uit->field_tp_nacenka = $item['nacenka_procent'];
            $stroka_uit->field_tp_nacenka_summa = $item['nacenka_summa'];
            $stroka_uit->field_tp_skidka = $item['skidka_procent'];
            $stroka_uit->field_tp_skidka_summa = $item['skidka_summa'];
            $stroka_uit->field_tp_kolichestvo = $item['kolichestvo'];
            $stroka_uit->field_tp_edinica_izmereniya = $item['edinica_izmereniya'];
            $stroka_uit->field_tp_opisanie = $item['opisanie'];
            $stroka_uit->field_tp_plan_vrem_postupleniya = !empty($plan_vrem_postupleniya) ? date('Y-m-d\TH:i:s', $plan_vrem_postupleniya->getTimestamp()) : NULL;
            $stroka_uit->field_tp_sklad = !empty($item['sklad']) ? $item['sklad'] : NULL;
            $stroka_uit->field_tp_itogo = $item['itogo'];
            $stroka_uit->field_tp_nds = $item['nds'];
            $stroka_uit->field_tp_kharakteristika_tovara = !empty($item['harakteristika']) ? $item['harakteristika'] : NULL;

            $stroka_uit->title = $item['uit'];
            if ($tovar) {
              $stroka_uit->field_tp_tovar = $tovar->id();
              $stroka_uit->field_tp_artikul = $tovar->get('field_tp_artikul')->getString();
              $stroka_uit->title = $tovar->label();
            }
            $stroka_uit->save();
            $stroka_id = $stroka_uit->id();
          }
          $vals[] = ['target_id' => $stroka_id];
        }
      }
    }
    $form_state->set('vals', $vals);
    return $vals;
  }

  public function uitValidate($form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    if (!isset($values['field_tp_stroki']))
      return;
    $stroki = $values['field_tp_stroki'];
    foreach ($stroki as $key => $item) {
      if (is_numeric($key) && $item['uit'] != '') {
        $tovar = \Drupal::service('trinion_tp.helper')->tovarfromAutocomleteString($item['uit']);
        if (!$tovar) {
          $form_state->setErrorByName('', 'Не корректно выбрана услуга или товар в строке ' . $key + 1);
        }
      }
    }
  }
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc