Snippets Collections
<?php

namespace Drupal\musin_core\Plugin\Field\FieldWidget;

use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Custom field widget for instruments.
 *
 * @FieldWidget(
 *   id = "instruments_widget",
 *   label = @Translation("Instruments widget"),
 *   description = @Translation("Instruments widget"),
 *   field_types = {
 *     "entity_reference",
 *     "string"
 *   }
 * )
 */
class InstrumentsWidget extends WidgetBase {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, array $third_party_settings, EntityTypeManagerInterface $entityTypeManager) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $third_party_settings);
    $this->entityTypeManager = $entityTypeManager;
  }

  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['third_party_settings'],
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
    // TODO: Implement formElement() method.
    $value = isset($items[$delta]->value) ? $items[$delta]->value : '';

    $rows = [];
    $taxonomies = $this->entityTypeManager
      ->getStorage('taxonomy_term')
      ->loadByProperties([
        'vid' => 'instruments',
      ]);
    foreach ($taxonomies as $term) {
      $rows[$term->getName()] = $term->getName();
    }

    $element['first'] = [
      '#type' => 'checkboxes',
      '#options' => $rows,
      '#attributes' => [
        'name' => 'base_taxonomy',
      ]
    ];

    $element['second'] = [
      '#type' => 'textfield',
      '#title' => 'Enter your instruments',
      '#states' => [
        'visible' => [
          ':input[name="base_taxonomy"]' => ['value' => 'Other']
        ]
      ]
    ];

    return $element;
  }

}

$variation = \Drupal::entityTypeManager()->getStorage('commerce_product_variation')->load(id)->delete();
<?php

namespace Drupal\csv_import\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity\File;
use Drupal\node\Entity\Node;

class CSVImportForm extends FormBase {

  public function getFormId() {
    return 'csv_import';
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['csv_file'] = [
      '#title' => 'Upload your file',
      '#type' => 'managed_file',
      '#upload_location' => 'public://',
      '#upload_validators' => [
        'file_validate_extensions' => ['csv']
      ]
    ];

    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save'),
    ];

    return $form;
  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $csv_file = $form_state->getValue('csv_file');
    $csv_file = reset($csv_file);
    $file = File::load($csv_file);
    $data = $this->csvtoarray($file->getFileUri(), ',');
    foreach ($data as $row) {
      $operations[] = ['\Drupal\csv_import\Form\CSVImportForm::addImportContentItem', [$row]];
    }

    $batch = [
      'title' => $this->t('Importing data...'),
      'operations' => $operations,
      'init_message' => $this->t('Import is starting.'),
      'finished' => '\Drupal\csv_import\Form\CSVImportForm::addImportContentItemCallback',
    ];
    batch_set($batch);

    $this->messenger()->addMessage($this->t('Your form was submitted!'));
  }

  public function csvtoarray($filename='', $delimiter) {
    if (!file_exists($filename) || !is_readable($filename)) return FALSE;
    $header = NULL;

    if(($handle = fopen($filename, 'r')) !== FALSE) {
      while(($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
        if(!$header) {
          $header = $row;
        } else {
          $data[] = array_combine($header, $row);
        }
      }
      fclose($handle);
    }
    return $data;
  }

  public static function addImportContentItem($item, &$context) {
    $message = 'Creating ' . $item['Title'];
    $results = [];
    self::create_node($item);
    $context['message'] = $message;
    $context['results'] = $item;
  }

  public function addImportContentItemCallback($success, $results, $operations) {
    if ($success) {
      $message = \Drupal::translation()->formatPlural(count($results), 'One item processed.', '@count items processed.');
    } else {
      $message = t('Finished with an error.');
    }
    $this->messenger()->addMessage(t($message));
  }

  public static function create_node($item)
  {
    $data = file_get_contents($item['Image']);
    $file = file_save_data($data, 'public://sample.png', \Drupal\Core\File\FileSystemInterface::EXISTS_RENAME);

    $nodes = [
      'type' => 'articles_about_programming',
      'title' => $item['Title'],
      'field_description' => $item['Description'],
      'field_myimage' => [
        'target_id' => $file->id(),
        'alt' => 'Sample',
        'title' => 'Sample file',
      ],
      'field_link_to_website' => [
        'uri' => 'https://www.' . $item['Link to website'],
        'title' => $item['Title'],
        'options' => ['target' => '_blank'],
      ],
    ];
    $node = Node::create($nodes);
    $node->setPublished(TRUE);
    $node->save();
  }
}
// If we want to use it as a dependency injection (we should),
// than this is the right way.

/**
 * Logger interface.
 *
 * @var \Psr\Log\LoggerInterface
 */
protected $logger;

// After that we add it to constructor method.

/**
* Controller_name constructor
 *
 * @param \Psr\Log\LoggerInterface $logger
 *  Logger interface.
 */
public function __construct(LoggerInterface $logger) {
  $this->logger = $logger;
}

public function someFunction(){
  if (something) {
    // Line of code...
  } else {
    $this->logger->error('Error message');
  }
}
stormtextil_core.edifact_orders:
  path: '/cron/synchronize-edifact-orders'
  defaults:
    _controller: '\Drupal\stormtextil_synchronization\Controller\SynchronizeEdifactOrders::parse'
    _title: 'Edifact Parser'
  requirements:
    _permission: 'access content'
<?php

namespace Drupal\stormtextil_config\Form;

use Drupal\Core\Cache\Cache;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Link;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class StormTextil Config Form.
 */
class StormTextilConfigForm extends ConfigFormBase {

  /**
   * EntityTypeManagerInterface.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * StormTextilConfigForm constructor.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The Entity Type Manager.
   */
  public function __construct(EntityTypeManagerInterface $entityTypeManager) {
    $this->entityTypeManager = $entityTypeManager;
  }

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

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'stormtextil_config.config_form';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return ['stormtextil_config.settings'];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $config = $this->config('stormtextil_config.settings');

    // Promotions e-mail.
    $form['promotions_email'] = [
      '#type' => 'details',
      '#title' => $this->t('Promotions in Order e-mail'),
      '#description' => $this->t('Add custom promotional text into order confirmation e-mail'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $promotions_email = $config->get('promotions_email');

    $form['promotions_email']['enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable promotions'),
      '#default_value' => isset($promotions_email['enabled']) ? $promotions_email['enabled'] : '',
    ];

    $form['promotions_email']['EN'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Text - en'),
      '#format' => 'full_html',
      '#default_value' => isset($promotions_email['EN']['value']) ? $promotions_email['EN']['value'] : '',
    ];

    $form['promotions_email']['DA'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Text - da'),
      '#format' => 'full_html',
      '#default_value' => isset($promotions_email['DA']['value']) ? $promotions_email['DA']['value'] : '',
    ];

    $form['promotions_email']['DE'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Text - de'),
      '#format' => 'full_html',
      '#default_value' => isset($promotions_email['DE']['value']) ? $promotions_email['DE']['value'] : '',
    ];

    // Stock notify e-mail.
    $form['stock_notify_email'] = [
      '#type' => 'details',
      '#title' => $this->t('Stock notify e-mail'),
      '#description' => $this->t('Add custom text into stock notify e-mail'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $stock_notify_email = $config->get('stock_notify_email');

    $form['stock_notify_email']['en']['subject'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Subject - en'),
      '#default_value' => isset($stock_notify_email['en']['subject']) ? $stock_notify_email['en']['subject'] : '',
      '#size' => 50,
    ];

    $form['stock_notify_email']['en']['message'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Text - en'),
      '#format' => 'full_html',
      '#default_value' => isset($stock_notify_email['en']['message']['value']) ? $stock_notify_email['en']['message']['value'] : '',
    ];

    $form['stock_notify_email']['da']['subject'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Subject - da'),
      '#default_value' => isset($stock_notify_email['da']['subject']) ? $stock_notify_email['da']['subject'] : '',
      '#size' => 50,
    ];

    $form['stock_notify_email']['da']['message'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Text - da'),
      '#format' => 'full_html',
      '#default_value' => isset($stock_notify_email['da']['message']['value']) ? $stock_notify_email['da']['message']['value'] : '',
    ];

    $form['stock_notify_email']['de']['subject'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Subject - de'),
      '#default_value' => isset($stock_notify_email['de']['subject']) ? $stock_notify_email['de']['subject'] : '',
      '#size' => 50,
    ];

    $form['stock_notify_email']['de']['message'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Text - de'),
      '#format' => 'full_html',
      '#default_value' => isset($stock_notify_email['de']['message']['value']) ? $stock_notify_email['de']['message']['value'] : '',
    ];

    // Exchange rates.
    $form['exchange_rates'] = [
      '#type' => 'details',
      '#title' => $this->t('Exchange rates'),
      '#description' => $this->t('Defines the exchange rate for 1 unit of the currency in DKK.'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $exchange_rates = $config->get('exchange_rates');

    $form['exchange_rates']['EUR'] = [
      '#type' => 'textfield',
      '#title' => $this->t('EUR to DKK'),
      '#default_value' => isset($exchange_rates['EUR']) ? $exchange_rates['EUR'] : '',
      '#size' => 10,
    ];

    $form['exchange_rates']['SEK'] = [
      '#type' => 'textfield',
      '#title' => $this->t('SEK to DKK'),
      '#default_value' => isset($exchange_rates['SEK']) ? $exchange_rates['SEK'] : '',
      '#size' => 10,
    ];

    // Order fees.
    $form['order_fees'] = [
      '#type' => 'details',
      '#title' => $this->t('Order fees'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $form['order_fees']['administration_fee'] = [
      '#type' => 'details',
      '#title' => $this->t('Administration fees'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $administration_fee = $config->get('administration_fee');

    $form['order_fees']['administration_fee']['DKK']['range'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Invoice total (DKK)'),
      '#default_value' => isset($administration_fee['DKK']['range']) ? $administration_fee['DKK']['range'] : '',
      '#size' => 10,
    ];

    $form['order_fees']['administration_fee']['DKK']['fee'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Fee (DKK)'),
      '#default_value' => isset($administration_fee['DKK']['fee']) ? $administration_fee['DKK']['fee'] : '',
      '#size' => 10,
    ];

    $form['order_fees']['administration_fee']['EUR']['range'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Invoice total (EUR)'),
      '#default_value' => isset($administration_fee['EUR']['range']) ? $administration_fee['EUR']['range'] : '',
      '#size' => 10,
    ];

    $form['order_fees']['administration_fee']['EUR']['fee'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Fee (EUR)'),
      '#default_value' => isset($administration_fee['EUR']['fee']) ? $administration_fee['EUR']['fee'] : '',
      '#size' => 10,
    ];

    $form['order_fees']['administration_fee']['SEK']['range'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Invoice total (SEK)'),
      '#default_value' => isset($administration_fee['SEK']['range']) ? $administration_fee['SEK']['range'] : '',
      '#size' => 10,
    ];

    $form['order_fees']['administration_fee']['SEK']['fee'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Fee (SEK)'),
      '#default_value' => isset($administration_fee['SEK']['fee']) ? $administration_fee['SEK']['fee'] : '',
      '#size' => 10,
    ];

    // Added costs.
    $form['order_fees']['added_cost'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Added cost price (DKK)'),
      '#default_value' => $config->get('added_cost'),
      '#size' => 10,
    ];

    // VAT.
    $form['order_fees']['vat'] = [
      '#type' => 'textfield',
      '#title' => $this->t('VAT (%)'),
      '#default_value' => $config->get('vat'),
      '#size' => 10,
    ];

    // Balance is overdue notice.
    $form['balance_is_overdue'] = [
      '#type' => 'details',
      '#title' => $this->t('Balance is overdue notification'),
      '#description' => $this->t('Add custom notification text for user with overdue balance'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $balance_is_overdue = $config->get('balance_is_overdue');

    $form['balance_is_overdue']['enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable notifications'),
      '#default_value' => isset($balance_is_overdue['enabled']) ? $balance_is_overdue['enabled'] : '',
    ];

    $form['balance_is_overdue']['EN'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Text - en'),
      '#format' => 'full_html',
      '#default_value' => isset($balance_is_overdue['EN']['value']) ? $balance_is_overdue['EN']['value'] : '',
    ];

    $form['balance_is_overdue']['DA'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Text - da'),
      '#format' => 'full_html',
      '#default_value' => isset($balance_is_overdue['DA']['value']) ? $balance_is_overdue['DA']['value'] : '',
    ];

    $form['balance_is_overdue']['DE'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Text - de'),
      '#format' => 'full_html',
      '#default_value' => isset($balance_is_overdue['DE']['value']) ? $balance_is_overdue['DE']['value'] : '',
    ];
    // Edifact orders ftp connection.
    $form['edifact'] = [
      '#type' => 'details',
      '#title' => $this->t('Ftp connection'),
      '#description' => $this->t('Configure ftp connection to remote server'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $ftp_connection = $config->get('edifact');

    $form['edifact']['server'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Ftp server'),
      '#default_value' => isset($ftp_connection['server']) ? $ftp_connection['server'] : '',
      '#size' => 30,
    ];
    $form['edifact']['username'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Username'),
      '#default_value' => isset($ftp_connection['username']) ? $ftp_connection['username'] : '',
      '#size' => 30,
    ];
    $form['edifact']['password'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Password'),
      '#default_value' => isset($ftp_connection['password']) ? $ftp_connection['password'] : '',
      '#size' => 30,
    ];
    // Samba connection.
    $form['samba'] = [
      '#type' => 'details',
      '#title' => $this->t('Samba connection'),
      '#description' => $this->t('Configure connection to remote computer'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $samba = $config->get('samba');

    $form['samba']['username'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Username'),
      '#default_value' => isset($samba['username']) ? $samba['username'] : '',
      '#size' => 30,
    ];

    $form['samba']['password'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Password'),
      '#default_value' => isset($samba['password']) ? $samba['password'] : '',
      '#size' => 30,
    ];

    $form['samba']['workgroup'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Workgroup'),
      '#default_value' => isset($samba['workgroup']) ? $samba['workgroup'] : '',
      '#size' => 30,
    ];

    $form['samba']['pdf'] = [
      '#type' => 'details',
      '#title' => $this->t('Order PDF files'),
      '#description' => $this->t('Configure connection to remote computer to synchronize PDF files'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $form['samba']['pdf']['host'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Host (IP address of remote computer)'),
      '#default_value' => isset($samba['pdf']['host']) ? $samba['pdf']['host'] : '',
      '#size' => 30,
    ];

    $form['samba']['pdf']['share'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Shared folder'),
      '#default_value' => isset($samba['pdf']['share']) ? $samba['pdf']['share'] : '',
      '#size' => 30,
    ];

    $form['samba']['invoice'] = [
      '#type' => 'details',
      '#title' => $this->t('Order invoices'),
      '#description' => $this->t('Configure connection to remote computer to synchronize invoices'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $form['samba']['invoice']['host'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Host (IP address of remote computer)'),
      '#default_value' => isset($samba['invoice']['host']) ? $samba['invoice']['host'] : '',
      '#size' => 30,
    ];

    $form['samba']['invoice']['share'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Shared folder'),
      '#default_value' => isset($samba['invoice']['share']) ? $samba['invoice']['share'] : '',
      '#size' => 30,
    ];

    // Samba connection.
    $form['theme'] = [
      '#type' => 'details',
      '#title' => $this->t('Theme settings'),
      '#description' => $this->t('Configure theme specific variables'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $theme = $config->get('theme');

    $form['theme']['theme_color'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Theme color'),
      '#default_value' => isset($theme['theme_color']) ? $theme['theme_color'] : '',
      '#description' => $this->t('Insert color HEX code'),
      '#size' => 10,
    ];

    /** @var \Drupal\taxonomy\TermStorageInterface $termStorage */
    $termStorage = $this->entityTypeManager->getStorage('taxonomy_term');
    $categoriesTree = $termStorage->loadTree('categories', 0, NULL, TRUE);
    $options = [];

    foreach ($categoriesTree as $category) {
      $options[$category->id()] = $category->label();
    }

    $form['designer_exclude_categories'] = [
      '#type' => 'details',
      '#title' => $this->t('Designer Exclude Categories'),
      '#description' => $this->t('Designer Exclude Categories'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $form['designer_exclude_categories']['exclude'] = [
      '#type' => 'select',
      '#title' => $this->t('Excluded'),
      '#default_value' => $config->get('designer_exclude_categories'),
      '#options' => $options,
      '#multiple' => TRUE,
      '#size' => 120,
      '#attributes' => [
        'style' => 'height: 240px',
      ],
    ];

    $form['designer_query_maps_id'] = [
      '#type' => 'details',
      '#title' => $this->t('Designer Query Maps'),
      '#description' => $this->t('Set the active query maps.'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $form['designer_query_maps_id']['id'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Designer Query Maps'),
      '#description' => Link::createFromRoute(
        $this->t('See more'),
        'graphql.query_maps'
      ),
      '#default_value' => $config->get('designer_query_maps_id'),
    ];

    // Checkout text.
    $form['checkout'] = [
      '#type' => 'details',
      '#title' => $this->t('Checkout'),
      '#open' => FALSE,
      '#tree' => TRUE,
    ];

    $checkout = $config->get('checkout');

    $form['checkout']['enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable checkout text'),
      '#default_value' => isset($checkout['enabled']) ? $checkout['enabled'] : '',
    ];

    $form['checkout']['EN'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Checkout text - en'),
      '#format' => 'full_html',
      '#default_value' => isset($checkout['EN']['value']) ? $checkout['EN']['value'] : '',
    ];

    $form['checkout']['DA'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Checkout text - da'),
      '#format' => 'full_html',
      '#default_value' => isset($checkout['DA']['value']) ? $checkout['DA']['value'] : '',
    ];

    $form['checkout']['DE'] = [
      '#type' => 'text_format',
      '#title' => $this->t('Checkout text - de'),
      '#format' => 'full_html',
      '#default_value' => isset($checkout['DE']['value']) ? $checkout['DE']['value'] : '',
    ];

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $form_values = $form_state->getValues();

    if (!empty($form_values['exchange_rates'])) {
      $error_msg = $this->t('Exchange rate values must be numeric and decimal points should be used. Commas are not allowed.');

      foreach ($form_values['exchange_rates'] as $key => $value) {
        if (!is_numeric($value)) {
          $form_state->setError($form['exchange_rates'][$key], $error_msg);
        }
      }
    }

    if (!empty($form_values['order_fees']['added_cost'])) {
      $error_msg = $this->t('Added cost price must be numeric and decimal points should be used. Commas are not allowed.');

      if (!is_numeric($form_values['order_fees']['added_cost'])) {
        $form_state->setError($form['order_fees']['added_cost'], $error_msg);
      }
    }

    if (!empty($form_values['order_fees']['administration_fee'])) {
      $error_msg = $this->t('Administration fee values must be numeric and decimal points should be used. Commas are not allowed.');

      foreach ($form_values['order_fees']['administration_fee'] as $currency => $item) {
        foreach ($form_values['order_fees']['administration_fee'][$currency] as $key => $value) {
          if (!is_numeric($value)) {
            $form_state->setError($form['order_fees']['administration_fee'][$currency][$key], $error_msg);
          }
        }
      }
    }

  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this->config('stormtextil_config.settings');
    $form_values = $form_state->getValues();

    $config->set('promotions_email', $form_values['promotions_email'])
      ->set('stock_notify_email', $form_values['stock_notify_email'])
      ->set('exchange_rates', $form_values['exchange_rates'])
      ->set('balance_is_overdue', $form_values['balance_is_overdue'])
      ->set('administration_fee', $form_values['order_fees']['administration_fee'])
      ->set('edifact', $form_values['edifact'])
      ->set('samba', $form_values['samba'])
      ->set('theme', $form_values['theme'])
      ->set('added_cost', $form_values['order_fees']['added_cost'])
      ->set('vat', $form_values['order_fees']['vat'])
      ->set('designer_exclude_categories', array_values($form_values['designer_exclude_categories']['exclude']))
      ->set('designer_query_maps_id', $form_values['designer_query_maps_id']['id'])
      ->set('checkout', $form_values['checkout'])
      ->save();

    Cache::invalidateTags(['designer_exclude_categories']);

    parent::submitForm($form, $form_state);
  }

}
<?php

namespace Drupal\stormtextil_core\Controller;

use Drupal\commerce_shipping\Entity\Shipment;
use Drupal\commerce_shipping\Entity\ShippingMethod;
use Drupal\commerce_shipping\ShipmentItem;
use Drupal\Core\Controller\ControllerBase;
use Drupal\physical\Weight;
use Drupal\physical\WeightUnit;
use Drupal\profile\Entity\Profile;
use EDI\Parser;
use Drupal\commerce_price\Price;
use Drupal\commerce_order\Entity\OrderItem;
use Drupal\commerce_order\Entity\Order;

class EdifactController extends ControllerBase {

  public function parse() {
    $parser = new Parser();
    $ediFile = file_get_contents('./sites/default/files/1509018E1-000523-1611970.EDI');
    $parsedEdiFile = $parser->loadString($ediFile);

    $lineItems = [];
    $orderItems = [];
    $currency = $parsedEdiFile[18][1][1];

    foreach ($parsedEdiFile as $ediElement) {
      switch($ediElement[0]) {
        case 'NAD':
          if ($ediElement[1] == 'DP') {
            $organization = $ediElement[3][0];
            $address_line1 = $ediElement[3][1];
            $postal_local = explode(" ", $ediElement[3][2]);
            $postal_code = $postal_local[0];
            $locality = $postal_local[1];
            $country_code = $ediElement[3][3];
          } else if ($ediElement[1] == 'BY') {
            $billing_address = $ediElement[5];
            $billing_city = $ediElement[6];
            $billing_company = $ediElement[4];
            $billing_zip_code = $ediElement[8];
          };
          break;
        // Name that we are going to use in profile.
        case 'CTA':
          $name = explode(" ", $ediElement[2][1]);
          $given_name = $name[0];
          $family_name = $name[1];
          break;
        case 'TAX':
          if (!isset($tax)) {
            $tax = $ediElement[5][3] / 100;
            break;
          }
        // Name of shipping method.
        case 'ALC':
          $shipping_method_name = $ediElement[2];
          break;
        case 'MOA':
          if($ediElement[1][0] == '8') {
            $shipping_price = $ediElement[1][1];
          }
        // Line item variation.
        case 'PIA':
          if ($ediElement[1] == '5') {
            $sku = $ediElement[2][0];
            $rawProductVariation = $this->entityTypeManager()
              ->getStorage('commerce_product_variation')
              ->loadByProperties([
                'sku' => $sku,
              ]);
            $productVariation = reset($rawProductVariation);
            $lineItems[$productVariation->getTitle()]['variation'] = $productVariation;
          }
          break;
        // Line item quantity.
        case 'QTY':
          $quantity = $ediElement[1][1];
          $lineItems[$productVariation->getTitle()]['quantity'] = $quantity;
          break;
        // Line item price.
        case 'PRI':
          if ($ediElement[1][0] == 'AAA') {
            $price = $ediElement[1][1];
            $lineItems[$productVariation->getTitle()]['price'] = $price;
          }
          break;
        // Number of line items.
        case 'CNT':
          $numberOfLineItems = $ediElement[1][1];
          break;
      }
    }

    // Creating order item for each line item.
    foreach ($lineItems as $lineItem) {
      $orderItem = OrderItem::create([
        'type' => 'default',
        'purchased_entity' => $lineItem['variation'],
        'quantity' => $lineItem['quantity'],
        'unit_price' => new Price($lineItem['price'], $currency),
        'overridden_unit_price' => TRUE,
      ]);
      $orderItem->save();
      $orderItems[] = $orderItem;
    }

    // Creating order.
    $order = Order::create([
      'type' => 'default',
      'mail' => $this->currentUser()->getEmail(),
      'uid' => $this->currentUser()->id(),
      'store_id' => 1,
      'order_items' => [$orderItems[0], $orderItems[1]],
      'placed' => \Drupal::time()->getCurrentTime(),
    ]);
    $order->save();

    // Creating shipment.
    if ($order->get('shipments')->count() == 0) {
      $first_shipment = Shipment::create([
        'type' => 'default',
        'order_id' => $order->id(),
        'title' => 'Shipment',
        'state' => 'ready'
      ]);
      $first_shipment->save();
    }

    foreach ($orderItems as $order_item) {
      $quantity = $order_item->getQuantity();
      $purchased_entity = $order_item->getPurchasedEntity();

      if ($purchased_entity->get('weight')->isEmpty()) {
        $weight = new Weight(1, WeightUnit::GRAM);
      } else {
        $weight_item = $purchased_entity->get('weight')->first();
        $weight = $weight_item->toMeasurement();
      }

      // Creating shipment item.
      $shipment_item = new ShipmentItem([
        'order_item_id' => $order_item ->id(),
        'title' => $purchased_entity->label(),
        'quantity' => $quantity,
        'weight' => $weight->multiply($quantity),
        'declared_value' => $order_item->getTotalPrice(),
      ]);
      $first_shipment->addItem($shipment_item);
    }
    // Creating shipping method.
    $shipping_method = ShippingMethod::create([
      'stores' => 1,
      'name' => $shipping_method_name,
      'plugin' => [
        'target_plugin_id' => 'flat_rate',
        'target_plugin_configuration' => [
          'rate_label' =>'Shipping GG',
          'rate_amount' => [
            'number' => $shipping_price, //TODO: Zameniti sa varijablom
            'currency_code' => $currency
          ]
        ],
      ],
      'status' => TRUE,
      'weight' => 0,
    ]);
    $shipping_method->save();
    // Adding newly created shipment method to shipment.
    $first_shipment->setShippingMethod($shipping_method);

    // Adding amount to shipment.
    $shipping_method_plugin = $shipping_method->getPlugin();
    $shipping_rates = $shipping_method_plugin->calculateRates($first_shipment);
    $shipping_rate = reset($shipping_rates);
    $shipping_service = $shipping_rate->getService()->getId();
    $amount = reset($shipping_rates)->getAmount();
    $first_shipment->setAmount($amount);
    $first_shipment->save();

    $order->set('shipments', [$first_shipment]);
    $order->save();

    // Creating profile using data from EDI file.
    $profile = Profile::create([
      'uid' => $order->getCustomerId(),
      'type' => 'customer',
    ]);
    $profile->address->given_name = $given_name;
    $profile->set('field_address_1', $name);
    $profile->address->family_name = $family_name;
    $profile->address->organization = $organization;
    $profile->set('field_company', $organization);
    $profile->address->country_code = $country_code;
    $profile->set('field_new_country', $country_code);
    $profile->address->locality = $locality;
    $profile->set('field_city', $locality);
    $profile->address->postal_code = $postal_code;
    $profile->set('field_zip_code', $postal_code);
    $profile->address->address_line1 = $address_line1;
    $profile->set('field_address_1', $address_line1);
    $profile->save();

    // Create a billing profile.
    if(empty($order->getBillingProfile())) {
      $billing_profile = Profile::create([
        'type' => 'customer',
        'uid' => $order->getCustomerId(),
      ]);
      $billing_profile->save();
      $billing_profile->set('field_address_1', $billing_address);
      $billing_profile->set('field_city', $billing_city);
      $billing_profile->set('field_company', $billing_company);
      $billing_profile->set('field_zip_code', $billing_zip_code);
      $billing_profile->save();
      $order->setBillingProfile($billing_profile);
      $order->save();
    }

    //TODO: Add other data to profile.

    $first_shipment->setShippingProfile($profile);
    $first_shipment->setShippingService($shipping_service);
    $first_shipment->save();
    $order->set('shipments', $first_shipment);
    // Including tax into price.
    $priceWithTax = $order->getTotalPrice()->getNumber() + ($order->getTotalPrice()->getNumber() * $tax);
    $order->set('total_price', new Price($priceWithTax, $currency));
    $order->save();

    // Checking the number of line items.
    if ($numberOfLineItems == count($orderItems)) {
      $poruka = 'Provera prošla';
    } else {
      $poruka = 'Provera nije prošla';
    }

    return [
      '#markup' => $poruka,
    ];
  }

}
/**
 * Implements hook_preprocess_HOOK().
 */
function green_deal_core_preprocess_commerce_product__teaser(&$variables) {
  $product = $variables['elements']['#commerce_product'];
  $product_variation = reset($product);
  $price = $product_variation->get('price')->number;
  $list_price = $product_variation->get('list_price')->number;

  if ($list_price != NULL) {
    $percentage = round((($list_price - $price) / $list_price) * 100);
    if ($percentage < 10) {
      $percentage = 10;
    }
    $variables['percentage'] = $percentage . '%';
  }
}

function green_deal_core_preprocess_commerce_product__full(&$variables) {
  $product = $variables['elements']['#commerce_product'];
  $product_variation = reset($product);
  $price = $product_variation->get('price')->number;
  $list_price = $product_variation->get('list_price')->number;

  if ($list_price != NULL) {
    $percentage = round((($list_price - $price) / $list_price) * 100);
    if ($percentage < 10) {
      $percentage = 10;
    }
    $variables['percentage'] = $percentage . '%';
  }
}
green_deal_core.test:
  path: '/product_action'
  defaults:
    _controller: '\Drupal\green_deal_core\Controller\ProductActionController::test'
    _title: 'Product action controller'
  requirements:
    _permission: 'access content'
<?php

namespace Drupal\green_deal_core\Controller;

use Drupal\commerce_price\Price;
use Drupal\Core\Controller\ControllerBase;

class ProductActionController extends ControllerBase {

  public function test() {

    $flag_id = 'promotion_akcija';

    $flag_service = \Drupal::service('flag');
    $flag = $flag_service->getFlagById($flag_id);
    $products = $this->entityTypeManager()
      ->getStorage('commerce_product')
      ->loadByProperties([
        'type' => 'default'
      ]);

    $variation = $this->entityTypeManager()
      ->getStorage('commerce_product_variation')
      ->load(1267);

    foreach ($products as $product) {
      if($flag_service->getEntityFlaggings($flag, $product)) {
        $variation = $product->getVariations();
        $variation = reset($variation);
        $price = $variation->getPrice()->getNumber();
        $nesto[] = $price;
        $list_price = ceil($price / 0.9);
        $variation->setListPrice(new Price($list_price, 'RSD'));
        $variation->save();
        $poruka = 'nesto';
      }
    }

    return ([
      '#markup' => $poruka,
    ]);
  }

}
// First we create order items.
    foreach ($lineItems as $lineItem) {
      $orderItem = OrderItem::create([
        'type' => 'default',
        'purchased_entity' => $lineItem['variation'],
        'quantity' => $lineItem['quantity'],
        'unit_price' => new Price($lineItem['price'], $currency),
        'overridden_unit_price' => TRUE,
      ]);
      $orderItem->save();
      $orderItems[] = $orderItem;
    }

// Than we create order.
    $order = Order::create([
      'type' => 'default',
      'mail' => $this->currentUser()->getEmail(),
      'uid' => $this->currentUser()->id(),
      'store_id' => 1,
      'order_items' => [$orderItems[0], $orderItems[1]],
      'placed' => \Drupal::time()->getCurrentTime(),
    ]);
    $order->save();

// Than we create shipment.
    if ($order->get('shipments')->count() == 0) {
      $first_shipment = Shipment::create([
        'type' => 'default',
        'order_id' => $order->id(),
        'title' => 'Shipment',
        'state' => 'ready'
      ]);
      $first_shipment->save();
    }

// After that we create data for shipment item and shipment items.
    foreach ($orderItems as $order_item) {
      $quantity = $order_item->getQuantity();
      $purchased_entity = $order_item->getPurchasedEntity();

      if ($purchased_entity->get('weight')->isEmpty()) {
        $weight = new Weight(1, WeightUnit::GRAM);
      } else {
        $weight_item = $purchased_entity->get('weight')->first();
        $weight = $weight_item->toMeasurement();
      }

      // Creating shipment item.
      $shipment_item = new ShipmentItem([
        'order_item_id' => $order_item ->id(),
        'title' => $purchased_entity->label(),
        'quantity' => $quantity,
        'weight' => $weight->multiply($quantity),
        'declared_value' => $order_item->getTotalPrice(),
      ]);
      $first_shipment->addItem($shipment_item);
    }

//Than we create shipping methods and add them to shipment.
    $shipping_method = ShippingMethod::create([
      'stores' => 1,
      'name' => $shipping_method_name,
      'plugin' => [
        'target_plugin_id' => 'flat_rate',
        'target_plugin_configuration' => [
          'rate_label' =>'Shipping GG',
          'rate_amount' => [
            'number' => $shipping_price, //TODO: Zameniti sa varijablom
            'currency_code' => $currency
          ]
        ],
      ],
      'status' => TRUE,
      'weight' => 0,
    ]);
    $shipping_method->save();
    // Adding newly created shipment method to shipment.
    $first_shipment->setShippingMethod($shipping_method);

// After that we add amount to shipment.
    $shipping_method_plugin = $shipping_method->getPlugin();
    $shipping_rates = $shipping_method_plugin->calculateRates($first_shipment);
    $shipping_rate = reset($shipping_rates);
    $shipping_service = $shipping_rate->getService()->getId();
    $amount = reset($shipping_rates)->getAmount();
    $first_shipment->setAmount($amount);
    $first_shipment->save();

    $order->set('shipments', [$first_shipment]);
    $order->save();

// And finally we create shipping and billing profile.
    $profile = Profile::create([
      'uid' => $order->getCustomerId(),
      'type' => 'customer',
    ]);
    $profile->address->given_name = $given_name;
    $profile->set('field_address_1', $name);
    $profile->address->family_name = $family_name;
    $profile->address->organization = $organization;
    $profile->set('field_company', $organization);
    $profile->address->country_code = $country_code;
    $profile->set('field_new_country', $country_code);
    $profile->address->locality = $locality;
    $profile->set('field_city', $locality);
    $profile->address->postal_code = $postal_code;
    $profile->set('field_zip_code', $postal_code);
    $profile->address->address_line1 = $address_line1;
    $profile->set('field_address_1', $address_line1);
    $profile->save();

    if(empty($order->getBillingProfile())) {
      $billing_profile = Profile::create([
        'type' => 'customer',
        'uid' => $order->getCustomerId(),
      ]);
      $billing_profile->save();
      $billing_profile->set('field_address_1', $billing_address);
      $billing_profile->set('field_city', $billing_city);
      $billing_profile->set('field_company', $billing_company);
      $billing_profile->set('field_zip_code', $billing_zip_code);
      $billing_profile->save();
      $order->setBillingProfile($billing_profile);
      $order->save();
    }

    //TODO: Add other data to profile.

    $first_shipment->setShippingProfile($profile);
    $first_shipment->setShippingService($shipping_service);
    $first_shipment->save();
    $order->set('shipments', $first_shipment);
    // Including tax into price.
    $priceWithTax = $order->getTotalPrice()->getNumber() + ($order->getTotalPrice()->getNumber() * $tax);
    $order->set('total_price', new Price($priceWithTax, $currency));
    $order->save();

{#
/**
 * @file
 * Template for the shipment confirmation.
 *
 * Available variables:
 * - order_entity: The order entity.
 * - shipment_entity: The shipment entity.
 * - shipping_profile: The profile associated with a shipment.
 * - tracking_code: The tracking code associated with the shipment.
 *
 * @ingroup themeable
 */
#}
{% set shipmentItemCount = shipment_entity.getItems|length %}
<table style="margin: 15px auto 0 auto; max-width: 768px; font-family: arial,sans-serif">
  <tbody>
  <tr>
    <td>
      <table style="margin-left: auto; margin-right: auto; max-width: 768px; text-align: center;">
        <tbody>
        <tr>
          <td>
            <a href="{{ url('<front>') }}" style="color: #0e69be; text-decoration: none; font-weight: bold; margin-top: 15px;">{{ order_entity.getStore.label }}</a>
          </td>
        </tr>
        </tbody>
      </table>
      <table style="margin-left: auto; margin-right: auto; min-width: 450px; margin: 5px auto 0 auto; border: 1px solid #cccccc; border-radius: 5px; padding: 40px 30px 30px 30px;">
        <tbody>
        <tr>
          <td style="text-align: center; font-weight: bold; padding-top:15px; padding-bottom: 15px; border-top: 1px solid #cccccc; border-bottom: 1px solid #cccccc">
            {% trans %}
              An item in your order #{{ order_entity.getOrderNumber }} has shipped!
            {% plural shipmentItemCount %}
              Items in your order #{{ order_entity.getOrderNumber }} have shipped!
            {% endtrans %}
          </td>
        </tr>
        <tr>
          <td>
            <table style="width: 100%; padding-top:15px; padding-bottom: 15px; text-align: left; border-bottom: 1px solid #cccccc">
              <tbody>
              <tr>
                <td style="font-weight: bold; padding-bottom: 15px; text-align: left; vertical-align: top;">
                  {{ 'Shipped to:'|t }}
                </td>
              </tr>
              <tr>
                <td>
                  {% block shipping_profile %}
                    {{ shipping_profile }}
                  {% endblock %}
                </td>
              </tr>
              </tbody>
            </table>
          </td>
        </tr>
        <tr>
          <td>
            {% block shipment_items %}
              <table style="padding-top: 15px; padding-bottom:15px; width: 100%">
                <tbody style="text-align: left;">
                <tr>
                  <td colspan="2" style="font-weight: bold; padding-bottom: 15px; text-align: left; vertical-align: top;">
                    {% trans %}
                      Item in shipment
                    {% plural shipmentItemCount %}
                      Items in shipment
                    {% endtrans %}
                  </td>
                </tr>
                {% for shipment_item in shipment_entity.getItems() %}
                  <tr>
                    <td>
                      {{ shipment_item.quantity|number_format }} x
                    </td>
                    <td>
                      <span>{{ shipment_item.title }}</span>
                    </td>
                  </tr>
                {% endfor %}
                </tbody>
              </table>
            {% endblock %}
          </td>
        </tr>
        {% if (tracking_code) %}
          {% block tracking_info %}
            <tr>
              <td style="font-weight: bold; padding-top:15px; padding-bottom: 15px; text-align: left; vertical-align: top; border-top: 1px solid #cccccc">
                {{ 'Tracking information:'|t }}
              </td>
            </tr>
            <tr>
              <td style="padding-bottom: 15px;">
                {{ tracking_code }}
              </td>
            </tr>
            <tr>
              <td style="padding-top:15px; padding-bottom: 15px; text-align: center; border-top: 1px solid #cccccc">
                {{ 'Thank you for your order!'|t }}
              </td>
            </tr>
          {% endblock %}
        {% endif %}
        </tbody>
      </table>
    </td>
  </tr>
  </tbody>
</table>
	/**
 * Implements hook_theme().
 */
function commerce_shipping_theme() {
  return [
    'commerce_shipment' => [
      'render element' => 'elements',
    ],
    'commerce_shipment_confirmation' => [
      'variables' => [
        'order_entity' => NULL,
        'shipment_entity' => NULL,
        'shipping_profile' => NULL,
        'tracking_code' => NULL,
      ],
    ],
  ];
}
<?php

namespace Drupal\commerce_shipping\Mail;

use Drupal\commerce\MailHandlerInterface;
use Drupal\commerce_shipping\Entity\ShipmentInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;

class ShipmentConfirmationMail implements ShipmentConfirmationMailInterface {

  use StringTranslationTrait;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The mail handler.
   *
   * @var \Drupal\commerce\MailHandlerInterface
   */
  protected $mailHandler;

  /**
   * Constructs a new ShipmentConfirmationMail object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   * @param \Drupal\commerce\MailHandlerInterface $mail_handler
   *   The mail handler.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager, MailHandlerInterface $mail_handler) {
    $this->entityTypeManager = $entity_type_manager;
    $this->mailHandler = $mail_handler;
  }

  /**
   * {@inheritdoc}
   */
  public function send(ShipmentInterface $shipment, $to = NULL, $bcc = NULL) {
    /** @var \Drupal\commerce_order\Entity\OrderInterface $order */
    $order = $shipment->getOrder();
    $to = isset($to) ? $to : $order->getEmail();
    if (!$to) {
      // The email should not be empty.
      return FALSE;
    }

    $subject = $this->formatPlural(
      $shipment->get('items')->count(),
      'An item for order #@number shipped!',
      'Items for your order #@number shipped!',
      ['@number' => $order->getOrderNumber()]
    );

    $profile_view_builder = $this->entityTypeManager->getViewBuilder('profile');
    $shipment_view_builder = $this->entityTypeManager->getViewBuilder('commerce_shipment');
    $body = [
      '#theme' => 'commerce_shipment_confirmation',
      '#order_entity' => $order,
      '#shipment_entity' => $shipment,
      '#shipping_profile' => $profile_view_builder->view($shipment->getShippingProfile()),
      '#tracking_code' => $shipment_view_builder->viewField($shipment->get('tracking_code'), 'default'),
    ];

    $params = [
      'id' => 'shipment_confirmation',
      'from' => $order->getStore()->getEmail(),
      'bcc' => $bcc,
      'order' => $order,
      'shipment' => $shipment,
    ];
    $customer = $order->getCustomer();
    if ($customer->isAuthenticated()) {
      $params['langcode'] = $customer->getPreferredLangcode();
    }

    return $this->mailHandler->sendMail($to, $subject, $body, $params);
  }

}
$url = "https://jsonplaceholder.typicode.com/posts";
$data = file_get_contents($url);
$characters = json_decode($data);
<?php

namespace Drupal\stormtextil_synchronization\Controller;

use Drupal\commerce_shipping\Entity\Shipment;
use Drupal\commerce_shipping\Entity\ShippingMethod;
use Drupal\commerce_shipping\ShipmentItem;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\physical\Weight;
use Drupal\physical\WeightUnit;
use Drupal\profile\Entity\Profile;
use EDI\Parser;
use Drupal\commerce_price\Price;
use Drupal\commerce_order\Entity\OrderItem;
use Drupal\commerce_order\Entity\Order;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class Synchronize Edifact Orders.
 *
 * @package Drupal\stormtextil_synchronization\Controller
 */
class SynchronizeEdifactOrders extends ControllerBase {

  /**
   * The time service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected $time;

  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $config;

  /**
   * Logger interface.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * Constructs Synchronize Edifact Orders.
   *
   * @param \Drupal\Component\Datetime\TimeInterface $time
   *   The Time service.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $configFactory
   *   The config factory.
   * @param \Psr\Log\LoggerInterface $logger
   *   Logger interface.
   */
  public function __construct(TimeInterface $time, ConfigFactoryInterface $configFactory, LoggerInterface $logger) {
    $this->time = $time;
    $this->config = $configFactory;
    $this->logger = $logger;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('datetime.time'),
      $container->get('config.factory'),
      $container->get('logger.channel.default')
    );
  }

  /**
   * Parse the edi file and create an order.
   *
   * @return string[]|void
   *   Response.
   *
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Core\Entity\EntityStorageException
   * @throws \Drupal\Core\TypedData\Exception\MissingDataException
   */
  public function parse() {
    // Login information.
    $login_data = $this->config->get('stormtextil_config.settings');
    $ftp_server = $login_data->get('edifact')['server'];
    $ftp_user = $login_data->get('edifact')['username'];
    $ftp_pass = $login_data->get('edifact')['password'];
    // Set up a connection or die.
    $ftp = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
    // Try to login.
    if (ftp_login($ftp, $ftp_user, $ftp_pass)) {
      echo "Connected as $ftp_user@$ftp_server\n";
    }
    else {
      echo "Couldn't connect as $ftp_user\n";
    }
    // Turn passive mode on,
    // e have to use passive mode because the,
    // running docker container is listening on a different port.
    ftp_set_option($ftp, FTP_USEPASVADDRESS, FALSE);
    ftp_pasv($ftp, TRUE);
    // Listing all companies in root folder.
    $companies = ftp_nlist($ftp, '/');
    foreach ($companies as $company) {
      // Check if this is a valid C5 ID.
      if (is_numeric(basename($company))) {
        $company_id = basename($company);
      }
      // Listing all files in stores directory.
      $files = ftp_nlist($ftp, './' . $company_id . '/archive/');
      foreach ($files as $file) {
        if ((preg_match('/^.*\.(edi)$/i', $file))) {
          // Edi file for proceeding the order.
          $ediFile = file_get_contents('ftp://' . $ftp_user . ':' . $ftp_pass . '@' . $ftp_server . '/'
            . $company_id . '/archive/' . basename($file));
          // Parsing the file.
          $parser = new Parser();
          $parsedEdiFile = $parser->loadString($ediFile);

          $lineItems = [];
          $orderItems = [];
          // Looping through all parsed EDI elements and taking
          // data for order information.
          foreach ($parsedEdiFile as $ediElement) {
            switch ($ediElement[0]) {
              // Delivery information.
              case 'NAD':
                if ($ediElement[1] == 'DP') {
                  $organization = $ediElement[3][0];
                  $address_line1 = $ediElement[3][1];
                  $postal_local = explode(" ", $ediElement[3][2]);
                  $postal_code = $postal_local[0];
                  $locality = $postal_local[1];
                  $country_code = $ediElement[3][3];
                }
                elseif ($ediElement[1] == 'BY') {
                  $billing_address = $ediElement[5];
                  $billing_city = $ediElement[6];
                  $billing_company = $ediElement[4];
                  $billing_zip_code = $ediElement[8];
                };
                break;

              // Name that we are going to use in shipment profile.
              case 'CTA':
                $name = explode(" ", $ediElement[2][1]);
                $given_name = $name[0];
                $family_name = $name[1];
                break;

              // Currency code.
              case 'CUX':
                $currency = $ediElement[1][1];
                break;

              // Tax percentage.
              case 'TAX':
                if (!isset($tax)) {
                  $tax = $ediElement[5][3] / 100;
                }
                break;

              // Name of shipping method.
              case 'ALC':
                $shipping_method_name = $ediElement[2];
                break;

              // Shipping price.
              case 'MOA':
                if ($ediElement[1][0] == '8') {
                  $shipping_price = $ediElement[1][1];
                }
                break;

              // Line item variation.
              case 'PIA':
                if ($ediElement[1] == '5') {
                  $sku = $ediElement[2][0];
                  $rawProductVariation = $this->entityTypeManager()
                    ->getStorage('commerce_product_variation')
                    ->loadByProperties([
                      'sku' => $sku,
                    ]);
                  $productVariation = reset($rawProductVariation);
                  $lineItems[$productVariation->getTitle()]['variation'] = $productVariation;
                }
                break;

              // Line item quantity.
              case 'QTY':
                $quantity = $ediElement[1][1];
                $lineItems[$productVariation->getTitle()]['quantity'] = $quantity;
                break;

              // Line item price.
              case 'PRI':
                if ($ediElement[1][0] == 'AAA') {
                  $price = $ediElement[1][1];
                  $lineItems[$productVariation->getTitle()]['price'] = $price;
                }
                break;

              // Number of line items.
              case 'CNT':
                $numberOfLineItems = $ediElement[1][1];
                break;
            }
          }

          // Creating order items.
          foreach ($lineItems as $lineItem) {
            $orderItem = OrderItem::create([
              'type' => 'default',
              'purchased_entity' => $lineItem['variation'],
              'quantity' => $lineItem['quantity'],
              'unit_price' => new Price($lineItem['price'], $currency),
              'overridden_unit_price' => TRUE,
            ]);
            $orderItem->save();
            $orderItems[] = $orderItem;
          }
          // Creating order.
          $order = Order::create([
            'type' => 'default',
            'mail' => $this->currentUser()->getEmail(),
            'uid' => $this->currentUser()->id(),
            'store_id' => 1,
            'order_items' => [$orderItems[0], $orderItems[1]],
            'placed' => $this->time->getCurrentTime(),
          ]);
          $order->save();
          // Creating shipment.
          if ($order->get('shipments')->count() == 0) {
            $first_shipment = Shipment::create([
              'type' => 'default',
              'order_id' => $order->id(),
              'title' => 'Shipment',
              'state' => 'ready',
            ]);
            $first_shipment->save();
          }
          // Caclculating weight for shipment.
          foreach ($orderItems as $order_item) {
            $quantity = $order_item->getQuantity();
            $purchased_entity = $order_item->getPurchasedEntity();

            if ($purchased_entity->get('weight')->isEmpty()) {
              $weight = new Weight(1, WeightUnit::GRAM);
            }
            else {
              $weight_item = $purchased_entity->get('weight')->first();
              $weight = $weight_item->toMeasurement();
            }
            // Creating shipment item.
            $shipment_item = new ShipmentItem([
              'order_item_id' => $order_item->id(),
              'title' => $purchased_entity->label(),
              'quantity' => $quantity,
              'weight' => $weight->multiply($quantity),
              'declared_value' => $order_item->getTotalPrice(),
            ]);
            $first_shipment->addItem($shipment_item);
          }
          // Creating shipping method.
          $shipping_method = ShippingMethod::create([
            'stores' => 1,
            'name' => $shipping_method_name,
            'plugin' => [
              'target_plugin_id' => 'flat_rate',
              'target_plugin_configuration' => [
                'rate_label' => 'Shipping GG',
                'rate_amount' => [
                  'number' => $shipping_price,
                  'currency_code' => $currency,
                ],
              ],
            ],
            'status' => TRUE,
            'weight' => 0,
          ]);
          $shipping_method->save();
          // Adding newly created shipment method to shipment.
          $first_shipment->setShippingMethod($shipping_method);
          // Adding amount to shipment.
          $shipping_method_plugin = $shipping_method->getPlugin();
          $shipping_rates = $shipping_method_plugin->calculateRates($first_shipment);
          $shipping_rate = reset($shipping_rates);
          $shipping_service = $shipping_rate->getService()->getId();
          $amount = reset($shipping_rates)->getAmount();
          $first_shipment->setAmount($amount);
          $first_shipment->save();

          $order->set('shipments', [$first_shipment]);
          $order->save();

          // Creating shipment profile using data from EDI file.
          $shipment_profile = Profile::create([
            'uid' => $order->getCustomerId(),
            'type' => 'customer',
          ]);
          $shipment_profile->address->given_name = $given_name;
          $shipment_profile->set('field_contact_person', implode(" ", $name));
          $shipment_profile->address->family_name = $family_name;
          $shipment_profile->address->organization = $organization;
          $shipment_profile->set('field_company', $organization);
          $shipment_profile->address->country_code = $country_code;
          $shipment_profile->set('field_new_country', $country_code);
          $shipment_profile->address->locality = $locality;
          $shipment_profile->set('field_city', $locality);
          $shipment_profile->address->postal_code = $postal_code;
          $shipment_profile->set('field_zip_code', $postal_code);
          $shipment_profile->address->address_line1 = $address_line1;
          $shipment_profile->set('field_address_1', $address_line1);
          $shipment_profile->save();
          $first_shipment->setShippingProfile($shipment_profile);
          $first_shipment->setShippingService($shipping_service);
          $first_shipment->save();
          $order->set('shipments', $first_shipment);
          // Create a billing profile.
          if (empty($order->getBillingProfile())) {
            $billing_profile = Profile::create([
              'type' => 'customer',
              'uid' => $order->getCustomerId(),
            ]);
            $billing_profile->save();
            $billing_profile->set('field_address_1', $billing_address);
            $billing_profile->set('field_city', $billing_city);
            $billing_profile->set('field_company', $billing_company);
            $billing_profile->set('field_zip_code', $billing_zip_code);
            $billing_profile->save();
            $order->setBillingProfile($billing_profile);
            $order->save();
          }
          // Including tax into price.
          $priceWithTax = $order->getTotalPrice()->getNumber() + ($order->getTotalPrice()->getNumber() * $tax);
          $order->set('total_price', new Price(round($priceWithTax, 2), $currency));
          $order->save();
          // Checking the number of line items.
          if ($numberOfLineItems == count($orderItems)) {
            $poruka = 'Order created.';
          }
          else {
            $poruka = 'Order was not created.';
          }
          // @todo Ovo će trebati da se otkomentariše u nekom momentu.
          // ftp_delete($ftp, $file);.
          return [
            '#markup' => $poruka,
          ];
        }
        else {
          // @todo Create a logic for putting wrong files in the error directory.
          $this->logger->error('Wrong file format');
        }
      }
    }
    // Closing ftp connection.
    ftp_close($ftp);
  }

}
$ediFile = file_get_contents('./sites/default/files/1509018E1-000523-1611970.EDI');
/**
 * Provides My Config Block.
 *
 * @Block(
 *   id = "config_block",
 *   admin_label = @Translation("My Config Block"),
 *   category = @Translation("My Config Block"),
 * )
 */
/*Ovaj kod možemo da pišemo u modules/module.module fajlu ili u themes/module.theme fajlu.
Prvo ide naziv modula (green_deal_core), zatim ide preprocess, i onda naziv template-a kojem hoćemo da prosledimo varijablu (commerce_product__teaser, ovaj template najčešće nalazimo u public_html->themes->custom->templates). Izvorni naziv template-a je sa crticama (-) ali mi to u hook moramo promeniti na underline (_).

Zatim upišemo $varibles['test'] i onda varijablu {{ test }} možemo da koristimo u tom template-u (commerce_product__teaser).

OBAVEZNO MORAMO DA FLAŠUJEMO KEŠ NAKON ŠTO NAPRAVIMO HOOK.
*/

function green_deal_core_preprocess_commerce_product__teaser(&$variables) {
  $variables['test'] = '123';
}
kazan_dizajner.admin_settings:
  path: '/kazan-dizajner/cenovnik'
  defaults:
    _form: '\Drupal\kazan_dizajner\Form\DesignerBlockSettingsForm'
    _title: 'Cenovnik kazana'
  requirements:
    _permission: 'administer kazan dizajner'

kazan_dizajner.send_mail_controller:
  path: '/kreiraj-svoj-kazan/izvestaj'
  defaults:
    _controller: '\Drupal\kazan_dizajner\Controller\SendMailController::sendmail'
    _title: 'Dizajn poslat'
  requirements:
    _role: 'authenticated'

kazan_dizajner.kazani_form:
  path: '/kazani_forma'
  defaults:
    _form: '\Drupal\kazan_dizajner\Form\KazaniForm'
    _title: 'Kazani forma'
  requirements:
    _permission: 'access content'
<?php

namespace Drupal\kazan_dizajner\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class KazaniForm extends FormBase {

  protected $cena;

  public function getFormId(): string
  {
    return 'kazani_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state): array
  {
    $form['kazani_tipovi'] = [
      '#type' => 'radios',
      '#title' => '1. Izaberite model kazana koji želite da kreirate:',
      '#options' => [
        'prevrtac' => 'Kazani prevrtači',
        'praktik' => 'Kazani praktik',
        'profesionalni' => 'Kazani profesionalni',
      ],
    ];
    $form['kazani_prevrtaci_zapremina'] = [
      '#type' => 'radios',
      '#title' => '2. Izaberite zapreminu kotla:',
      '#options' => [
        '_prevrtac_40_litara' => '40 litara',
        '_prevrtac_60_litara' => '60 litara',
        '_prevrtac_80_litara' => '80 litara',
        '_prevrtac_100_litara' => '100 litara'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => ['value' => 'prevrtac']
        ]
      ],
      //TODO: Ne rade conditional fieldovi kada radi ajax
//      '#ajax' => [
//        'callback' => '::myAjaxCallback',
//        'wrapper' => 'edit-output',
//        'progress' => [
//          'type' => 'throbber',
//          'message' => $this->t('Verifying entry...'),
//        ],
//      ]
    ];
    $form['kazani_prevrtaci_debljina_dna'] = [
      '#type' => 'radios',
      '#title' => 'Izaberite debljinu dna kotla:',
      '#options' => [
        '_prevrtac_1_5_mm' => 'Dno kotla - 1.5 mm',
        '_prevrtac_2_mm' => 'Dno kotla - 2 mm',
        '_prevrtac_3_mmm' => 'Dno kotla - 3 mm',
        '_prevrtac_4_mm' => 'Dno kotla - 4 mm'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_prevrtaci_zapremina"]' => [
            ['value' => '_prevrtac_40_litara'],
            ['value' => '_prevrtac_60_litara'],
            ['value' => '_prevrtac_80_litara'],
            ['value' => '_prevrtac_100_litara'],
          ],
          ['input[name="kazani_tipovi"]' => ['value' => 'prevrtac']]
        ]
      ]
    ];
    $form['kazani_prevrtaci_cev'] = [
      '#type' => 'radios',
      '#title' => '3. Izaberite željenu dužinu i prečnik cevi/lule:',
      '#options' => [
        '_prevrtac_fi28x1500mm' => 'Cev/lula - fi 28x1500 mm (STANDARD)',
        '_prevrtac_fi28x2000mm' => 'Cev/lula - fi 28x2000 mm',
        '_prevrtac_fi28x2500mm' => 'Cev/lula - fi 28x2500 mm',
        '_prevrtac_fi28x3000mm' => 'Cev/lula - fi 28x3000 mm',
        '_prevrtac_fi28x3500mm' => 'Cev/lula - fi 28x3500 mm',
        '_prevrtac_fi28x4000mm' => 'Cev/lula - fi 28x4000 mm',
        '_prevrtac_fi40x2000mm' => 'Cev/lula - fi 40x2000 mm',
        '_prevrtac_fi40x2500mm' => 'Cev/lula - fi 40x2500 mm',
        '_prevrtac_fi40x3000mm' => 'Cev/lula - fi 40x3000 mm',
        '_prevrtac_fi40x3500mm' => 'Cev/lula - fi 40x3500 mm',
        '_prevrtac_fi40x4000mm' => 'Cev/lula - fi 40x4000 mm',
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => ['value' => 'prevrtac']
        ],
      ]
    ];
    $form['kazani_prevrtaci_hladnjak'] = [
      '#type' => 'radios',
      '#title' => '4. Izaberite zapreminu i model hladnjaka:',
      '#options' => [
        '_prevrtac_pocinkovani_od_330_litara' => 'Pocinkovani hladnjak od 330 litara (STANDARD)',
        '_praktik_prohromski_od_330_litara' => 'Prohromski hladnjak od 330 litara',
        '_prevrtac_pocinkovani_od_470_litara' => 'Pocinkovani hladnjak od 470 litara',
        '_prevrtac_prohromski_od_470_litara' => 'Prohromski hladnjak od 470 litara'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'prevrtac'],
          ]
        ],
      ]
    ];
    $form['hladnjak_prevrtaci_izmenjivac'] = [
      '#type' => 'radios',
      '#title' => 'Izmenjivač toplote u hladnjaku',
      '#options' => [
        '_prevrtac_spirala_5_navoja' => 'Spirala 5 navoja (STANDARD)',
        '_prevrtac_cilindar_kiler' => 'Doplata za cilindar/kiler'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'prevrtac'],
          ]
        ],
      ]
    ];
    $form['kazani_prevrtaci_mesalica'] = [
      '#type' => 'radios',
      '#title' => '5. Izaberite jednu od varijanti mešalice:',
      '#options' => [
        '_prevrtac_rucna' => 'Ručna mešalica (STANDARD)',
        '_prevrtac_elektricna' => 'Električna mešalica'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'prevrtac'],
          ]
        ],
      ]
    ];
    $form['dodatna_prevrtaci_oprema'] = [
      '#type' => 'checkboxes',
      '#title' => '6. Izaberite potrebnu dodatnu opremu:',
      '#options' => [
        '_prevrtac_alkoholmetar' => 'Alkoholmetar',
        '_prevrtac_sirometar' => 'Sirometar',
        '_prevrtac_plamenik' => 'Plamenik',
        '_prevrtac_levak' => 'Levak',
        '_prevrtac_menzura' => 'Menzura',
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'prevrtac'],
          ]
        ],
      ]
    ];
    // Kazani praktik.
    $form['kazani_praktik_zapremina'] = [
      '#type' => 'radios',
      '#title' => '2. Izaberite zapreminu kotla:',
      '#options' => [
        '_praktik_60_litara' => '60 litara',
        '_praktik_80_litara' => '80 litara',
        '_praktik_100_litara' => '100 litara'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => ['value' => 'praktik']
        ]
      ]
    ];
    $form['kazani_praktik_debljina_dna'] = [
      '#type' => 'radios',
      '#title' => 'Izaberite debljinu dna kotla:',
      '#options' => [
        '_praktik_1_5_mm' => 'Dno kotla - 1.5 mm',
        '_praktik_2_mm' => 'Dno kotla - 2 mm',
        '_praktik_3_mmm' => 'Dno kotla - 3 mm',
        '_praktik_4_mm' => 'Dno kotla - 4 mm'
      ],
      '#states' => [
        'visible' => [
          ':input[name="kazani_praktik_zapremina"]' => [
            ['value' => '_praktik_60_litara'],
            ['value' => '_praktik_80_litara'],
            ['value' => '_praktik_100_litara']
          ],
          [':input[name="kazani_tipovi"]' => ['value' => 'praktik']]
        ]
      ]
    ];
    $form['kazani_praktik_cev'] = [
      '#type' => 'radios',
      '#title' => '3. Izaberite željenu dužinu i prečnik cevi/lule:',
      '#options' => [
        '_praktik_fi40x2000mm' => 'Cev/lula - fi 40x2000 mm (STANDARD)',
        '_praktik_fi40x2500mm' => 'Cev/lula - fi 40x2500 mm',
        '_praktik_fi40x3000mm' => 'Cev/lula - fi 40x3000 mm',
        '_praktik_fi40x3500mm' => 'Cev/lula - fi 40x3500 mm',
        '_praktik_fi40x4000mm' => 'Cev/lula - fi 40x4000 mm',
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => ['value' => 'praktik']
        ],
      ]
    ];
    $form['kazani_praktik_hladnjak'] = [
      '#type' => 'radios',
      '#title' => '4. Izaberite zapreminu i model hladnjaka:',
      '#options' => [
        '_praktik_pocinkovani_od_330_litara' => 'Pocinkovani hladnjak od 330 litara (STANDARD)',
        '_praktik_prohromski_od_330_litara' => 'Prohromski hladnjak od 330 litara',
        '_praktik_pocinkovani_od_470_litara' => 'Pocinkovani hladnjak od 470 litara',
        '_praktik_prohromski_od_470_litara' => 'Prohromski hladnjak od 470 litara'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'praktik'],
          ]
        ],
      ]
    ];
    $form['hladnjak_praktik_izmenjivac'] = [
      '#type' => 'radios',
      '#title' => 'Izmenjivač toplote u hladnjaku',
      '#options' => [
        '_praktik_spirala_5_navoja' => 'Spirala 5 navoja (STANDARD)',
        '_praktik_cilindar_kiler' => 'Doplata za cilindar/kiler'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'praktik'],
          ]
        ],
      ]
    ];
    $form['kazani_praktik_mesalica'] = [
      '#type' => 'radios',
      '#title' => '5. Izaberite jednu od varijanti mešalice:',
      '#options' => [
        '_praktik_rucna' => 'Ručna mešalica (STANDARD)',
        '_praktik_elektricna' => 'Električna mešalica'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'praktik'],
          ]
        ],
      ]
    ];
    $form['dodatna_praktik_oprema'] = [
      '#type' => 'checkboxes',
      '#title' => '6. Izaberite potrebnu dodatnu opremu:',
      '#options' => [
        '_praktik_alkoholmetar' => 'Alkoholmetar',
        '_praktik_sirometar' => 'Sirometar',
        '_praktik_plamenik' => 'Plamenik',
        '_praktik_levak' => 'Levak',
        '_praktik_menzura' => 'Menzura',
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'praktik'],
          ]
        ],
      ]
    ];
    // Kazani profesionalni.
    $form['kazani_profesionalni_zapremina'] = [
      '#type' => 'radios',
      '#title' => '2. Izaberite zapreminu kotla:',
      '#options' => [
        '_profi_80_litara' => '80 litara',
        '_profi_100_litara' => '100 litara',
        '_profi_120_litara' => '120 litara',
        '_profi_160_litara' => '160 litara',
        '_profi_200_litara' => '200 litara',
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => ['value' => 'profesionalni']
        ]
      ]
    ];
    $form['kazani_profesionalni_debljina_dna'] = [
      '#type' => 'radios',
      '#title' => 'Izaberite debljinu dna kotla:',
      '#options' => [
        '_profi_1_5_mm' => 'Dno kotla - 1.5 mm (STANDARD)',
        '_profi_2_mm' => 'Dno kotla - 2 mm',
        '_profi_3_mmm' => 'Dno kotla - 3 mm',
        '_profi_4_mm' => 'Dno kotla - 4 mm',
        '_profi_5_mm' => 'Dno kotla - 5 mm',
      ],
      '#states' => [
        'visible' => [
          ':input[name="kazani_profesionalni_zapremina"]' => [
            ['value' => '_profi_80_litara'],
            ['value' => '_profi_100_litara'],
            ['value' => '_profi_120_litara'],
            ['value' => '_profi_160_litara'],
            ['value' => '_profi_200_litara'],
          ],
          [':input[name="kazani_tipovi"]' => ['value' => 'profesionalni']]
        ],
      ]
    ];
    $form['kazani_profesionalni_cev'] = [
      '#type' => 'radios',
      '#title' => '3. Izaberite željenu dužinu i prečnik cevi/lule:',
      '#options' => [
        '_profi_fi40x2000mm' => 'Cev/lula - fi 40x2000 mm (STANDARD)',
        '_profi_fi40x2500mm' => 'Cev/lula - fi 40x2500 mm',
        '_profi_fi40x3000mm' => 'Cev/lula - fi 40x3000 mm',
        '_profi_fi40x3500mm' => 'Cev/lula - fi 40x3500 mm',
        '_profi_fi40x4000mm' => 'Cev/lula - fi 40x4000 mm',
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => ['value' => 'profesionalni']
        ],
      ]
    ];
    $form['kazani_profesionalni_hladnjak'] = [
      '#type' => 'radios',
      '#title' => '4. Izaberite zapreminu i model hladnjaka:',
      '#options' => [
        '_profi_pocinkovani_od_330_litara' => 'Pocinkovani hladnjak od 330 litara (STANDARD)',
        '_profi_prohromski_od_330_litara' => 'Prohromski hladnjak od 330 litara',
        '_profi_pocinkovani_od_470_litara' => 'Pocinkovani hladnjak od 470 litara',
        '_profi_prohromski_od_470_litara' => 'Prohromski hladnjak od 470 litara'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'profesionalni']
          ]
        ],
      ]
    ];
    $form['hladnjak_profesionalni_izmenjivac'] = [
      '#type' => 'radios',
      '#title' => 'Izmenjivač toplote u hladnjaku',
      '#options' => [
        '_profi_spirala_5_navoja' => 'Spirala 5 navoja (STANDARD)',
        '_profi_cilindar_kiler' => 'Doplata za cilindar/kiler'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'profesionalni']
          ]
        ],
      ]
    ];
    $form['kazani_profesionalni_mesalica'] = [
      '#type' => 'radios',
      '#title' => '5. Izaberite jednu od varijanti mešalice:',
      '#options' => [
        '_profi_rucna' => 'Ručna mešalica (STANDARD)',
        '_profi_elektricna' => 'Električna mešalica'
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'profesionalni']
          ]
        ],
      ]
    ];
    $form['dodatna_profesionalni_oprema'] = [
      '#type' => 'checkboxes',
      '#title' => '6. Izaberite potrebnu dodatnu opremu:',
      '#options' => [
        '_profi_alkoholmetar' => 'Alkoholmetar',
        '_profi_sirometar' => 'Sirometar',
        '_profi_plamenik' => 'Plamenik',
        '_profi_levak' => 'Levak',
        '_profi_menzura' => 'Menzura',
      ],
      '#states' => [
        'visible' => [
          'input[name="kazani_tipovi"]' => [
            ['value' => 'profesionalni']
          ]
        ],
      ]
    ];
    $form['izracunaj_cenu'] = [
      '#type' => 'button',
      '#value' => 'Izracunaj cenu',
      '#ajax' => [
        'callback' => '::cene',
        'wrapper' => 'edit-output',
        'progress' => [
          'type' => 'throbber',
          'message' => $this->t('Verifying entry...'),
        ]
      ]
    ];
    // Order price.
    $form['cena'] = [
      '#type' => 'label',
      '#attributes' => ['id' => 'edit-output'],
      '#title' => 'Cena',
    ];
    // User information.
    $form['emailaddress'] = [
      '#type' => 'email',
      '#title' => 'E-mail (dobićete kopiju gore kreiranog kazana)*'
    ];
    $form['phone'] = [
      '#type' => 'tel',
      '#title' => 'Broj telefona*'
    ];
    $form['message'] = [
      '#type' => 'textarea',
      '#title' => 'Poruka*'
    ];
    $form['actions']['#type'] = 'actions';
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save'),
      '#button_type' => 'primary'
    ];

    return $form;
  }

  public static function cene(array &$form, FormStateInterface $form_state) {
    $config = \Drupal::config('kazan_dizajner.settings');
    $cena = '';
    $oprema_cena = '';
    // Fetching users input for acquiring each item price.
    if ($form_state->getUserInput()['kazani_tipovi'] == 'prevrtac') {
      $zapremina = $form_state->getUserInput()['kazani_prevrtaci_zapremina'];
      ($zapremina) ? $form_state->getUserInput()['kazani_prevrtaci_zapremina'] : '';
      $dno = $form_state->getUserInput()['kazani_prevrtaci_debljina_dna'];
      ($dno) ? $form_state->getUserInput()['kazani_prevrtaci_debljina_dna'] : '';
      $cev = $form_state->getUserInput()['kazani_prevrtaci_cev'];
      ($cev) ? $form_state->getUserInput()['kazani_prevrtaci_cev'] : '';
      $hladnjak = $form_state->getUserInput()['kazani_prevrtaci_hladnjak'];
      ($hladnjak) ? $form_state->getUserInput()['kazani_prevrtaci_hladnjak'] : '';
      $izmenjivac = $form_state->getUserInput()['hladnjak_prevrtaci_izmenjivac'];
      ($izmenjivac) ? $form_state->getUserInput()['hladnjak_prevrtaci_izmenjivac'] : '';
      $mesalica = $form_state->getUserInput()['kazani_prevrtaci_mesalica'];
      ($mesalica) ? $form_state->getUserInput()['kazani_prevrtaci_mesalica'] : '';
      $dodaci = $form_state->getUserInput()['dodatna_prevrtaci_oprema'];
      foreach ($dodaci as $dodatak) {
        if ($dodatak != NULL) {
          $oprema_cena += $config->get($dodatak);
        }
      }
    } else if ($form_state->getUserInput()['kazani_tipovi'] == 'praktik') {
      $zapremina = $form_state->getUserInput()['kazani_praktik_zapremina'];
      ($zapremina) ? $form_state->getUserInput()['kazani_prevrtaci_zapremina'] : '';
      $dno = $form_state->getUserInput()['kazani_praktik_debljina_dna'];
      ($dno) ? $form_state->getUserInput()['kazani_praktik_debljina_dna'] : '';
      $cev = $form_state->getUserInput()['kazani_praktik_cev'];
      ($cev) ? $form_state->getUserInput()['kazani_praktik_cev'] : '';
      $hladnjak = $form_state->getUserInput()['kazani_praktik_hladnjak'];
      ($hladnjak) ? $form_state->getUserInput()['kazani_praktik_hladnjak'] : '';
      $izmenjivac = $form_state->getUserInput()['hladnjak_praktik_izmenjivac'];
      ($izmenjivac) ? $form_state->getUserInput()['hladnjak_praktik_izmenjivac'] : '';
      $mesalica = $form_state->getUserInput()['kazani_praktik_mesalica'];
      ($mesalica) ? $form_state->getUserInput()['kazani_praktik_mesalica'] : '';
      $dodaci = $form_state->getUserInput()['dodatna_praktik_oprema'];
      foreach ($dodaci as $dodatak) {
        if ($dodatak != NULL) {
          $oprema_cena += $config->get($dodatak);
        }
      }
    } else {
      $zapremina = $form_state->getUserInput()['kazani_profesionalni_zapremina'];
      ($zapremina) ? $form_state->getUserInput()['kazani_profesionalni_zapremina'] : '';
      $dno = $form_state->getUserInput()['kazani_profesionalni_debljina_dna'];
      ($dno) ? $form_state->getUserInput()['kazani_profesionalni_debljina_dna'] : '';
      $cev = $form_state->getUserInput()['kazani_profesionalni_cev'];
      ($cev) ? $form_state->getUserInput()['kazani_profesionalni_cev'] : '';
      $hladnjak = $form_state->getUserInput()['kazani_profesionalni_hladnjak'];
      ($hladnjak) ? $form_state->getUserInput()['kazani_profesionalni_hladnjak'] : '';
      $izmenjivac = $form_state->getUserInput()['hladnjak_profesionalni_izmenjivac'];
      ($izmenjivac) ? $form_state->getUserInput()['hladnjak_profesionalni_izmenjivac'] : '';
      $mesalica = $form_state->getUserInput()['kazani_profesionalni_mesalica'];
      ($mesalica) ? $form_state->getUserInput()['kazani_profesionalni_mesalica'] : '';
      $dodaci = $form_state->getUserInput()['dodatna_profesionalni_oprema'];
      foreach ($dodaci as $dodatak) {
        if ($dodatak != NULL) {
          $oprema_cena += $config->get($dodatak);
        }
      }
    }
    //Calculating total order price.
    $artikli = [];
    array_push($artikli, $zapremina, $dno, $cev, $hladnjak, $izmenjivac, $mesalica);
    foreach($artikli as $artikal) {
      if ($artikal != NULL) {
        $cena += $config->get($artikal);
      }
    }
    $cena += $oprema_cena;

    $form['cena']['#title'] = 'Cena ovog kazana bi iznosila ' . $cena . ' RSD.';
    return $form['cena'];
  }

  public function submitForm(array &$form, FormStateInterface $form_state)
  {
    if ($form_state->getValue)

    $message =
      'Specifikacija kazana' . PHP_EOL . PHP_EOL
    . 'Email: ' . $form_state->getValue('emailaddress') . PHP_EOL
    . 'Telefon: ' . $form_state->getValue('phone') . PHP_EOL
    . 'Poruka: ' . $form_state->getValue('message') . PHP_EOL
    . 'Tip: ' . $form_state->getValue('kazani_tipovi') . PHP_EOL
    . 'Zapremina: ' . $form_state->getValue('');
    $mailManager = \Drupal::service('plugin.manager.mail');
    $module = 'kazan_dizajner';
    $key = 'mail_order';
    $to = $form_state->getValue('emailaddress');
    dsm($form_state->getValue('kazani_tipovi'));

  }
}
musin_core.shipping:
  path: '/get/thread/title'
  defaults:
    _controller: '\Drupal\musin_core\Controller\Thread::getTitle'
  requirements:
    _permission: 'access content'

musin_core.completeness:
  path: '/completeness'
  defaults:
    _controller: '\Drupal\musin_core\Controller\CompletenessController::populateCompleteness'
  requirements:
    _permission: 'access content'
<?php

namespace Drupal\musin_core\Service;

use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountInterface;

class UserHelperService {


  /**
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  public function __construct(AccountInterface $current_user, EntityTypeManagerInterface $entity_type_manager) {
    $this->currentUser = $current_user;
    $this->entityTypeManager = $entity_type_manager;
  }

  public static function getProfileCompleteness($user) {
    $field_weightings = [
      'field_first_name' => 10,
      'field_last_name' => 10,
      'field_city' => 10,
      'field_age' => 10,
      'user_picture' => 10,
      'field_cover_image' => 10,
      'field_genres' => 5,
      'field_instruments' => 5,
      'field_sample_tracks' => 5,
      'field_short_biography' => 5,
      'field_social_media_soundcloud' => 5,
      'field_social_media_spotify' => 5,
      'field_social_media_tiktok' => 5,
      'field_social_media_youtube' => 5,
    ];

    $completeness = 0;

    foreach ($field_weightings as $key => $value) {
      if ($user->hasField($key) && $user->get($key)->isEmpty() === FALSE) {
        $completeness = $completeness + $value;
      }
    }
    return $completeness;
  }
}
<?php

namespace Drupal\musin_core\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\musin_core\Service\UserHelperService;

class CompletenessController extends ControllerBase {

  protected $entityTypeManager;

  public function populateCompleteness()
  {
    $query = \Drupal::entityQuery('user');
    $uids = $query->execute();

    foreach ($uids as $key => $id) {
      $user = \Drupal::entityTypeManager()->getStorage('user')->load($id);
      $result = UserHelperService::getProfileCompleteness($user);
      $user->set('field_completeness', $result);
      $user->save();
    }
    return [];
  }
}
/**
 * Implements hook_entity_presave.
 */
function musin_core_entity_presave(EntityInterface $entity) {
  if ($entity instanceof \Drupal\user\UserInterface) {
    $completeness = \Drupal\musin_core\Service\UserHelperService::getProfileCompleteness($entity);
    $entity->set('field_completeness', $completeness);
    $entity->save();
  }
}
$media = \Drupal\file\Entity\File::load(2); //2 je target_id iz field_image (iz noda npr.).
dsm($media);
$user->set('field_mailchimp_subscription', ['subscribe' => "1"]);
$current_path = $this->request->getCurrentRequest()->headers->get('referer');
$path = explode('8000', $current_path);  
//8000 is just a part of a string, from where we are breaking the string.
$route_name = Url::fromUserInput($path[1])->getRouteName();
return $this->redirect($route_name, ['user' => $user->id()]);
name: Subscribe block
type: module
description: Define a custom block for applying for subscription.
core_version_requirement: ^8 || ^9
package: Custom
dependencies:
  - block
<?php

namespace Drupal\bacademy_core\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\Url;
use Drupal\user\Entity\User;

class SubscribeController extends ControllerBase {

  public function __construct(EntityTypeManager $entityTypeManager) {
    $this->entityTypeManager = $entityTypeManager;
  }

  public function subscribe(int $id) {
    $user = $this->entityTypeManager->getStorage('user')->load($id);
    /** @var User $user */
    $subscribed = $user->get('field_mailchimp_subscription')[0]->get('subscribe')->getValue();
    if ($subscribed != "1") {
      $user->set('field_mailchimp_subscription', ['subscribe' => "1"] );
      $user->save();
      return Url::fromRoute('entity.user.canonical', ['user' => $user->id()])->toString();
    } else {
      return Url::fromRoute('entity.user.canonical', ['user' => $user->id()])->toString();
    }
  }
}
<?php

namespace Drupal\bacademy_core\Plugin\Block;

use Drupal\bacademy_core\Controller\SubscribeController;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
 * Provides a 'Subscribe' block.
 *
 * @Block(
 *   id = "subscribe_block",
 *   admin_label= @Translation("Subscribe"),
 *   category= @Translation("Subscribe"),
 * )
 */
class SubscribeBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Entity type manager.
   *
   * @var EntityTypeManager
   */
  protected $entityTypeManager;

  public function __construct(array $configuration, $plugin_id, $plugin_definition, AccountProxyInterface $current_user, EntityTypeManager $entityTypeManager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->currentUser = $current_user;
    $this->entityTypeManager = $entityTypeManager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition){
    return new static (
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('current_user'),
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritDoc}
   */
  public function build() {
    // Check if current user is subscribed.
    $user = $this->entityTypeManager
      ->getStorage('user')
      ->loadByProperties([
        'uid' => $this->currentUser->id(),
      ]);
    $user = reset($user);
    $subscribed = 0;
    if ($user->hasField('field_mailchimp_subscription')) {
      $subscribed = $user->get('field_mailchimp_subscription')[0]->get('subscribe')->getValue();
    }
    if ($subscribed == "1") {
      return [];
    } else {
      return [
        '#type' => 'inline_template',
        '#template' => "<div>
                        <p>Opt in and don't miss out on the latest from the Academy.</p>
                        <a href='{{ controller_link }}'>YES PLEASE</a>
                        <a href='#'>NO THANKS</a>
                      </div>",
        '#context' => [
          'controller_link' => Url::fromRoute('bacademy_core.subscription', ['id' => $this->currentUser->id()])->toString(),
        ],
      ];
    }
  }
}
//If we don't want to cache anonymus user choices or content
//than we add next line of code in mymodule.routing.yml file
//for the specified page

no_cache: 'TRUE'
    /** @var \Drupal\bacademy_cpd\Entity\CpdPoints $cpd_record */
    foreach ($cpd_records as $cpd_record) {
      $completed_node = $cpd_record->get('node')->entity;
      /** @var \Drupal\node\Entity\Node $completed_node */
      $completed_nodeID = $completed_node->get('nid')->value;
// clear that cache
composer create-project drupal/recommended-project myproject -n
cd myproject
lando init --source cwd --recipe drupal8 --webroot web --name myproject
lando start


composer require drush/drush drupal/admin_toolbar
drush si --db-url=mysql://drupal8:drupal8@database/drupal8 --account-pass=content -y
drush en admin_toolbar admin_toolbar_tools
drush uli -l http://myproject.lndo.site
function mytheme_preprocess_node(&$variables) {
  switch ($variables['node']->getType()) {
    case "video":
      // ...
    break;
    case "something_else":
      // ...
    break;
  }
}			
function events_preprocess_node(&$variables) {
  // Get route name.
  $routeName = \Drupal::routeMatch()->getRouteName();
  // Get entity.
  $node = &$variables['node'];
  // Check if it's an event.
  if ($node->getType() === 'event' && $node->hasField('field_place')) {
    // Get the place.
    $place = $node->get('field_place')->entity;
    // Check if place is NULL.
    if ($place) {
      if ($node->get('field_teaser_media')->isEmpty()) {
        // Get teaser.
        $variables['place_teaser_media'] = $place
          ->get('field_teaser_media')
          ->view($routeName === 'entity.node.canonical' ? 'default' : 'small_teaser_square');
      }
      // Get organization name from place.
      $variables['place_organization'] = $place
        ->get('field_address')[0]
        ->get('organization')->getValue();
    }
  }
}
global $language;
$lang = $language->language;
$base_node = node_load(XXXXX);

$translations = translation_node_get_translations($base_node->tnid);
$translated_node = (isset($translations[$lang])?node_load($translations[$lang]->nid):$base_node);
star

Wed Jan 19 2022 14:52:39 GMT+0000 (UTC)

#drupal #php
star

Tue Jan 18 2022 08:17:48 GMT+0000 (UTC)

#drupal #php
star

Mon Jan 17 2022 21:39:57 GMT+0000 (UTC)

#drupal #php
star

Fri Jan 14 2022 11:26:54 GMT+0000 (UTC)

#drupal #php
star

Fri Jan 14 2022 08:50:22 GMT+0000 (UTC)

#drupal #php
star

Fri Jan 14 2022 08:49:31 GMT+0000 (UTC)

#drupal #php
star

Thu Jan 13 2022 20:52:16 GMT+0000 (UTC)

#drupal #php
star

Wed Jan 12 2022 22:17:41 GMT+0000 (UTC)

#drupal #php
star

Wed Jan 12 2022 14:52:58 GMT+0000 (UTC)

#drupal #php
star

Wed Jan 12 2022 14:52:18 GMT+0000 (UTC)

#drupal #php
star

Mon Jan 10 2022 12:32:25 GMT+0000 (UTC)

#drupal #php
star

Thu Jan 06 2022 14:52:48 GMT+0000 (UTC)

#drupal #php
star

Tue Jan 04 2022 19:59:01 GMT+0000 (UTC)

#drupal #php
star

Tue Jan 04 2022 15:37:21 GMT+0000 (UTC) https://colorfield.be/blog/lando-configuration-solr7-drupal8-search-api-umami-profile

#solr #drupal
star

Mon Dec 27 2021 14:57:51 GMT+0000 (UTC)

#drupal #php
star

Mon Dec 27 2021 14:57:06 GMT+0000 (UTC)

#drupal #php
star

Sun Dec 26 2021 17:40:07 GMT+0000 (UTC)

#drupal #php
star

Sun Dec 26 2021 17:24:00 GMT+0000 (UTC)

#drupal #php
star

Sun Dec 26 2021 17:23:20 GMT+0000 (UTC)

#drupal #php
star

Sun Dec 26 2021 17:17:51 GMT+0000 (UTC)

#drupal #php
star

Tue Dec 21 2021 20:33:20 GMT+0000 (UTC)

#drupal #php
star

Mon Dec 20 2021 12:19:02 GMT+0000 (UTC)

#drupal #php
star

Mon Dec 20 2021 12:17:31 GMT+0000 (UTC)

#drupal #php
star

Thu Dec 16 2021 14:52:00 GMT+0000 (UTC)

#drupal #php
star

Thu Dec 16 2021 14:51:34 GMT+0000 (UTC)

#drupal #php
star

Thu Dec 16 2021 14:51:00 GMT+0000 (UTC)

#drupal #php
star

Wed Dec 15 2021 14:54:12 GMT+0000 (UTC) https://medium.com/@askibinski/integrating-storybook-with-drupal-ddabfc6c2f9d

#drupal #twig #storybook
star

Wed Dec 15 2021 13:52:07 GMT+0000 (UTC)

#drupal #php
star

Sun Dec 12 2021 14:07:55 GMT+0000 (UTC)

#drupal #php
star

Wed Dec 08 2021 09:37:16 GMT+0000 (UTC) https://drupal.stackexchange.com/questions/239783/how-to-use-dependency-injection-for-plugins-blocks-drupalformbuilder-and

#drupal
star

Mon Dec 06 2021 20:54:35 GMT+0000 (UTC) https://www.drupal.org/project/drupal/issues/3099148

#php #drupal
star

Fri Dec 03 2021 12:23:07 GMT+0000 (UTC)

#php #drupal
star

Fri Sep 03 2021 09:25:59 GMT+0000 (UTC) https://api.drupal.org/api/drupal/modules%21translation%21translation.module/function/translation_node_get_translations/7.x

#drupal #drupal7 #node #translation #languages

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension